From b7a7a53a18bd60c132d0a3e050bfa1125b924d42 Mon Sep 17 00:00:00 2001 From: Greg Wilkins Date: Mon, 24 Jun 2019 17:42:39 +0200 Subject: [PATCH] Jetty 10.0.x reformat (#3812) * Removing Legacy Method Separators * Restyling branch `jetty-9.4.x` * Applying changes highlighted by checkstyle * Removing Legacy Method Separators * Restyling branch `jetty-10.0.x` * Applying checkstyle changes * Applying checkstyle changes * Applying XML restyling * Restyling XML in branch `jetty-10.0.x` * Fixing XML codestyle for IntelliJ * Fixing XML style mistakes * Fixing XML restyling in branch `jetty-10.0.x` * Revert "Applying XML restyling" * Updating checkstyle for XML codestyle * Revert "Restyling XML in branch `jetty-10.0.x`" # Conflicts: # jetty-xml/src/test/resources/org/eclipse/jetty/xml/configureWithAttr.xml # jetty-xml/src/test/resources/org/eclipse/jetty/xml/configureWithElements.xml * Adding back build-resources * Reformatting pom.xml files * Disabling Checkstyle job * fixed empty string on line wrap * reformatted with latest intellij style * misc checkstyle fixes Signed-off-by: Joakim Erdfelt Signed-off-by: Greg Wilkins --- Jenkinsfile | 5 +- aggregates/jetty-websocket-all/pom.xml | 3 +- apache-jsp/pom.xml | 9 +- .../apache/jsp/JettyJasperInitializer.java | 30 +- .../jetty/apache/jsp/JettyTldPreScanned.java | 14 +- .../org/eclipse/jetty/apache/jsp/JuliLog.java | 64 +- .../eclipse/jetty/jsp/JettyJspServlet.java | 44 +- .../jetty/jsp/TestJettyJspServlet.java | 27 +- .../jetty/jsp/TestJettyTldPreScanned.java | 22 +- .../jetty/jsp/TestJspFileNameToClass.java | 19 +- apache-jstl/pom.xml | 56 +- .../org/eclipse/jetty/jstl/JspConfig.java | 2 +- .../eclipse/jetty/jstl/JspIncludeTest.java | 37 +- .../java/org/eclipse/jetty/jstl/JstlTest.java | 57 +- build-resources/jetty-codestyle-intellij.xml | 14 +- build-resources/pom.xml | 4 +- examples/async-rest/async-rest-jar/pom.xml | 3 +- .../asyncrest/AbstractRestServlet.java | 63 +- .../example/asyncrest/AsyncRestServlet.java | 67 +- .../example/asyncrest/SerialRestServlet.java | 45 +- examples/async-rest/async-rest-server/pom.xml | 3 +- .../example/asyncrest/AsyncRestServer.java | 12 +- examples/async-rest/async-rest-webapp/pom.xml | 3 +- examples/async-rest/pom.xml | 3 +- .../jetty/embedded/AsyncEchoServlet.java | 18 +- .../eclipse/jetty/embedded/DumpServlet.java | 10 +- .../eclipse/jetty/embedded/ExampleServer.java | 6 +- .../jetty/embedded/ExampleServerXml.java | 2 +- .../jetty/embedded/FastFileServer.java | 53 +- .../eclipse/jetty/embedded/FileServer.java | 14 +- .../eclipse/jetty/embedded/FileServerXml.java | 4 +- .../eclipse/jetty/embedded/HelloHandler.java | 15 +- .../eclipse/jetty/embedded/HelloServlet.java | 11 +- .../jetty/embedded/HelloSessionServlet.java | 27 +- .../eclipse/jetty/embedded/HelloWorld.java | 13 +- .../eclipse/jetty/embedded/Http2Server.java | 76 +- .../org/eclipse/jetty/embedded/JarServer.java | 7 +- .../jetty/embedded/JettyDistribution.java | 22 +- .../eclipse/jetty/embedded/LikeJettyXml.java | 91 +- .../jetty/embedded/ManyConnectors.java | 26 +- .../eclipse/jetty/embedded/ManyContexts.java | 10 +- .../eclipse/jetty/embedded/ManyHandlers.java | 27 +- .../jetty/embedded/ManyServletContexts.java | 8 +- .../jetty/embedded/MinimalServlets.java | 9 +- .../eclipse/jetty/embedded/OneConnector.java | 2 +- .../eclipse/jetty/embedded/OneContext.java | 10 +- .../eclipse/jetty/embedded/OneHandler.java | 2 +- .../jetty/embedded/OneServletContext.java | 26 +- .../embedded/OneServletContextJmxStats.java | 6 +- .../OneServletContextWithSession.java | 5 +- .../org/eclipse/jetty/embedded/OneWebApp.java | 6 +- .../jetty/embedded/OneWebAppWithJsp.java | 32 +- .../eclipse/jetty/embedded/ProxyServer.java | 5 +- .../eclipse/jetty/embedded/RewriteServer.java | 12 +- .../jetty/embedded/SecuredHelloHandler.java | 6 +- .../jetty/embedded/ServerWithAnnotations.java | 14 +- .../eclipse/jetty/embedded/ServerWithJMX.java | 23 +- .../jetty/embedded/ServerWithJNDI.java | 12 +- .../jetty/embedded/SimplestServer.java | 2 +- .../jetty/embedded/SplitFileServer.java | 8 +- .../jetty/embedded/WebSocketJsrServer.java | 11 +- .../jetty/embedded/WebSocketServer.java | 8 +- .../org/eclipse/jetty/embedded/TestXml.java | 4 +- examples/pom.xml | 3 +- jetty-alpn/jetty-alpn-client/pom.xml | 8 +- .../alpn/client/ALPNClientConnection.java | 1 - .../client/ALPNClientConnectionFactory.java | 7 +- .../jetty-alpn-conscrypt-client/pom.xml | 36 +- .../client/ConscryptClientALPNProcessor.java | 2 +- .../jetty-alpn-conscrypt-server/pom.xml | 30 +- .../server/ConscryptServerALPNProcessor.java | 1 - jetty-alpn/jetty-alpn-java-client/pom.xml | 4 +- .../java/client/JDK9ClientALPNProcessor.java | 9 +- jetty-alpn/jetty-alpn-java-server/pom.xml | 7 +- .../java/server/JDK9ServerALPNProcessor.java | 11 +- .../jetty/alpn/java/server/JDK9ALPNTest.java | 9 +- jetty-alpn/jetty-alpn-server/pom.xml | 14 +- .../alpn/server/ALPNServerConnection.java | 3 +- .../server/ALPNServerConnectionFactory.java | 13 +- jetty-alpn/pom.xml | 4 +- jetty-annotations/pom.xml | 10 +- ...AbstractDiscoverableAnnotationHandler.java | 6 +- .../annotations/AnnotationConfiguration.java | 558 ++++--- .../annotations/AnnotationDecorator.java | 15 +- .../annotations/AnnotationIntrospector.java | 41 +- .../jetty/annotations/AnnotationParser.java | 315 ++-- .../annotations/ClassInheritanceHandler.java | 19 +- ...ContainerInitializerAnnotationHandler.java | 29 +- .../DeclareRolesAnnotationHandler.java | 9 +- .../MultiPartConfigAnnotationHandler.java | 19 +- .../PostConstructAnnotationHandler.java | 49 +- .../PreDestroyAnnotationHandler.java | 48 +- .../ResourceAnnotationHandler.java | 166 +- .../ResourcesAnnotationHandler.java | 22 +- .../annotations/RunAsAnnotationHandler.java | 15 +- .../ServletContainerInitializersStarter.java | 18 +- .../ServletSecurityAnnotationHandler.java | 105 +- .../annotations/WebFilterAnnotation.java | 41 +- .../WebFilterAnnotationHandler.java | 17 +- .../annotations/WebListenerAnnotation.java | 25 +- .../WebListenerAnnotationHandler.java | 12 +- .../annotations/WebServletAnnotation.java | 74 +- .../WebServletAnnotationHandler.java | 15 +- .../src/test/java/org/acme/ClassOne.java | 6 - .../org/eclipse/jetty/annotations/ClassA.java | 26 +- .../org/eclipse/jetty/annotations/ClassB.java | 20 +- .../eclipse/jetty/annotations/FilterC.java | 14 +- .../eclipse/jetty/annotations/InterfaceD.java | 2 - .../eclipse/jetty/annotations/ListenerC.java | 5 +- .../org/eclipse/jetty/annotations/Multi.java | 2 +- .../org/eclipse/jetty/annotations/Sample.java | 2 +- .../eclipse/jetty/annotations/ServletC.java | 15 +- .../eclipse/jetty/annotations/ServletD.java | 6 +- .../TestAnnotationConfiguration.java | 52 +- .../TestAnnotationInheritance.java | 70 +- .../annotations/TestAnnotationParser.java | 61 +- .../TestSecurityAnnotationConversions.java | 79 +- .../annotations/TestServletAnnotations.java | 84 +- .../annotations/resources/ResourceA.java | 34 +- .../annotations/resources/ResourceB.java | 13 +- .../resources/TestResourceAnnotations.java | 21 +- jetty-ant/pom.xml | 2 +- .../jetty/ant/AntMetaInfConfiguration.java | 23 +- .../eclipse/jetty/ant/AntWebAppContext.java | 187 +-- .../jetty/ant/AntWebInfConfiguration.java | 4 +- .../jetty/ant/AntWebXmlConfiguration.java | 16 +- .../org/eclipse/jetty/ant/JettyRunTask.java | 95 +- .../org/eclipse/jetty/ant/JettyStopTask.java | 36 +- .../eclipse/jetty/ant/ServerProxyImpl.java | 164 +- .../eclipse/jetty/ant/types/Attribute.java | 10 +- .../eclipse/jetty/ant/types/Attributes.java | 6 +- .../eclipse/jetty/ant/types/Connector.java | 3 - .../eclipse/jetty/ant/types/Connectors.java | 5 +- .../jetty/ant/types/ContextHandlers.java | 1 - .../ant/types/FileMatchingConfiguration.java | 11 +- .../jetty/ant/types/LoginServices.java | 1 - .../jetty/ant/types/SystemProperties.java | 12 +- .../eclipse/jetty/ant/utils/ServerProxy.java | 7 +- .../org/eclipse/jetty/ant/utils/TaskLog.java | 3 +- .../java/org/eclipse/jetty/ant/AntBuild.java | 48 +- .../eclipse/jetty/ant/JettyAntTaskTest.java | 21 +- jetty-client/pom.xml | 7 +- .../jetty/client/AbstractConnectionPool.java | 16 +- .../client/AuthenticationProtocolHandler.java | 9 +- .../eclipse/jetty/client/ContentDecoder.java | 8 +- .../jetty/client/DuplexConnectionPool.java | 30 +- .../jetty/client/GZIPContentDecoder.java | 2 +- .../org/eclipse/jetty/client/HttpChannel.java | 2 +- .../org/eclipse/jetty/client/HttpClient.java | 29 +- .../eclipse/jetty/client/HttpConnection.java | 2 +- .../org/eclipse/jetty/client/HttpContent.java | 15 +- .../jetty/client/HttpContentResponse.java | 10 +- .../jetty/client/HttpConversation.java | 60 +- .../eclipse/jetty/client/HttpDestination.java | 30 +- .../eclipse/jetty/client/HttpExchange.java | 8 +- .../org/eclipse/jetty/client/HttpProxy.java | 14 +- .../eclipse/jetty/client/HttpReceiver.java | 29 +- .../eclipse/jetty/client/HttpRedirector.java | 14 +- .../org/eclipse/jetty/client/HttpRequest.java | 16 +- .../eclipse/jetty/client/HttpResponse.java | 2 + .../jetty/client/HttpResponseException.java | 2 +- .../org/eclipse/jetty/client/HttpSender.java | 18 +- .../jetty/client/MultiplexConnectionPool.java | 30 +- .../eclipse/jetty/client/ProtocolHandler.java | 2 +- .../jetty/client/ProtocolHandlers.java | 2 +- .../jetty/client/ProxyConfiguration.java | 5 +- .../jetty/client/ResponseNotifier.java | 8 +- .../client/RoundRobinConnectionPool.java | 12 +- .../org/eclipse/jetty/client/Socks4Proxy.java | 2 + .../client/ValidatingConnectionPool.java | 4 +- .../jetty/client/api/Authentication.java | 17 +- .../org/eclipse/jetty/client/api/Request.java | 10 +- .../eclipse/jetty/client/api/Response.java | 2 +- .../org/eclipse/jetty/client/api/Result.java | 8 +- .../dynamic/HttpClientTransportDynamic.java | 22 +- .../client/http/HttpChannelOverHTTP.java | 23 +- .../client/http/HttpReceiverOverHTTP.java | 4 +- .../eclipse/jetty/client/package-info.java | 5 +- .../ProxyProtocolClientConnectionFactory.java | 16 +- .../util/BufferingResponseListener.java | 2 +- .../util/ByteBufferContentProvider.java | 2 + .../client/util/BytesContentProvider.java | 2 + .../client/util/DeferredContentProvider.java | 12 +- .../client/util/DigestAuthentication.java | 26 +- .../client/util/MultiPartContentProvider.java | 28 +- .../util/OutputStreamContentProvider.java | 3 +- .../client/util/PathContentProvider.java | 6 +- .../client/util/SPNEGOAuthentication.java | 11 +- .../client/AbstractHttpClientServerTest.java | 10 +- .../client/ClientConnectionCloseTest.java | 91 +- .../jetty/client/ConnectionPoolTest.java | 27 +- .../jetty/client/ContentResponseTest.java | 33 +- .../jetty/client/EmptyServerHandler.java | 1 - .../jetty/client/ExternalSiteTest.java | 36 +- .../client/HostnameVerificationTest.java | 4 +- .../client/HttpAuthenticationStoreTest.java | 5 +- .../client/HttpClientAsyncContentTest.java | 41 +- .../client/HttpClientAuthenticationTest.java | 101 +- .../client/HttpClientChunkedContentTest.java | 77 +- .../client/HttpClientCustomProxyTest.java | 5 +- .../HttpClientExplicitConnectionTest.java | 4 +- .../jetty/client/HttpClientFailureTest.java | 26 +- .../jetty/client/HttpClientGZIPTest.java | 39 +- .../jetty/client/HttpClientProxyTest.java | 76 +- .../jetty/client/HttpClientRedirectTest.java | 173 ++- .../client/HttpClientSynchronizationTest.java | 12 +- .../jetty/client/HttpClientTLSTest.java | 78 +- .../eclipse/jetty/client/HttpClientTest.java | 650 ++++---- .../jetty/client/HttpClientURITest.java | 124 +- .../HttpClientUploadDuringServerShutdown.java | 31 +- .../client/HttpConnectionLifecycleTest.java | 267 ++-- .../eclipse/jetty/client/HttpCookieTest.java | 155 +- .../jetty/client/HttpRequestAbortTest.java | 224 +-- .../jetty/client/HttpResponseAbortTest.java | 111 +- .../HttpResponseConcurrentAbortTest.java | 79 +- .../eclipse/jetty/client/LivelockTest.java | 34 +- .../client/ServerConnectionCloseTest.java | 16 +- .../eclipse/jetty/client/Socks4ProxyTest.java | 51 +- .../client/TLSServerConnectionCloseTest.java | 17 +- .../client/ValidatingConnectionPoolTest.java | 49 +- .../org/eclipse/jetty/client/api/Usage.java | 109 +- .../http/HttpDestinationOverHTTPTest.java | 68 +- .../client/http/HttpReceiverOverHTTPTest.java | 52 +- .../client/http/HttpSenderOverHTTPTest.java | 2 +- .../jetty/client/jmx/HttpClientJMXTest.java | 8 +- .../client/ssl/NeedWantClientAuthTest.java | 31 +- .../jetty/client/ssl/SslBytesClientTest.java | 27 +- .../jetty/client/ssl/SslBytesServerTest.java | 150 +- .../jetty/client/ssl/SslBytesTest.java | 5 +- .../jetty/client/ssl/SslConnectionTest.java | 3 +- .../util/DeferredContentProviderTest.java | 10 +- .../util/InputStreamContentProviderTest.java | 17 +- .../util/MultiPartContentProviderTest.java | 99 +- .../client/util/SPNEGOAuthenticationTest.java | 5 +- .../client/util/TypedContentProviderTest.java | 25 +- jetty-deploy/pom.xml | 7 +- .../java/org/eclipse/jetty/deploy/App.java | 51 +- .../eclipse/jetty/deploy/AppLifeCycle.java | 50 +- .../org/eclipse/jetty/deploy/AppProvider.java | 9 +- .../jetty/deploy/ConfigurationManager.java | 2 +- .../jetty/deploy/DeploymentManager.java | 126 +- .../PropertiesConfigurationManager.java | 26 +- .../jetty/deploy/bindings/DebugBinding.java | 12 +- .../deploy/bindings/DebugListenerBinding.java | 12 +- .../bindings/GlobalWebappConfigBinding.java | 14 +- .../deploy/bindings/OrderedGroupBinding.java | 35 +- .../deploy/bindings/StandardDeployer.java | 3 +- .../deploy/bindings/StandardStarter.java | 3 +- .../deploy/bindings/StandardStopper.java | 7 +- .../deploy/bindings/StandardUndeployer.java | 3 +- .../org/eclipse/jetty/deploy/graph/Edge.java | 12 +- .../org/eclipse/jetty/deploy/graph/Graph.java | 105 +- .../jetty/deploy/graph/GraphOutputDot.java | 12 +- .../org/eclipse/jetty/deploy/graph/Node.java | 2 +- .../deploy/jmx/DeploymentManagerMBean.java | 4 +- .../deploy/providers/ScanningAppProvider.java | 61 +- .../deploy/providers/WebAppProvider.java | 106 +- .../providers/jmx/WebAppProviderMBean.java | 6 +- .../org/eclipse/jetty/deploy/util/FileID.java | 14 +- .../deploy/AppLifeCyclePathCollector.java | 9 +- .../jetty/deploy/AppLifeCycleTest.java | 59 +- .../jetty/deploy/BadAppDeployTest.java | 14 +- .../DeploymentManagerLifeCyclePathTest.java | 17 +- .../jetty/deploy/DeploymentManagerTest.java | 6 +- .../jetty/deploy/JmxServiceConnection.java | 18 +- .../eclipse/jetty/deploy/MockAppProvider.java | 14 +- .../GlobalWebappConfigBindingTest.java | 13 +- .../eclipse/jetty/deploy/graph/GraphTest.java | 116 +- ...ScanningAppProviderRuntimeUpdatesTest.java | 41 +- .../ScanningAppProviderStartupTest.java | 4 +- .../deploy/providers/WebAppProviderTest.java | 41 +- .../jetty/deploy/test/XmlConfiguredJetty.java | 87 +- jetty-distribution/pom.xml | 4 +- jetty-documentation/pom.xml | 4 +- jetty-fcgi/fcgi-client/pom.xml | 3 +- .../fcgi/client/http/HttpChannelOverFCGI.java | 2 +- .../client/http/HttpConnectionOverFCGI.java | 10 +- .../fcgi/client/http/HttpSenderOverFCGI.java | 4 +- .../jetty/fcgi/generator/ClientGenerator.java | 1 - .../eclipse/jetty/fcgi/generator/Flusher.java | 2 + .../jetty/fcgi/generator/ServerGenerator.java | 2 + .../jetty/fcgi/parser/ClientParser.java | 4 + .../fcgi/parser/ResponseContentParser.java | 8 +- .../fcgi/generator/ClientGeneratorTest.java | 13 +- .../jetty/fcgi/parser/ClientParserTest.java | 2 + .../fcgi/server/HttpChannelOverFCGI.java | 2 +- .../fcgi/server/HttpTransportOverFCGI.java | 8 +- .../fcgi/server/ServerFCGIConnection.java | 4 +- .../server/proxy/FastCGIProxyServlet.java | 33 +- .../server/AbstractHttpClientServerTest.java | 4 +- .../jetty/fcgi/server/EmptyServerHandler.java | 1 - .../server/ExternalFastCGIServerTest.java | 10 +- .../jetty/fcgi/server/HttpClientTest.java | 170 +- .../proxy/DrupalHTTP2FastCGIProxyServer.java | 12 +- .../server/proxy/FastCGIProxyServletTest.java | 53 +- .../fcgi/server/proxy/TryFilesFilterTest.java | 7 +- .../WordPressHTTP2FastCGIProxyServer.java | 13 +- jetty-fcgi/pom.xml | 42 +- .../jetty-gcloud-session-manager/pom.xml | 19 +- .../session/GCloudSessionDataStore.java | 372 +++-- .../GCloudSessionDataStoreFactory.java | 12 +- .../gcloud/session/GCloudSessionTester.java | 21 +- jetty-hazelcast/pom.xml | 3 +- .../session/HazelcastSessionDataStore.java | 81 +- .../HazelcastSessionDataStoreFactory.java | 63 +- .../session/SessionDataSerializer.java | 22 +- .../session/TestHazelcastSessions.java | 101 +- jetty-http-spi/pom.xml | 18 +- .../jetty/http/spi/DelegatingThreadPool.java | 42 +- .../jetty/http/spi/HttpSpiContextHandler.java | 36 +- .../eclipse/jetty/http/spi/JettyExchange.java | 3 +- .../jetty/http/spi/JettyHttpContext.java | 12 +- .../jetty/http/spi/JettyHttpExchange.java | 31 +- .../http/spi/JettyHttpExchangeDelegate.java | 14 +- .../jetty/http/spi/JettyHttpServer.java | 58 +- .../http/spi/JettyHttpServerProvider.java | 13 +- .../jetty/http/spi/JettyHttpsExchange.java | 13 +- .../eclipse/jetty/http/spi/SPIServerTest.java | 73 +- .../TestEndpointMultiplePublishProblem.java | 96 +- .../eclipse/jetty/http/spi/TestSPIServer.java | 81 +- .../org/eclipse/jetty/http/spi/util/Pool.java | 1 - .../jetty/http/spi/util/PrintTask.java | 2 - .../jetty/http/spi/util/SpiConstants.java | 4 +- .../jetty/http/spi/util/SpiUtility.java | 15 +- jetty-http/pom.xml | 14 +- .../jetty/http/BadMessageException.java | 29 +- .../jetty/http/ComplianceViolation.java | 5 + .../jetty/http/CompressedContentFormat.java | 16 +- .../eclipse/jetty/http/CookieCompliance.java | 9 +- .../org/eclipse/jetty/http/CookieCutter.java | 79 +- .../org/eclipse/jetty/http/DateGenerator.java | 46 +- .../org/eclipse/jetty/http/DateParser.java | 56 +- .../eclipse/jetty/http/HostPortHttpField.java | 29 +- .../jetty/http/Http1FieldPreEncoder.java | 35 +- .../eclipse/jetty/http/HttpCompliance.java | 55 +- .../org/eclipse/jetty/http/HttpContent.java | 38 +- .../org/eclipse/jetty/http/HttpCookie.java | 67 +- .../org/eclipse/jetty/http/HttpField.java | 169 +- .../jetty/http/HttpFieldPreEncoder.java | 13 +- .../org/eclipse/jetty/http/HttpFields.java | 333 ++-- .../org/eclipse/jetty/http/HttpGenerator.java | 609 ++++---- .../org/eclipse/jetty/http/HttpHeader.java | 69 +- .../eclipse/jetty/http/HttpHeaderValue.java | 34 +- .../org/eclipse/jetty/http/HttpMethod.java | 83 +- .../org/eclipse/jetty/http/HttpParser.java | 996 ++++++------ .../org/eclipse/jetty/http/HttpScheme.java | 21 +- .../org/eclipse/jetty/http/HttpStatus.java | 178 +-- .../org/eclipse/jetty/http/HttpTokens.java | 139 +- .../java/org/eclipse/jetty/http/HttpURI.java | 572 ++++--- .../org/eclipse/jetty/http/HttpVersion.java | 91 +- .../java/org/eclipse/jetty/http/MetaData.java | 22 +- .../org/eclipse/jetty/http/MimeTypes.java | 502 +++--- .../jetty/http/MultiPartFormInputStream.java | 206 ++- .../eclipse/jetty/http/MultiPartParser.java | 273 ++-- .../jetty/http/PreEncodedHttpField.java | 72 +- .../jetty/http/PrecompressedHttpContent.java | 11 +- .../org/eclipse/jetty/http/QuotedCSV.java | 21 +- .../eclipse/jetty/http/QuotedCSVParser.java | 175 ++- .../eclipse/jetty/http/QuotedQualityCSV.java | 30 +- .../jetty/http/ResourceHttpContent.java | 85 +- .../java/org/eclipse/jetty/http/Syntax.java | 34 +- .../jetty/http/pathmap/MappedResource.java | 2 +- .../jetty/http/pathmap/PathMappings.java | 145 +- .../eclipse/jetty/http/pathmap/PathSpec.java | 33 +- .../jetty/http/pathmap/PathSpecGroup.java | 18 +- .../jetty/http/pathmap/PathSpecSet.java | 6 +- .../jetty/http/pathmap/RegexPathSpec.java | 10 +- .../jetty/http/pathmap/ServletPathSpec.java | 94 +- .../http/pathmap/UriTemplatePathSpec.java | 59 +- .../jetty/http/CookieCutterLenientTest.java | 15 +- .../eclipse/jetty/http/CookieCutterTest.java | 110 +- .../eclipse/jetty/http/DateParserTest.java | 1 - .../jetty/http/GZIPContentDecoderTest.java | 11 +- .../eclipse/jetty/http/HttpCookieTest.java | 50 +- .../org/eclipse/jetty/http/HttpFieldTest.java | 124 +- .../eclipse/jetty/http/HttpFieldsTest.java | 362 +++-- .../jetty/http/HttpGeneratorClientTest.java | 166 +- .../http/HttpGeneratorServerHTTPTest.java | 32 +- .../jetty/http/HttpGeneratorServerTest.java | 151 +- .../eclipse/jetty/http/HttpParserTest.java | 919 ++++++----- .../eclipse/jetty/http/HttpSchemeTest.java | 5 +- .../jetty/http/HttpStatusCodeTest.java | 9 +- .../eclipse/jetty/http/HttpURIParseTest.java | 309 ++-- .../org/eclipse/jetty/http/HttpURITest.java | 269 ++-- .../org/eclipse/jetty/http/MimeTypesTest.java | 54 +- .../jetty/http/MultiPartCaptureTest.java | 19 +- .../http/MultiPartFormInputStreamTest.java | 701 ++++----- .../jetty/http/MultiPartParserTest.java | 386 +++-- .../org/eclipse/jetty/http/QuotedCSVTest.java | 100 +- .../jetty/http/QuotedQualityCSVTest.java | 129 +- .../org/eclipse/jetty/http/SyntaxTest.java | 92 +- .../jetty/http/pathmap/PathMappingsTest.java | 162 +- .../jetty/http/pathmap/PathSpecAssert.java | 2 +- .../jetty/http/pathmap/RegexPathSpecTest.java | 84 +- .../pathmap/ServletPathSpecMatchListTest.java | 45 +- .../pathmap/ServletPathSpecOrderTest.java | 79 +- .../http/pathmap/ServletPathSpecTest.java | 50 +- .../UriTemplatePathSpecBadSpecsTest.java | 8 +- .../http/pathmap/UriTemplatePathSpecTest.java | 154 +- jetty-http2/http2-client/pom.xml | 7 +- .../client/HTTP2ClientConnectionFactory.java | 2 +- .../jetty/http2/client/AbstractTest.java | 1 - .../jetty/http2/client/AsyncIOTest.java | 8 +- .../jetty/http2/client/AsyncServletTest.java | 23 +- .../http2/client/ConnectTimeoutTest.java | 12 +- .../jetty/http2/client/EmptyHttpServlet.java | 1 - .../http2/client/FlowControlStalledTest.java | 7 +- .../http2/client/FlowControlStrategyTest.java | 20 +- .../http2/client/FlowControlWindowsTest.java | 6 +- .../eclipse/jetty/http2/client/HTTP2Test.java | 10 +- .../jetty/http2/client/IdleTimeoutTest.java | 15 +- .../jetty/http2/client/InterleavingTest.java | 14 +- .../jetty/http2/client/InvalidServerTest.java | 6 +- .../http2/client/MaxPushedStreamsTest.java | 82 +- .../eclipse/jetty/http2/client/PingTest.java | 7 +- .../jetty/http2/client/PrefaceTest.java | 19 +- .../jetty/http2/client/PriorityTest.java | 9 +- .../jetty/http2/client/ProxyProtocolTest.java | 22 +- .../eclipse/jetty/http2/client/ProxyTest.java | 5 +- .../http2/client/PushCacheFilterTest.java | 3 +- .../jetty/http2/client/RawHTTP2ProxyTest.java | 10 +- .../http2/client/SessionFailureTest.java | 10 +- .../http2/client/SmallThreadPoolLoadTest.java | 36 +- .../jetty/http2/client/StreamCloseTest.java | 11 +- .../jetty/http2/client/StreamCountTest.java | 9 +- .../jetty/http2/client/StreamResetTest.java | 30 +- .../jetty/http2/client/TrailersTest.java | 5 +- .../http2/BufferingFlowControlStrategy.java | 12 +- .../org/eclipse/jetty/http2/HTTP2Cipher.java | 579 ++++--- .../eclipse/jetty/http2/HTTP2Connection.java | 6 +- .../org/eclipse/jetty/http2/HTTP2Flusher.java | 48 +- .../org/eclipse/jetty/http2/HTTP2Session.java | 30 +- .../org/eclipse/jetty/http2/HTTP2Stream.java | 20 +- .../org/eclipse/jetty/http2/ISession.java | 20 +- .../java/org/eclipse/jetty/http2/IStream.java | 2 +- .../org/eclipse/jetty/http2/api/Session.java | 45 +- .../org/eclipse/jetty/http2/api/Stream.java | 28 +- .../api/server/ServerSessionListener.java | 1 + .../jetty/http2/frames/GoAwayFrame.java | 10 +- .../jetty/http2/frames/HeadersFrame.java | 12 +- .../jetty/http2/frames/PrefaceFrame.java | 4 +- .../jetty/http2/frames/SettingsFrame.java | 2 +- .../http2/generator/HeadersGenerator.java | 2 +- .../jetty/http2/parser/HeaderBlockParser.java | 2 +- .../http2/parser/SettingsBodyParser.java | 4 +- .../http2/frames/ContinuationParseTest.java | 9 +- .../http2/frames/DataGenerateParseTest.java | 9 +- .../http2/frames/GoAwayGenerateParseTest.java | 9 +- .../frames/HeadersGenerateParseTest.java | 9 +- .../http2/frames/MaxFrameSizeParseTest.java | 2 + .../http2/frames/PingGenerateParseTest.java | 9 +- .../frames/PriorityGenerateParseTest.java | 5 +- .../frames/PushPromiseGenerateParseTest.java | 7 +- .../http2/frames/ResetGenerateParseTest.java | 5 +- .../frames/SettingsGenerateParseTest.java | 17 +- .../jetty/http2/frames/UnknownParseTest.java | 4 + .../frames/WindowUpdateGenerateParseTest.java | 5 +- .../jetty/http2/hpack/AuthorityHttpField.java | 14 +- .../jetty/http2/hpack/HpackContext.java | 316 ++-- .../jetty/http2/hpack/HpackDecoder.java | 143 +- .../jetty/http2/hpack/HpackEncoder.java | 279 ++-- .../jetty/http2/hpack/HpackException.java | 13 +- .../http2/hpack/HpackFieldPreEncoder.java | 53 +- .../eclipse/jetty/http2/hpack/Huffman.java | 654 ++++---- .../jetty/http2/hpack/MetaDataBuilder.java | 96 +- .../jetty/http2/hpack/NBitInteger.java | 76 +- .../http2/hpack/StaticTableHttpField.java | 26 +- .../jetty/http2/hpack/HpackContextTest.java | 499 +++--- .../jetty/http2/hpack/HpackDecoderTest.java | 308 ++-- .../jetty/http2/hpack/HpackEncoderTest.java | 248 ++- .../jetty/http2/hpack/HpackPerfTest.java | 75 +- .../eclipse/jetty/http2/hpack/HpackTest.java | 172 +-- .../jetty/http2/hpack/HuffmanTest.java | 54 +- .../jetty/http2/hpack/NBitIntegerTest.java | 232 ++- .../http2-http-client-transport/pom.xml | 7 +- .../client/http/HttpChannelOverHTTP2.java | 6 +- .../client/http/HttpConnectionOverHTTP2.java | 14 +- .../client/http/DirectHTTP2OverTLSTest.java | 7 +- .../http2/client/http/EmptyServerHandler.java | 1 - .../HttpClientTransportOverHTTP2Test.java | 77 +- .../client/http/MaxConcurrentStreamsTest.java | 148 +- .../client/http/PushedResourcesTest.java | 75 +- jetty-http2/http2-server/pom.xml | 7 +- .../AbstractHTTP2ServerConnectionFactory.java | 12 +- .../server/HTTP2CServerConnectionFactory.java | 17 +- .../http2/server/HTTP2ServerConnection.java | 20 +- .../server/HTTP2ServerConnectionFactory.java | 4 +- .../http2/server/HttpChannelOverHTTP2.java | 40 +- .../http2/server/HttpTransportOverHTTP2.java | 20 +- .../http2/server/AbstractServerTest.java | 5 +- .../eclipse/jetty/http2/server/CloseTest.java | 7 +- .../jetty/http2/server/HTTP2CServer.java | 23 +- .../jetty/http2/server/HTTP2CServerTest.java | 20 +- .../jetty/http2/server/HTTP2ServerTest.java | 36 +- jetty-infinispan/infinispan-common/pom.xml | 25 +- .../infinispan/InfinispanSessionData.java | 6 +- .../InfinispanSessionDataStore.java | 247 ++- .../InfinispanSessionDataStoreFactory.java | 23 +- .../InfinispanSessionLegacyConverter.java | 68 +- .../session/infinispan/QueryManager.java | 1 + .../infinispan/SessionDataMarshaller.java | 4 +- .../infinispan-embedded-query/pom.xml | 45 +- .../infinispan/EmbeddedQueryManager.java | 20 +- .../EmbeddedQueryManagerFactory.java | 3 +- .../infinispan/EmbeddedQueryManagerTest.java | 30 +- jetty-infinispan/infinispan-embedded/pom.xml | 33 +- .../infinispan-remote-query/pom.xml | 53 +- .../infinispan/RemoteQueryManager.java | 23 +- .../infinispan/RemoteQueryManagerFactory.java | 3 +- .../infinispan/RemoteQueryManagerTest.java | 46 +- jetty-infinispan/infinispan-remote/pom.xml | 55 +- jetty-io/pom.xml | 3 +- .../jetty/io/AbstractByteBufferPool.java | 2 + .../eclipse/jetty/io/AbstractConnection.java | 33 +- .../eclipse/jetty/io/AbstractEndPoint.java | 127 +- .../eclipse/jetty/io/ArrayByteBufferPool.java | 6 +- .../eclipse/jetty/io/ByteArrayEndPoint.java | 220 ++- .../org/eclipse/jetty/io/ByteBufferPool.java | 6 +- .../org/eclipse/jetty/io/ChannelEndPoint.java | 102 +- .../java/org/eclipse/jetty/io/Connection.java | 18 +- .../jetty/io/ConnectionStatistics.java | 2 +- .../org/eclipse/jetty/io/CyclicTimeout.java | 62 +- .../java/org/eclipse/jetty/io/EndPoint.java | 52 +- .../org/eclipse/jetty/io/EofException.java | 13 +- .../org/eclipse/jetty/io/FillInterest.java | 25 +- .../jetty/io/LeakTrackingByteBufferPool.java | 6 +- .../org/eclipse/jetty/io/ManagedSelector.java | 143 +- .../jetty/io/MappedByteBufferPool.java | 4 +- .../jetty/io/NegotiatingClientConnection.java | 1 - .../NegotiatingClientConnectionFactory.java | 1 - .../jetty/io/NetworkTrafficListener.java | 4 +- .../NetworkTrafficSelectChannelEndPoint.java | 18 +- .../org/eclipse/jetty/io/QuietException.java | 5 +- .../eclipse/jetty/io/RuntimeIOException.java | 4 +- .../org/eclipse/jetty/io/SelectorManager.java | 62 +- .../jetty/io/SocketChannelEndPoint.java | 16 +- .../org/eclipse/jetty/io/WriteFlusher.java | 16 +- .../eclipse/jetty/io/WriterOutputStream.java | 55 +- .../io/ssl/SslClientConnectionFactory.java | 1 - .../eclipse/jetty/io/ssl/SslConnection.java | 95 +- .../jetty/io/ssl/SslHandshakeListener.java | 1 - .../jetty/io/ArrayByteBufferPoolTest.java | 30 +- .../jetty/io/ByteArrayEndPointTest.java | 98 +- .../eclipse/jetty/io/CyclicTimeoutTest.java | 59 +- .../java/org/eclipse/jetty/io/IOTest.java | 65 +- .../org/eclipse/jetty/io/IdleTimeoutTest.java | 50 +- .../java/org/eclipse/jetty/io/NIOTest.java | 8 +- .../eclipse/jetty/io/SelectorManagerTest.java | 11 +- .../SocketChannelEndPointInterestsTest.java | 15 +- .../SocketChannelEndPointOpenCloseTest.java | 33 +- .../jetty/io/SocketChannelEndPointTest.java | 15 +- .../eclipse/jetty/io/SslConnectionTest.java | 69 +- .../jetty/io/SslEngineBehaviorTest.java | 69 +- .../eclipse/jetty/io/WriteFlusherTest.java | 35 +- jetty-jaas/pom.xml | 3 +- .../eclipse/jetty/jaas/JAASLoginService.java | 90 +- .../org/eclipse/jetty/jaas/JAASPrincipal.java | 16 +- .../java/org/eclipse/jetty/jaas/JAASRole.java | 6 +- .../eclipse/jetty/jaas/JAASUserPrincipal.java | 23 +- .../callback/AbstractCallbackHandler.java | 15 +- .../jaas/callback/DefaultCallbackHandler.java | 19 +- .../jetty/jaas/callback/ObjectCallback.java | 8 +- .../callback/RequestParameterCallback.java | 10 +- .../jaas/callback/ServletRequestCallback.java | 10 +- .../jaas/spi/AbstractDatabaseLoginModule.java | 78 +- .../jetty/jaas/spi/AbstractLoginModule.java | 81 +- .../jetty/jaas/spi/DataSourceLoginModule.java | 21 +- .../jetty/jaas/spi/JDBCLoginModule.java | 38 +- .../jetty/jaas/spi/LdapLoginModule.java | 52 +- .../jaas/spi/PropertyFileLoginModule.java | 31 +- .../org/eclipse/jetty/jaas/spi/UserInfo.java | 43 +- .../jetty/jaas/JAASLdapLoginServiceTest.java | 127 +- .../jetty/jaas/JAASLoginServiceTest.java | 83 +- .../eclipse/jetty/jaas/TestLoginModule.java | 6 +- .../security/jaspi/JaspiAuthenticator.java | 52 +- .../jaspi/JaspiAuthenticatorFactory.java | 68 +- .../security/jaspi/JaspiMessageInfo.java | 56 +- .../jaspi/ServletCallbackHandler.java | 28 +- .../security/jaspi/SimpleAuthConfig.java | 3 +- .../CredentialValidationCallback.java | 28 +- .../jaspi/modules/BaseAuthModule.java | 32 +- .../jaspi/modules/BasicAuthModule.java | 34 +- .../security/jaspi/modules/UserInfo.java | 2 +- .../security/jaspi/HttpHeaderAuthModule.java | 25 +- .../jetty/security/jaspi/JaspiTest.java | 83 +- jetty-jmx/pom.xml | 4 +- .../eclipse/jetty/jmx/ConnectorServer.java | 21 +- .../org/eclipse/jetty/jmx/MBeanContainer.java | 22 +- .../java/org/eclipse/jetty/jmx/MetaData.java | 45 +- .../eclipse/jetty/util/log/jmx/LogMBean.java | 12 +- jetty-jmx/src/test/java/com/acme/Base.java | 18 +- jetty-jmx/src/test/java/com/acme/Derived.java | 1 - jetty-jmx/src/test/java/com/acme/Managed.java | 1 - .../src/test/java/com/acme/SuperManaged.java | 1 - .../test/java/com/acme/jmx/DerivedMBean.java | 4 +- .../test/java/com/acme/jmx/ManagedMBean.java | 3 +- .../jetty/jmx/ConnectorServerTest.java | 16 +- .../jmx/MBeanContainerLifeCycleTest.java | 6 +- .../eclipse/jetty/jmx/MBeanContainerTest.java | 1 - .../eclipse/jetty/jmx/ObjectMBeanTest.java | 1 - .../jetty/jmx/ObjectMBeanUtilTest.java | 7 +- .../jetty/util/log/jmx/LogMBeanTest.java | 2 +- jetty-jndi/pom.xml | 5 +- .../jetty/jndi/BindingEnumeration.java | 12 +- .../eclipse/jetty/jndi/ContextFactory.java | 84 +- .../eclipse/jetty/jndi/DataSourceCloser.java | 24 +- .../jetty/jndi/InitialContextFactory.java | 22 +- .../eclipse/jetty/jndi/NameEnumeration.java | 11 +- .../org/eclipse/jetty/jndi/NamingContext.java | 410 +++-- .../org/eclipse/jetty/jndi/NamingUtil.java | 43 +- .../jndi/factories/MailSessionReference.java | 56 +- .../jetty/jndi/java/javaNameParser.java | 36 +- .../jetty/jndi/java/javaRootURLContext.java | 103 +- .../jndi/java/javaURLContextFactory.java | 33 +- .../jetty/jndi/local/localContextRoot.java | 169 +- .../org/eclipse/jetty/jndi/package-info.java | 2 +- .../factories/TestMailSessionReference.java | 17 +- .../org/eclipse/jetty/jndi/java/TestJNDI.java | 177 ++- .../jetty/jndi/java/TestLocalJNDI.java | 37 +- jetty-jspc-maven-plugin/pom.xml | 5 +- .../src/it/package-root/pom.xml | 3 +- .../src/it/simple-jsp-fail/pom.xml | 4 +- .../src/it/simple-jsp/pom.xml | 4 +- .../eclipse/jetty/jspc/plugin/JspcMojo.java | 223 ++- jetty-maven-plugin/pom.xml | 12 +- .../src/it/it-parent-pom/pom.xml | 3 +- .../src/it/javax-annotation-api/pom.xml | 3 +- .../src/main/java/test/App.java | 39 +- .../src/it/jetty-cdi-run-forked/pom.xml | 4 +- .../src/main/java/test/Greeter.java | 10 +- .../src/it/jetty-deploy-war-mojo-it/pom.xml | 4 +- .../api/pom.xml | 3 +- .../api/src/main/java/test/Api.java | 1 - .../pom.xml | 4 +- .../web/pom.xml | 3 +- ...sLoadingTestingServletContextListener.java | 7 +- .../jetty-simple-base/pom.xml | 3 +- .../HelloServlet.java | 11 +- .../jetty_run_distro_mojo_it/PingServlet.java | 10 +- .../jetty-simple-webapp/pom.xml | 4 +- .../src/it/jetty-run-distro-mojo-it/pom.xml | 3 +- .../jetty-simple-base/pom.xml | 3 +- .../HelloServlet.java | 9 +- .../jetty_run_forked_mojo_it/PingServlet.java | 10 +- .../jetty-simple-webapp/pom.xml | 6 +- .../src/it/jetty-run-forked-mojo-it/pom.xml | 3 +- .../jetty-simple-base/pom.xml | 3 +- .../its/jetty_run_mojo_it/HelloServlet.java | 9 +- .../its/jetty_run_mojo_it/PingServlet.java | 10 +- .../HelloTestServlet.java | 9 +- .../jetty-simple-webapp/pom.xml | 4 +- .../src/it/jetty-run-mojo-it/pom.xml | 3 +- .../src/it/jetty-run-mojo-jsp/pom.xml | 4 +- .../src/main/java/com/acme/Counter.java | 10 +- .../common/pom.xml | 3 +- .../module/module-api/pom.xml | 3 +- .../module/module-impl/pom.xml | 3 +- .../src/main/java/mca/module/ModuleImpl.java | 1 - .../module/pom.xml | 3 +- .../pom.xml | 3 +- .../webapp-war/pom.xml | 3 +- .../mca/webapp/WebAppServletListener.java | 7 +- .../jetty-simple-base/pom.xml | 3 +- .../HelloServlet.java | 9 +- .../PingServlet.java | 10 +- .../jetty-simple-webapp/pom.xml | 4 +- .../it/jetty-run-war-exploded-mojo-it/pom.xml | 3 +- .../jetty-simple-base/pom.xml | 3 +- .../its/jetty_run_mojo_it/HelloServlet.java | 9 +- .../its/jetty_run_mojo_it/PingServlet.java | 10 +- .../jetty-simple-webapp/pom.xml | 5 +- .../src/it/jetty-run-war-mojo-it/pom.xml | 3 +- .../jetty-simple-base/pom.xml | 3 +- .../its/jetty_start_mojo_it/HelloServlet.java | 9 +- .../its/jetty_start_mojo_it/PingServlet.java | 10 +- .../jetty-simple-webapp/pom.xml | 10 +- .../src/it/jetty-start-mojo-it/pom.xml | 3 +- .../src/main/java/org/olamy/App.java | 101 +- .../java/org/olamy/GreetingServiceImpl.java | 11 +- .../main/java/org/olamy/FieldVerifier.java | 13 +- .../main/java/org/olamy/GreetingResponse.java | 21 +- .../main/java/org/olamy/GreetingService.java | 3 +- .../java/org/olamy/GreetingServiceAsync.java | 5 +- .../src/it/run-mojo-gwt-it/pom.xml | 6 +- .../jetty/maven/plugin/AbstractJettyMojo.java | 345 ++--- .../jetty/maven/plugin/ConsoleScanner.java | 56 +- .../jetty/maven/plugin/JettyDeployWar.java | 20 +- .../maven/plugin/JettyEffectiveWebXml.java | 60 +- .../jetty/maven/plugin/JettyRunDistro.java | 293 ++-- .../maven/plugin/JettyRunForkedMojo.java | 211 ++- .../jetty/maven/plugin/JettyRunMojo.java | 373 +++-- .../maven/plugin/JettyRunWarExplodedMojo.java | 60 +- .../jetty/maven/plugin/JettyRunWarMojo.java | 50 +- .../jetty/maven/plugin/JettyStartMojo.java | 28 +- .../jetty/maven/plugin/JettyStopMojo.java | 53 +- .../maven/plugin/JettyWebAppContext.java | 61 +- .../plugin/MavenMetaInfConfiguration.java | 41 +- .../plugin/MavenQuickStartConfiguration.java | 39 +- .../maven/plugin/MavenServerConnector.java | 48 +- .../plugin/MavenWebInfConfiguration.java | 27 +- .../eclipse/jetty/maven/plugin/Overlay.java | 24 +- .../jetty/maven/plugin/OverlayConfig.java | 91 +- .../eclipse/jetty/maven/plugin/PluginLog.java | 8 +- .../jetty/maven/plugin/ScanPattern.java | 12 +- .../jetty/maven/plugin/ScanTargetPattern.java | 45 +- .../maven/plugin/SelectiveJarResource.java | 79 +- .../maven/plugin/ServerConnectorListener.java | 35 +- .../jetty/maven/plugin/ServerListener.java | 32 +- .../jetty/maven/plugin/ServerSupport.java | 106 +- .../eclipse/jetty/maven/plugin/Starter.java | 116 +- .../jetty/maven/plugin/SystemProperties.java | 27 +- .../jetty/maven/plugin/SystemProperty.java | 34 +- .../jetty/maven/plugin/WarPluginInfo.java | 43 +- .../maven/plugin/WebAppPropertyConverter.java | 91 +- .../plugin/utils/MavenProjectHelper.java | 11 +- .../jetty/maven/plugin/it/TestGetContent.java | 80 +- .../jetty-memcached-sessions/pom.xml | 50 +- .../session/MemcachedSessionDataMap.java | 57 +- .../MemcachedSessionDataMapFactory.java | 20 +- .../session/TestMemcachedSessions.java | 58 +- jetty-memcached/pom.xml | 1 - jetty-nosql/pom.xml | 3 +- .../jetty/nosql/NoSqlSessionDataStore.java | 29 +- .../nosql/mongodb/MongoSessionDataStore.java | 304 ++-- .../mongodb/MongoSessionDataStoreFactory.java | 11 +- .../jetty/nosql/mongodb/MongoUtils.java | 19 +- jetty-osgi/jetty-osgi-alpn/pom.xml | 12 +- jetty-osgi/jetty-osgi-boot-jsp/pom.xml | 90 +- .../jasper/ContainerTldBundleDiscoverer.java | 88 +- .../boot/jasper/JSTLBundleDiscoverer.java | 40 +- .../osgi/boot/jsp/FragmentActivator.java | 13 +- jetty-osgi/jetty-osgi-boot-warurl/pom.xml | 18 +- .../osgi/boot/warurl/WarUrlActivator.java | 11 +- .../osgi/boot/warurl/WarUrlStreamHandler.java | 25 +- .../internal/WarBundleManifestGenerator.java | 92 +- .../warurl/internal/WarURLConnection.java | 37 +- jetty-osgi/jetty-osgi-boot/pom.xml | 136 +- .../annotations/AnnotationConfiguration.java | 80 +- .../osgi/annotations/AnnotationParser.java | 74 +- .../osgi/boot/AbstractContextProvider.java | 110 +- .../jetty/osgi/boot/AbstractOSGiApp.java | 83 +- .../osgi/boot/AbstractWebAppProvider.java | 212 ++- .../osgi/boot/BundleContextProvider.java | 78 +- .../jetty/osgi/boot/BundleProvider.java | 6 +- .../jetty/osgi/boot/BundleWebAppProvider.java | 102 +- .../osgi/boot/JettyBootstrapActivator.java | 27 +- .../eclipse/jetty/osgi/boot/OSGiDeployer.java | 31 +- .../osgi/boot/OSGiMetaInfConfiguration.java | 124 +- .../jetty/osgi/boot/OSGiServerConstants.java | 8 +- .../jetty/osgi/boot/OSGiUndeployer.java | 16 +- .../osgi/boot/OSGiWebInfConfiguration.java | 4 +- .../jetty/osgi/boot/OSGiWebappConstants.java | 79 +- .../osgi/boot/ServiceContextProvider.java | 95 +- .../jetty/osgi/boot/ServiceProvider.java | 6 +- .../osgi/boot/ServiceWebAppProvider.java | 101 +- .../DefaultJettyAtJettyHomeHelper.java | 100 +- .../JettyServerServiceTracker.java | 30 +- .../serverfactory/ServerInstanceWrapper.java | 126 +- .../webapp/LibExtClassLoaderHelper.java | 42 +- .../webapp/OSGiWebappClassLoader.java | 71 +- .../boot/utils/BundleClassLoaderHelper.java | 13 +- .../utils/BundleClassLoaderHelperFactory.java | 17 +- .../boot/utils/BundleFileLocatorHelper.java | 35 +- .../utils/BundleFileLocatorHelperFactory.java | 17 +- .../jetty/osgi/boot/utils/EventSender.java | 39 +- .../osgi/boot/utils/FakeURLClassLoader.java | 18 +- .../osgi/boot/utils/OSGiClassLoader.java | 70 +- .../boot/utils/ServerConnectorListener.java | 15 +- .../osgi/boot/utils/TldBundleDiscoverer.java | 6 +- .../eclipse/jetty/osgi/boot/utils/Util.java | 52 +- .../DefaultBundleClassLoaderHelper.java | 145 +- .../internal/DefaultFileLocatorHelper.java | 118 +- .../internal/PackageAdminServiceTracker.java | 79 +- jetty-osgi/jetty-osgi-httpservice/pom.xml | 33 +- .../HttpServiceErrorHandlerHelper.java | 21 +- .../HttpServiceErrorPageErrorHandler.java | 75 +- jetty-osgi/pom.xml | 24 +- jetty-osgi/test-jetty-osgi-context/pom.xml | 17 +- .../main/java/com/acme/osgi/Activator.java | 21 +- jetty-osgi/test-jetty-osgi-fragment/pom.xml | 64 +- jetty-osgi/test-jetty-osgi-server/pom.xml | 17 +- .../main/java/com/acme/osgi/Activator.java | 30 +- .../main/java/com/acme/osgi/Activator.java | 27 +- jetty-osgi/test-jetty-osgi/pom.xml | 76 +- .../jetty/osgi/test/SimpleEchoSocket.java | 4 +- .../jetty/osgi/test/SimpleJavaxWebSocket.java | 13 +- .../jetty/osgi/test/SomeCustomBean.java | 6 +- .../TestJettyOSGiBootContextAsService.java | 1 - .../test/TestJettyOSGiBootHTTP2Conscrypt.java | 15 +- .../osgi/test/TestJettyOSGiBootHTTP2JDK9.java | 19 +- .../TestJettyOSGiBootWebAppAsService.java | 21 +- .../TestJettyOSGiBootWithAnnotations.java | 17 +- .../test/TestJettyOSGiBootWithBundle.java | 7 +- .../TestJettyOSGiBootWithJavaxWebSocket.java | 5 +- .../osgi/test/TestJettyOSGiBootWithJsp.java | 5 +- .../test/TestJettyOSGiBootWithWebSocket.java | 5 +- .../eclipse/jetty/osgi/test/TestOSGiUtil.java | 127 +- jetty-plus/pom.xml | 7 +- .../plus/annotation/ContainerInitializer.java | 66 +- .../jetty/plus/annotation/Injection.java | 62 +- .../plus/annotation/InjectionCollection.java | 58 +- .../plus/annotation/LifeCycleCallback.java | 42 +- .../LifeCycleCallbackCollection.java | 70 +- .../annotation/PostConstructCallback.java | 32 +- .../plus/annotation/PreDestroyCallback.java | 24 +- .../eclipse/jetty/plus/annotation/RunAs.java | 14 +- .../plus/annotation/RunAsCollection.java | 16 +- .../org/eclipse/jetty/plus/jndi/EnvEntry.java | 27 +- .../org/eclipse/jetty/plus/jndi/Link.java | 12 +- .../eclipse/jetty/plus/jndi/NamingDump.java | 8 +- .../eclipse/jetty/plus/jndi/NamingEntry.java | 88 +- .../jetty/plus/jndi/NamingEntryUtil.java | 77 +- .../org/eclipse/jetty/plus/jndi/Resource.java | 10 +- .../eclipse/jetty/plus/jndi/Transaction.java | 56 +- .../plus/security/DataSourceLoginService.java | 174 +-- .../jetty/plus/webapp/EnvConfiguration.java | 69 +- .../jetty/plus/webapp/PlusConfiguration.java | 51 +- .../jetty/plus/webapp/PlusDecorator.java | 10 +- .../plus/webapp/PlusDescriptorProcessor.java | 336 ++-- .../jetty/plus/jndi/NamingEntryUtilTest.java | 11 +- .../jetty/plus/jndi/TestNamingEntries.java | 85 +- .../jetty/plus/jndi/TestNamingEntryUtil.java | 10 +- .../webapp/PlusDescriptorProcessorTest.java | 49 +- .../jetty/plus/webapp/TestConfiguration.java | 23 +- jetty-proxy/pom.xml | 3 +- .../jetty/proxy/AbstractProxyServlet.java | 87 +- .../jetty/proxy/AfterContentTransformer.java | 23 +- .../jetty/proxy/AsyncMiddleManServlet.java | 10 +- .../jetty/proxy/AsyncProxyServlet.java | 4 +- .../eclipse/jetty/proxy/BalancerServlet.java | 4 +- .../eclipse/jetty/proxy/ConnectHandler.java | 24 +- .../org/eclipse/jetty/proxy/ProxyServlet.java | 5 +- .../proxy/AsyncMiddleManServletTest.java | 197 +-- .../jetty/proxy/BalancerServletTest.java | 12 +- .../jetty/proxy/CachingProxyServlet.java | 1 - .../jetty/proxy/ConnectHandlerSSLTest.java | 21 +- .../jetty/proxy/ConnectHandlerTest.java | 140 +- .../eclipse/jetty/proxy/EchoHttpServlet.java | 1 - .../eclipse/jetty/proxy/EmptyHttpServlet.java | 1 - .../jetty/proxy/ForwardProxyServerTest.java | 14 +- .../proxy/ForwardProxyTLSServerTest.java | 139 +- .../org/eclipse/jetty/proxy/ProxyServer.java | 1 - .../jetty/proxy/ProxyServletFailureTest.java | 45 +- .../jetty/proxy/ProxyServletLoadTest.java | 19 +- .../eclipse/jetty/proxy/ProxyServletTest.java | 268 ++-- .../eclipse/jetty/proxy/ReverseProxyTest.java | 11 +- jetty-quickstart/pom.xml | 3 +- .../jetty/quickstart/AttributeNormalizer.java | 153 +- .../ExtraXmlDescriptorProcessor.java | 24 +- .../quickstart/PreconfigureQuickStartWar.java | 14 +- .../quickstart/QuickStartConfiguration.java | 74 +- .../QuickStartDescriptorProcessor.java | 98 +- .../QuickStartGeneratorConfiguration.java | 378 ++--- .../jetty/quickstart/QuickStartWebApp.java | 19 +- .../jetty/quickstart/FooContextListener.java | 5 +- .../eclipse/jetty/quickstart/FooServlet.java | 5 +- .../jetty/quickstart/TestQuickStart.java | 24 +- jetty-rewrite/pom.xml | 3 +- .../jetty/rewrite/RewriteCustomizer.java | 2 +- .../rewrite/handler/CompactPathRule.java | 3 +- .../rewrite/handler/CookiePatternRule.java | 26 +- .../handler/ForwardedSchemeHeaderRule.java | 25 +- .../rewrite/handler/HeaderPatternRule.java | 40 +- .../rewrite/handler/HeaderRegexRule.java | 39 +- .../jetty/rewrite/handler/HeaderRule.java | 42 +- .../jetty/rewrite/handler/MsieSslRule.java | 47 +- .../jetty/rewrite/handler/PatternRule.java | 21 +- .../rewrite/handler/RedirectPatternRule.java | 17 +- .../rewrite/handler/RedirectRegexRule.java | 1 - .../jetty/rewrite/handler/RedirectUtil.java | 14 +- .../jetty/rewrite/handler/RegexRule.java | 34 +- .../rewrite/handler/ResponsePatternRule.java | 17 +- .../jetty/rewrite/handler/RewriteHandler.java | 67 +- .../rewrite/handler/RewritePatternRule.java | 22 +- .../rewrite/handler/RewriteRegexRule.java | 73 +- .../eclipse/jetty/rewrite/handler/Rule.java | 40 +- .../jetty/rewrite/handler/RuleContainer.java | 69 +- .../handler/TerminatingPatternRule.java | 3 +- .../rewrite/handler/TerminatingRegexRule.java | 3 +- .../jetty/rewrite/handler/ValidUrlRule.java | 19 +- .../handler/VirtualHostRuleContainer.java | 69 +- .../rewrite/handler/AbstractRuleTestCase.java | 27 +- .../handler/CookiePatternRuleTest.java | 2 - .../ForwardedSchemeHeaderRuleTest.java | 16 +- .../handler/HeaderPatternRuleTest.java | 50 +- .../rewrite/handler/HeaderRegexRuleTest.java | 79 +- .../rewrite/handler/MsieSslRuleTest.java | 5 +- .../rewrite/handler/PatternRuleTest.java | 116 +- .../handler/RedirectPatternRuleTest.java | 18 +- .../handler/RedirectRegexRuleTest.java | 16 +- .../jetty/rewrite/handler/RegexRuleTest.java | 59 +- .../handler/ResponsePatternRuleTest.java | 2 +- .../rewrite/handler/RewriteHandlerTest.java | 126 +- .../handler/RewritePatternRuleTest.java | 18 +- .../rewrite/handler/RewriteRegexRuleTest.java | 61 +- .../handler/TerminatingPatternRuleTest.java | 26 +- .../handler/TerminatingRegexRuleTest.java | 26 +- .../rewrite/handler/ValidUrlRuleTest.java | 46 +- .../handler/VirtualHostRuleContainerTest.java | 82 +- jetty-runner/pom.xml | 22 +- jetty-runner/src/it/test-jar-manifest/pom.xml | 6 +- .../java/org/eclipse/jetty/runner/Runner.java | 161 +- jetty-security/pom.xml | 3 +- .../jetty/security/AbstractLoginService.java | 119 +- .../security/AbstractUserAuthentication.java | 32 +- .../eclipse/jetty/security/Authenticator.java | 46 +- .../ConfigurableSpnegoLoginService.java | 3 +- .../jetty/security/ConstraintAware.java | 31 +- .../jetty/security/ConstraintMapping.java | 12 +- .../security/ConstraintSecurityHandler.java | 335 ++-- .../security/DefaultAuthenticatorFactory.java | 35 +- .../security/DefaultIdentityService.java | 16 +- .../jetty/security/DefaultUserIdentity.java | 24 +- .../jetty/security/HashLoginService.java | 51 +- .../jetty/security/IdentityService.java | 15 +- .../jetty/security/JDBCLoginService.java | 132 +- .../security/LoggedOutAuthentication.java | 17 +- .../eclipse/jetty/security/LoginService.java | 42 +- .../jetty/security/PropertyUserStore.java | 22 +- .../org/eclipse/jetty/security/RoleInfo.java | 43 +- .../jetty/security/RoleRunAsToken.java | 4 +- .../eclipse/jetty/security/RunAsToken.java | 1 + .../jetty/security/SecurityHandler.java | 232 ++- .../jetty/security/SpnegoUserIdentity.java | 1 - .../jetty/security/UserAuthentication.java | 7 +- .../jetty/security/UserDataConstraint.java | 9 +- .../org/eclipse/jetty/security/UserStore.java | 16 +- .../authentication/AuthorizationService.java | 1 - .../authentication/BasicAuthenticator.java | 27 +- .../ClientCertAuthenticator.java | 125 +- .../ConfigurableSpnegoAuthenticator.java | 6 +- .../DeferredAuthentication.java | 80 +- .../authentication/DigestAuthenticator.java | 18 +- .../authentication/FormAuthenticator.java | 214 ++- .../authentication/LoginAuthenticator.java | 19 +- .../authentication/LoginCallback.java | 4 - .../authentication/LoginCallbackImpl.java | 4 +- .../authentication/SessionAuthentication.java | 42 +- .../jetty/security/AliasedConstraintTest.java | 50 +- .../jetty/security/ConstraintTest.java | 878 ++++++----- .../jetty/security/DataConstraintsTest.java | 90 +- .../jetty/security/HashLoginServiceTest.java | 16 +- .../jetty/security/PropertyUserStoreTest.java | 84 +- .../security/SpecExampleConstraintTest.java | 107 +- .../jetty/security/TestLoginService.java | 30 +- .../eclipse/jetty/security/UserStoreTest.java | 42 +- .../SpnegoAuthenticatorTest.java | 5 +- .../server/AbstractConnectionFactory.java | 37 +- .../jetty/server/AbstractConnector.java | 179 ++- .../server/AbstractNetworkConnector.java | 11 +- .../eclipse/jetty/server/AcceptRateLimit.java | 73 +- .../jetty/server/AsyncContextEvent.java | 69 +- .../jetty/server/AsyncContextState.java | 40 +- .../jetty/server/AsyncRequestLogWriter.java | 1 - .../eclipse/jetty/server/Authentication.java | 194 ++- .../jetty/server/CachedContentFactory.java | 26 +- .../eclipse/jetty/server/ClassLoaderDump.java | 44 +- .../jetty/server/ConnectionFactory.java | 27 +- .../eclipse/jetty/server/ConnectionLimit.java | 63 +- .../org/eclipse/jetty/server/Connector.java | 14 +- .../org/eclipse/jetty/server/Cookies.java | 38 +- .../jetty/server/CustomRequestLog.java | 22 +- .../eclipse/jetty/server/DebugListener.java | 217 ++- .../eclipse/jetty/server/DeflaterPool.java | 1 - .../org/eclipse/jetty/server/Dispatcher.java | 253 +-- .../jetty/server/EncodingHttpWriter.java | 14 +- .../server/ForwardedRequestCustomizer.java | 30 +- .../org/eclipse/jetty/server/Handler.java | 41 +- .../jetty/server/HandlerContainer.java | 16 +- .../eclipse/jetty/server/HomeBaseWarning.java | 6 +- .../jetty/server/HostHeaderCustomizer.java | 3 +- .../org/eclipse/jetty/server/HttpChannel.java | 202 +-- .../jetty/server/HttpChannelOverHttp.java | 41 +- .../jetty/server/HttpChannelState.java | 679 ++++---- .../jetty/server/HttpConfiguration.java | 169 +- .../eclipse/jetty/server/HttpConnection.java | 146 +- .../jetty/server/HttpConnectionFactory.java | 12 +- .../org/eclipse/jetty/server/HttpInput.java | 183 ++- .../org/eclipse/jetty/server/HttpOutput.java | 55 +- .../eclipse/jetty/server/HttpTransport.java | 18 +- .../org/eclipse/jetty/server/HttpWriter.java | 25 +- .../jetty/server/InclusiveByteRange.java | 155 +- .../jetty/server/Iso88591HttpWriter.java | 36 +- .../eclipse/jetty/server/LocalConnector.java | 162 +- .../jetty/server/LowResourceMonitor.java | 121 +- .../server/MultiPartCleanerListener.java | 10 +- .../org/eclipse/jetty/server/MultiParts.java | 8 +- .../server/NegotiatingServerConnection.java | 7 +- .../NegotiatingServerConnectionFactory.java | 21 +- .../jetty/server/NetworkConnector.java | 4 +- .../server/OptionalSslConnectionFactory.java | 14 +- .../jetty/server/ProxyConnectionFactory.java | 18 +- .../eclipse/jetty/server/PushBuilderImpl.java | 68 +- .../jetty/server/QuietServletException.java | 7 +- .../org/eclipse/jetty/server/Request.java | 706 ++++----- .../org/eclipse/jetty/server/RequestLog.java | 10 +- .../jetty/server/RequestLogCollection.java | 8 +- .../jetty/server/RequestLogWriter.java | 2 +- .../jetty/server/ResourceContentFactory.java | 44 +- .../eclipse/jetty/server/ResourceService.java | 511 +++--- .../org/eclipse/jetty/server/Response.java | 255 +-- .../eclipse/jetty/server/ResponseWriter.java | 119 +- .../jetty/server/SecureRequestCustomizer.java | 95 +- .../java/org/eclipse/jetty/server/Server.java | 218 ++- .../eclipse/jetty/server/ServerConnector.java | 113 +- .../server/ServletRequestHttpWrapper.java | 14 +- .../server/ServletResponseHttpWrapper.java | 7 +- .../jetty/server/SessionIdManager.java | 90 +- .../eclipse/jetty/server/ShutdownMonitor.java | 4 +- .../server/SocketCustomizationListener.java | 30 +- .../jetty/server/SslConnectionFactory.java | 11 +- .../eclipse/jetty/server/UserIdentity.java | 21 +- .../eclipse/jetty/server/Utf8HttpWriter.java | 125 +- .../jetty/server/handler/AbstractHandler.java | 108 +- .../handler/AbstractHandlerContainer.java | 94 +- .../handler/AllowSymLinkAliasChecker.java | 12 +- .../server/handler/AsyncDelayHandler.java | 111 +- .../handler/BufferedResponseHandler.java | 130 +- .../jetty/server/handler/ContextHandler.java | 772 ++++----- .../handler/ContextHandlerCollection.java | 180 +-- .../jetty/server/handler/DebugHandler.java | 91 +- .../jetty/server/handler/DefaultHandler.java | 39 +- .../jetty/server/handler/ErrorHandler.java | 215 ++- .../server/handler/HandlerCollection.java | 88 +- .../jetty/server/handler/HandlerList.java | 16 +- .../jetty/server/handler/HandlerWrapper.java | 68 +- .../jetty/server/handler/HotSwapHandler.java | 38 +- .../server/handler/IdleTimeoutHandler.java | 17 +- .../server/handler/InetAccessHandler.java | 7 +- .../handler/ManagedAttributeListener.java | 53 +- .../server/handler/MovedContextHandler.java | 41 +- .../server/handler/RequestLogHandler.java | 20 +- .../jetty/server/handler/ResourceHandler.java | 113 +- .../jetty/server/handler/ScopedHandler.java | 136 +- .../handler/SecuredRedirectHandler.java | 9 +- .../jetty/server/handler/ShutdownHandler.java | 89 +- .../server/handler/StatisticsHandler.java | 49 +- .../server/handler/ThreadLimitHandler.java | 190 +-- .../server/handler/gzip/GzipFactory.java | 2 +- .../server/handler/gzip/GzipHandler.java | 378 ++--- .../gzip/GzipHttpOutputInterceptor.java | 204 +-- .../server/handler/gzip/package-info.java | 2 +- .../handler/jmx/AbstractHandlerMBean.java | 43 +- .../handler/jmx/ContextHandlerMBean.java | 28 +- .../server/jmx/AbstractConnectorMBean.java | 19 +- .../server/session/AbstractSessionCache.java | 390 +++-- .../session/AbstractSessionDataStore.java | 79 +- .../AbstractSessionDataStoreFactory.java | 12 +- .../session/CachingSessionDataStore.java | 76 +- .../CachingSessionDataStoreFactory.java | 20 +- .../jetty/server/session/DatabaseAdaptor.java | 142 +- .../server/session/DefaultSessionCache.java | 93 +- .../session/DefaultSessionCacheFactory.java | 33 +- .../session/DefaultSessionIdManager.java | 297 ++-- .../server/session/FileSessionDataStore.java | 271 ++-- .../session/FileSessionDataStoreFactory.java | 11 +- .../jetty/server/session/HouseKeeper.java | 125 +- .../server/session/JDBCSessionDataStore.java | 530 +++---- .../session/JDBCSessionDataStoreFactory.java | 22 +- .../server/session/NullSessionCache.java | 24 +- .../session/NullSessionCacheFactory.java | 16 +- .../server/session/NullSessionDataStore.java | 20 +- .../session/NullSessionDataStoreFactory.java | 6 +- .../eclipse/jetty/server/session/Session.java | 213 +-- .../jetty/server/session/SessionCache.java | 148 +- .../server/session/SessionCacheFactory.java | 5 +- .../jetty/server/session/SessionContext.java | 56 +- .../jetty/server/session/SessionData.java | 164 +- .../jetty/server/session/SessionDataMap.java | 26 +- .../server/session/SessionDataMapFactory.java | 2 - .../server/session/SessionDataStore.java | 39 +- .../session/SessionDataStoreFactory.java | 5 +- .../jetty/server/session/SessionHandler.java | 704 ++++----- .../UnreadableSessionDataException.java | 19 +- .../UnwriteableSessionDataException.java | 17 +- .../jetty/server/AbstractHttpTest.java | 30 +- .../jetty/server/AsyncRequestReadTest.java | 210 ++- .../eclipse/jetty/server/AsyncStressTest.java | 196 +-- .../server/CheckReverseProxyHeadersTest.java | 59 +- .../jetty/server/ClassLoaderDumpTest.java | 72 +- .../jetty/server/ConnectionOpenCloseTest.java | 33 +- .../jetty/server/ConnectorCloseTestBase.java | 85 +- .../jetty/server/ConnectorTimeoutTest.java | 357 +++-- .../org/eclipse/jetty/server/CookiesTest.java | 83 +- .../server/CustomResourcesMonitorTest.java | 60 +- .../org/eclipse/jetty/server/DumpHandler.java | 152 +- .../jetty/server/ErrorHandlerTest.java | 282 ++-- .../jetty/server/ExtendedServerTest.java | 42 +- .../ForwardedRequestCustomizerTest.java | 26 +- .../jetty/server/GracefulStopTest.java | 349 ++--- .../eclipse/jetty/server/HalfCloseTest.java | 60 +- .../server/HostHeaderCustomizerTest.java | 11 +- .../jetty/server/HttpChannelEventTest.java | 1 - .../jetty/server/HttpConnectionTest.java | 1080 ++++++------- .../jetty/server/HttpInputAsyncStateTest.java | 445 +++--- .../eclipse/jetty/server/HttpInputTest.java | 29 +- ...ManyWaysToAsyncCommitBadBehaviourTest.java | 7 +- .../server/HttpManyWaysToAsyncCommitTest.java | 4 +- .../server/HttpManyWaysToCommitTest.java | 43 +- .../eclipse/jetty/server/HttpOutputTest.java | 759 +++++---- .../jetty/server/HttpServerTestBase.java | 681 ++++---- .../jetty/server/HttpServerTestFixture.java | 126 +- .../server/HttpVersionCustomizerTest.java | 1 - .../eclipse/jetty/server/HttpWriterTest.java | 78 +- .../jetty/server/InclusiveByteRangeTest.java | 137 +- .../InsufficientThreadsDetectionTest.java | 10 +- .../jetty/server/LocalAsyncContextTest.java | 25 +- .../jetty/server/LocalConnectorTest.java | 387 +++-- .../jetty/server/LowResourcesMonitorTest.java | 72 +- .../server/NetworkTrafficListenerTest.java | 69 +- .../jetty/server/NotAcceptingTest.java | 290 ++-- .../server/OptionalSslConnectionTest.java | 9 +- .../jetty/server/PartialRFC2616Test.java | 709 +++++---- .../jetty/server/ProxyConnectionTest.java | 131 +- .../jetty/server/ProxyProtocolTest.java | 16 +- .../org/eclipse/jetty/server/RequestTest.java | 1373 ++++++++--------- .../jetty/server/ResourceCacheTest.java | 167 +- .../eclipse/jetty/server/ResponseTest.java | 298 ++-- .../ServerConnectorAsyncContextTest.java | 2 +- .../server/ServerConnectorCloseTest.java | 3 +- .../server/ServerConnectorHttpServerTest.java | 2 +- .../jetty/server/ServerConnectorTest.java | 89 +- .../server/ServerConnectorTimeoutTest.java | 60 +- .../jetty/server/ShutdownMonitorTest.java | 9 +- .../SlowClientWithPipelinedRequestTest.java | 30 +- .../org/eclipse/jetty/server/StressTest.java | 315 ++-- .../eclipse/jetty/server/SuspendHandler.java | 45 +- .../jetty/server/ThreadStarvationTest.java | 138 +- .../handler/AllowSymLinkAliasCheckerTest.java | 11 +- .../handler/BufferedResponseHandlerTest.java | 185 ++- .../handler/ContextHandlerCollectionTest.java | 236 +-- .../ContextHandlerGetResourceTest.java | 340 ++-- .../server/handler/ContextHandlerTest.java | 174 +-- .../server/handler/CustomRequestLogTest.java | 158 +- .../server/handler/DebugHandlerTest.java | 66 +- .../server/handler/DefaultHandlerTest.java | 50 +- .../jetty/server/handler/HandlerTest.java | 174 ++- .../server/handler/InetAccessHandlerTest.java | 63 +- .../server/handler/NcsaRequestLogTest.java | 221 ++- .../handler/ResourceHandlerRangeTest.java | 16 +- .../server/handler/ResourceHandlerTest.java | 153 +- .../server/handler/ScopedHandlerTest.java | 60 +- .../handler/SecuredRedirectHandlerTest.java | 46 +- .../server/handler/ShutdownHandlerTest.java | 5 +- .../server/handler/StatisticsHandlerTest.java | 42 +- .../handler/ThreadLimitHandlerTest.java | 102 +- .../server/session/SessionCookieTest.java | 27 +- .../jetty/server/ssl/SSLCloseTest.java | 49 +- .../jetty/server/ssl/SSLEngineTest.java | 187 +-- .../ssl/SSLReadEOFAfterResponseTest.java | 8 +- .../SSLSelectChannelConnectorLoadTest.java | 17 +- .../ssl/SelectChannelServerSslTest.java | 83 +- .../jetty/server/ssl/SlowClientsTest.java | 16 +- .../ssl/SniSslConnectionFactoryTest.java | 35 +- .../server/ssl/SslConnectionFactoryTest.java | 11 +- .../ssl/SslContextFactoryReloadTest.java | 17 +- .../ssl/SslSelectChannelTimeoutTest.java | 5 +- .../jetty/server/ssl/SslUploadTest.java | 16 +- jetty-servlet/pom.xml | 15 +- .../org/eclipse/jetty/servlet/BaseHolder.java | 84 +- .../eclipse/jetty/servlet/DefaultServlet.java | 248 ++- .../jetty/servlet/ErrorPageErrorHandler.java | 43 +- .../eclipse/jetty/servlet/FilterHolder.java | 107 +- .../eclipse/jetty/servlet/FilterMapping.java | 147 +- .../org/eclipse/jetty/servlet/Holder.java | 118 +- .../org/eclipse/jetty/servlet/Invoker.java | 166 +- .../servlet/JspPropertyGroupServlet.java | 72 +- .../eclipse/jetty/servlet/ListenerHolder.java | 46 +- .../eclipse/jetty/servlet/NoJspServlet.java | 7 +- .../jetty/servlet/ServletContextHandler.java | 500 +++--- .../eclipse/jetty/servlet/ServletHandler.java | 808 +++++----- .../eclipse/jetty/servlet/ServletHolder.java | 522 +++---- .../eclipse/jetty/servlet/ServletMapping.java | 57 +- .../org/eclipse/jetty/servlet/Source.java | 31 +- .../jetty/servlet/StatisticsServlet.java | 35 +- .../jetty/servlet/jmx/FilterMappingMBean.java | 2 +- .../jetty/servlet/jmx/HolderMBean.java | 5 +- .../servlet/jmx/ServletMappingMBean.java | 2 +- .../listener/ContainerInitializer.java | 18 +- .../servlet/listener/ELContextCleaner.java | 19 +- .../servlet/listener/IntrospectorCleaner.java | 5 +- .../AsyncContextDispatchWithQueryStrings.java | 47 +- .../servlet/AsyncContextListenersTest.java | 36 +- .../jetty/servlet/AsyncContextTest.java | 120 +- .../jetty/servlet/AsyncListenerTest.java | 73 +- .../jetty/servlet/AsyncServletIOTest.java | 542 ++++--- .../servlet/AsyncServletLongPollTest.java | 15 +- .../jetty/servlet/AsyncServletTest.java | 560 ++++--- .../servlet/ComplianceViolations2616Test.java | 10 +- .../jetty/servlet/CustomRequestLogTest.java | 11 +- .../servlet/DefaultServletRangesTest.java | 107 +- .../jetty/servlet/DefaultServletTest.java | 504 +++--- .../jetty/servlet/DispatcherForwardTest.java | 148 +- .../eclipse/jetty/servlet/DispatcherTest.java | 298 ++-- .../eclipse/jetty/servlet/EncodedURITest.java | 100 +- .../eclipse/jetty/servlet/ErrorPageTest.java | 120 +- .../jetty/servlet/FilterHolderTest.java | 102 +- .../jetty/servlet/GzipHandlerTest.java | 326 ++-- .../org/eclipse/jetty/servlet/HolderTest.java | 19 +- .../jetty/servlet/IncludedServletTest.java | 13 +- .../eclipse/jetty/servlet/InvokerTest.java | 13 +- .../jetty/servlet/MultiPartServletTest.java | 17 +- .../jetty/servlet/PostServletTest.java | 81 +- .../jetty/servlet/RequestHeadersTest.java | 17 +- .../eclipse/jetty/servlet/RequestURITest.java | 45 +- .../jetty/servlet/ResponseHeadersTest.java | 22 +- .../jetty/servlet/SSLAsyncIOServletTest.java | 9 +- .../servlet/ServletContextHandlerTest.java | 196 ++- .../servlet/ServletContextResourcesTest.java | 7 +- .../jetty/servlet/ServletHandlerTest.java | 239 ++- .../jetty/servlet/ServletHolderTest.java | 37 +- .../jetty/servlet/ServletRequestLogTest.java | 171 +- .../eclipse/jetty/servlet/ServletTester.java | 66 +- .../jetty/servlet/StatisticsServletTest.java | 71 +- jetty-servlets/pom.xml | 13 +- .../java/org/eclipse/jetty/servlets/CGI.java | 17 +- .../jetty/servlets/CloseableDoSFilter.java | 4 +- .../eclipse/jetty/servlets/ConcatServlet.java | 3 +- .../jetty/servlets/CrossOriginFilter.java | 47 +- .../servlets/DataRateLimitedServlet.java | 127 +- .../org/eclipse/jetty/servlets/DoSFilter.java | 70 +- .../jetty/servlets/EventSourceServlet.java | 9 +- .../eclipse/jetty/servlets/HeaderFilter.java | 47 +- .../servlets/IncludeExcludeBasedFilter.java | 80 +- .../jetty/servlets/PushCacheFilter.java | 20 +- .../servlets/PushSessionCacheFilter.java | 21 +- .../org/eclipse/jetty/servlets/PutFilter.java | 103 +- .../org/eclipse/jetty/servlets/QoSFilter.java | 7 +- .../eclipse/jetty/servlets/WelcomeFilter.java | 24 +- .../jetty/servlets/AbstractDoSFilterTest.java | 181 ++- .../jetty/servlets/AsyncManipFilter.java | 13 +- .../servlets/AsyncScheduledDispatchWrite.java | 11 +- .../servlets/AsyncTimeoutCompleteWrite.java | 19 +- .../servlets/AsyncTimeoutDispatchWrite.java | 9 +- .../jetty/servlets/ConcatServletTest.java | 32 +- .../jetty/servlets/CrossOriginFilterTest.java | 137 +- .../servlets/DataRateLimitedServletTest.java | 68 +- .../jetty/servlets/DoSFilterJMXTest.java | 24 +- .../eclipse/jetty/servlets/DoSFilterTest.java | 38 +- .../servlets/EventSourceServletTest.java | 12 +- .../jetty/servlets/GzipContentLengthTest.java | 113 +- .../servlets/GzipDefaultNoRecompressTest.java | 49 +- .../jetty/servlets/GzipDefaultTest.java | 232 ++- .../eclipse/jetty/servlets/GzipTester.java | 199 ++- .../jetty/servlets/HeaderFilterTest.java | 29 +- .../java/org/eclipse/jetty/servlets/Hex.java | 6 +- .../IncludeExcludeBasedFilterTest.java | 132 +- .../servlets/IncludedGzipMinSizeTest.java | 22 +- .../jetty/servlets/IncludedGzipTest.java | 50 +- .../jetty/servlets/NoOpOutputStream.java | 8 +- .../eclipse/jetty/servlets/PutFilterTest.java | 109 +- .../eclipse/jetty/servlets/QoSFilterTest.java | 3 +- .../jetty/servlets/TestDirContentServlet.java | 13 +- .../servlets/TestMinGzipSizeServlet.java | 3 +- .../TestServletBufferTypeLengthWrite.java | 5 +- .../TestServletLengthStreamTypeWrite.java | 3 +- .../TestServletLengthTypeStreamWrite.java | 3 +- .../TestServletStreamLengthTypeWrite.java | 3 +- ...ServletStreamLengthTypeWriteWithFlush.java | 13 +- .../TestServletStreamTypeLengthWrite.java | 3 +- .../TestServletTypeLengthStreamWrite.java | 3 +- .../TestServletTypeStreamLengthWrite.java | 3 +- .../servlets/TestStaticMimeTypeServlet.java | 29 +- .../jetty/servlets/ThreadStarvationTest.java | 134 +- jetty-spring/pom.xml | 6 +- .../spring/SpringConfigurationProcessor.java | 7 +- .../spring/SpringXmlConfigurationTest.java | 16 +- .../jetty/spring/TestConfiguration.java | 1 - jetty-start/pom.xml | 3 +- .../org/eclipse/jetty/start/BaseBuilder.java | 125 +- .../org/eclipse/jetty/start/BaseHome.java | 91 +- .../org/eclipse/jetty/start/Classpath.java | 19 +- .../jetty/start/CommandLineBuilder.java | 38 +- .../main/java/org/eclipse/jetty/start/FS.java | 10 +- .../java/org/eclipse/jetty/start/FileArg.java | 18 +- .../eclipse/jetty/start/FileInitializer.java | 106 +- .../org/eclipse/jetty/start/JarVersion.java | 4 +- .../org/eclipse/jetty/start/Licensing.java | 10 +- .../java/org/eclipse/jetty/start/Main.java | 151 +- .../java/org/eclipse/jetty/start/Module.java | 276 ++-- .../jetty/start/ModuleGraphWriter.java | 82 +- .../java/org/eclipse/jetty/start/Modules.java | 262 ++-- .../org/eclipse/jetty/start/PathFinder.java | 9 +- .../org/eclipse/jetty/start/PathMatchers.java | 39 +- .../java/org/eclipse/jetty/start/Props.java | 60 +- .../eclipse/jetty/start/PropsException.java | 2 +- .../java/org/eclipse/jetty/start/RawArgs.java | 4 +- .../org/eclipse/jetty/start/StartArgs.java | 313 ++-- .../org/eclipse/jetty/start/StartIni.java | 35 +- .../org/eclipse/jetty/start/StartLog.java | 48 +- .../org/eclipse/jetty/start/TextFile.java | 16 +- .../eclipse/jetty/start/UsageException.java | 8 +- .../java/org/eclipse/jetty/start/Utils.java | 12 +- .../java/org/eclipse/jetty/start/Version.java | 36 +- .../jetty/start/builders/StartDirBuilder.java | 8 +- .../jetty/start/builders/StartIniBuilder.java | 10 +- .../start/config/CommandLineConfigSource.java | 38 +- .../jetty/start/config/ConfigSource.java | 18 +- .../jetty/start/config/ConfigSources.java | 16 +- .../jetty/start/config/DirConfigSource.java | 53 +- .../start/config/JettyBaseConfigSource.java | 6 +- .../start/config/JettyHomeConfigSource.java | 4 +- .../fileinits/BaseHomeFileInitializer.java | 39 +- .../start/fileinits/LocalFileInitializer.java | 16 +- .../MavenLocalRepoFileInitializer.java | 52 +- .../start/fileinits/TestFileInitializer.java | 9 +- .../start/fileinits/UriFileInitializer.java | 18 +- .../org/eclipse/jetty/start/BaseHomeTest.java | 57 +- .../jetty/start/CommandLineBuilderTest.java | 16 +- .../jetty/start/ConfigurationAssert.java | 26 +- .../java/org/eclipse/jetty/start/FSTest.java | 18 +- .../org/eclipse/jetty/start/FileArgTest.java | 17 +- .../jetty/start/IncludeJettyDirTest.java | 294 ++-- .../eclipse/jetty/start/JarVersionTest.java | 15 +- .../org/eclipse/jetty/start/MainTest.java | 62 +- .../jetty/start/ModuleGraphWriterTest.java | 18 +- .../org/eclipse/jetty/start/ModuleTest.java | 36 +- .../org/eclipse/jetty/start/ModulesTest.java | 37 +- .../eclipse/jetty/start/PathFinderTest.java | 18 +- .../jetty/start/PathMatchersAbsoluteTest.java | 52 +- .../start/PathMatchersSearchRootTest.java | 10 +- .../org/eclipse/jetty/start/PropertyDump.java | 4 +- .../jetty/start/PropertyPassingTest.java | 30 +- .../org/eclipse/jetty/start/PropsTest.java | 68 +- .../eclipse/jetty/start/StartMatchers.java | 10 +- .../eclipse/jetty/start/TestBadUseCases.java | 26 +- .../java/org/eclipse/jetty/start/TestEnv.java | 2 +- .../org/eclipse/jetty/start/TestUseCases.java | 32 +- .../org/eclipse/jetty/start/UtilsTest.java | 4 +- .../org/eclipse/jetty/start/VersionTest.java | 74 +- .../jetty/start/config/ConfigSourcesTest.java | 377 ++--- .../MavenLocalRepoFileInitializerTest.java | 145 +- .../start/util/CorrectMavenCentralRefs.java | 26 +- .../start/util/RebuildTestResources.java | 20 +- .../jetty-unixsocket-client/pom.xml | 4 +- .../jetty/unixsocket/UnixSocketClient.java | 8 +- .../jetty/unixsocket/UnixSocketTest.java | 9 +- .../jetty-unixsocket-common/pom.xml | 4 +- .../jetty-unixsocket-server/pom.xml | 4 +- .../server/UnixSocketConnector.java | 26 +- .../unixsocket/UnixSocketProxyServer.java | 1 - .../jetty/unixsocket/UnixSocketServer.java | 13 +- jetty-unixsocket/pom.xml | 3 +- .../org/eclipse/jetty/util/ajax/JSON.java | 285 ++-- .../jetty/util/ajax/JSONDateConvertor.java | 27 +- .../jetty/util/ajax/JSONEnumConvertor.java | 20 +- .../jetty/util/ajax/JSONObjectConvertor.java | 50 +- .../jetty/util/ajax/JSONPojoConvertor.java | 208 ++- .../util/ajax/JSONPojoConvertorFactory.java | 50 +- .../ajax/JSONCollectionConvertorTest.java | 10 +- .../ajax/JSONPojoConvertorFactoryTest.java | 59 +- .../util/ajax/JSONPojoConvertorTest.java | 64 +- .../org/eclipse/jetty/util/ajax/JSONTest.java | 341 ++-- jetty-util/pom.xml | 3 +- .../org/eclipse/jetty/util/AbstractTrie.java | 26 +- .../eclipse/jetty/util/ArrayTernaryTrie.java | 476 +++--- .../org/eclipse/jetty/util/ArrayTrie.java | 388 +++-- .../org/eclipse/jetty/util/ArrayUtil.java | 102 +- .../eclipse/jetty/util/AtomicBiInteger.java | 98 +- .../org/eclipse/jetty/util/Attributes.java | 10 +- .../org/eclipse/jetty/util/AttributesMap.java | 6 +- .../jetty/util/BlockingArrayQueue.java | 88 +- .../org/eclipse/jetty/util/BufferUtil.java | 406 ++--- .../jetty/util/ByteArrayISO8859Writer.java | 210 ++- .../jetty/util/ByteArrayOutputStream2.java | 46 +- .../java/org/eclipse/jetty/util/Callback.java | 21 +- .../util/ClassLoadingObjectInputStream.java | 59 +- .../jetty/util/ClassVisibilityChecker.java | 21 +- .../jetty/util/CompletableCallback.java | 1 + .../org/eclipse/jetty/util/DateCache.java | 181 ++- .../jetty/util/DecoratedObjectFactory.java | 2 +- .../jetty/util/DeprecationWarning.java | 8 +- .../java/org/eclipse/jetty/util/Fields.java | 7 +- .../eclipse/jetty/util/FutureCallback.java | 50 +- .../org/eclipse/jetty/util/FuturePromise.java | 56 +- .../java/org/eclipse/jetty/util/HostMap.java | 45 +- .../java/org/eclipse/jetty/util/HostPort.java | 74 +- .../main/java/org/eclipse/jetty/util/IO.java | 337 ++-- .../eclipse/jetty/util/IncludeExclude.java | 13 +- .../eclipse/jetty/util/IncludeExcludeSet.java | 93 +- .../eclipse/jetty/util/InetAddressSet.java | 229 +-- .../eclipse/jetty/util/IntrospectionUtil.java | 192 +-- .../eclipse/jetty/util/IteratingCallback.java | 86 +- .../jetty/util/IteratingNestedCallback.java | 27 +- .../org/eclipse/jetty/util/JavaVersion.java | 26 +- .../java/org/eclipse/jetty/util/Jetty.java | 38 +- .../java/org/eclipse/jetty/util/LazyList.java | 261 ++-- .../org/eclipse/jetty/util/LeakDetector.java | 14 +- .../java/org/eclipse/jetty/util/Loader.java | 52 +- .../org/eclipse/jetty/util/ManifestUtils.java | 2 +- .../org/eclipse/jetty/util/MemoryUtils.java | 1 + .../eclipse/jetty/util/MultiException.java | 150 +- .../java/org/eclipse/jetty/util/MultiMap.java | 205 +-- .../jetty/util/MultiPartOutputStream.java | 92 +- .../eclipse/jetty/util/MultiPartWriter.java | 91 +- .../jetty/util/MultiReleaseJarFile.java | 52 +- .../org/eclipse/jetty/util/PathWatcher.java | 476 +++--- .../eclipse/jetty/util/PatternMatcher.java | 44 +- .../eclipse/jetty/util/ProcessorUtils.java | 2 +- .../java/org/eclipse/jetty/util/Promise.java | 2 +- .../jetty/util/QuotedStringTokenizer.java | 425 +++-- .../java/org/eclipse/jetty/util/RegexSet.java | 24 +- .../jetty/util/RolloverFileOutputStream.java | 245 ++- .../java/org/eclipse/jetty/util/Scanner.java | 324 ++-- .../org/eclipse/jetty/util/SearchPattern.java | 112 +- .../jetty/util/SharedBlockingCallback.java | 43 +- .../jetty/util/SocketAddressResolver.java | 11 +- .../org/eclipse/jetty/util/StringUtil.java | 526 ++++--- .../eclipse/jetty/util/TopologicalSort.java | 137 +- .../java/org/eclipse/jetty/util/TreeTrie.java | 294 ++-- .../java/org/eclipse/jetty/util/Trie.java | 81 +- .../java/org/eclipse/jetty/util/TypeUtil.java | 443 +++--- .../java/org/eclipse/jetty/util/URIUtil.java | 658 ++++---- .../java/org/eclipse/jetty/util/Uptime.java | 28 +- .../org/eclipse/jetty/util/UrlEncoded.java | 729 ++++----- .../eclipse/jetty/util/Utf8Appendable.java | 123 +- .../eclipse/jetty/util/Utf8LineParser.java | 8 +- .../eclipse/jetty/util/Utf8StringBuffer.java | 1 - .../eclipse/jetty/util/Utf8StringBuilder.java | 12 +- .../util/annotation/ManagedAttribute.java | 37 +- .../jetty/util/annotation/ManagedObject.java | 12 +- .../util/annotation/ManagedOperation.java | 20 +- .../eclipse/jetty/util/annotation/Name.java | 11 +- .../util/component/AbstractLifeCycle.java | 146 +- .../util/component/AttributeContainerMap.java | 2 +- .../jetty/util/component/Container.java | 37 +- .../util/component/ContainerLifeCycle.java | 207 +-- .../jetty/util/component/Dumpable.java | 64 +- .../util/component/DumpableCollection.java | 12 +- .../jetty/util/component/FileDestroyable.java | 23 +- .../FileNoticeLifeCycleListener.java | 37 +- .../jetty/util/component/Graceful.java | 18 +- .../jetty/util/component/LifeCycle.java | 63 +- .../jetty/util/component/StopLifeCycle.java | 19 +- .../jetty/util/log/AbstractLogger.java | 64 +- .../eclipse/jetty/util/log/JavaUtilLog.java | 108 +- .../jetty/util/log/JettyAwareLogger.java | 98 +- .../jetty/util/log/JettyLogHandler.java | 38 +- .../java/org/eclipse/jetty/util/log/Log.java | 81 +- .../org/eclipse/jetty/util/log/Logger.java | 17 +- .../org/eclipse/jetty/util/log/LoggerLog.java | 11 +- .../org/eclipse/jetty/util/log/Slf4jLog.java | 9 +- .../jetty/util/log/StacklessLogging.java | 10 +- .../org/eclipse/jetty/util/log/StdErrLog.java | 301 ++-- .../util/preventers/AWTLeakPreventer.java | 15 +- .../preventers/AbstractLeakPreventer.java | 13 +- .../preventers/AppContextLeakPreventer.java | 9 +- .../util/preventers/DOMLeakPreventer.java | 19 +- .../DriverManagerLeakPreventer.java | 9 +- .../preventers/GCThreadLeakPreventer.java | 16 +- .../util/preventers/Java2DLeakPreventer.java | 8 +- .../util/preventers/LDAPLeakPreventer.java | 8 +- .../LoginConfigurationLeakPreventer.java | 9 +- .../SecurityProviderLeakPreventer.java | 5 +- .../jetty/util/resource/BadResource.java | 52 +- .../jetty/util/resource/EmptyResource.java | 5 +- .../jetty/util/resource/JarFileResource.java | 237 ++- .../jetty/util/resource/JarResource.java | 107 +- .../jetty/util/resource/PathResource.java | 64 +- .../eclipse/jetty/util/resource/Resource.java | 296 ++-- .../util/resource/ResourceCollators.java | 29 +- .../util/resource/ResourceCollection.java | 7 +- .../jetty/util/resource/ResourceFactory.java | 14 +- .../jetty/util/resource/URLResource.java | 127 +- .../jetty/util/security/CertificateUtils.java | 10 +- .../util/security/CertificateValidator.java | 149 +- .../jetty/util/security/Constraint.java | 118 +- .../jetty/util/security/Credential.java | 26 +- .../util/security/CredentialProvider.java | 8 +- .../eclipse/jetty/util/security/Password.java | 53 +- .../jetty/util/security/UnixCrypt.java | 310 ++-- .../ssl/AliasedX509ExtendedKeyManager.java | 51 +- .../util/ssl/SniX509ExtendedKeyManager.java | 47 +- .../jetty/util/ssl/SslContextFactory.java | 231 +-- .../jetty/util/ssl/SslSelectionDump.java | 146 +- .../java/org/eclipse/jetty/util/ssl/X509.java | 47 +- .../jetty/util/statistic/RateStatistic.java | 63 +- .../jetty/util/thread/ExecutionStrategy.java | 6 +- .../jetty/util/thread/ExecutorThreadPool.java | 145 +- .../eclipse/jetty/util/thread/Invocable.java | 12 +- .../org/eclipse/jetty/util/thread/Locker.java | 4 +- .../jetty/util/thread/QueuedThreadPool.java | 11 +- .../util/thread/ReservedThreadExecutor.java | 55 +- .../jetty/util/thread/SerializedExecutor.java | 14 +- .../jetty/util/thread/ShutdownThread.java | 47 +- .../jetty/util/thread/ThreadPoolBudget.java | 15 +- .../jetty/util/thread/TimerScheduler.java | 11 +- .../jetty/util/thread/TryExecutor.java | 14 +- .../util/thread/strategy/EatWhatYouKill.java | 39 +- .../strategy/ExecuteProduceConsume.java | 5 +- .../util/thread/strategy/ProduceConsume.java | 13 +- .../strategy/ProduceExecuteConsume.java | 18 +- .../org/eclipse/jetty/util/ArrayUtilTest.java | 1 - .../jetty/util/AtomicBiIntegerTest.java | 115 +- .../jetty/util/BlockingArrayQueueTest.java | 127 +- .../eclipse/jetty/util/BufferUtilTest.java | 187 ++- .../org/eclipse/jetty/util/DateCacheTest.java | 38 +- .../jetty/util/FutureCallbackTest.java | 162 +- .../org/eclipse/jetty/util/HostPortTest.java | 100 +- .../jetty/util/IncludeExcludeSetTest.java | 17 +- .../jetty/util/IncludeExcludeTest.java | 126 +- .../jetty/util/InetAddressSetTest.java | 163 +- .../jetty/util/IntrospectionUtilTest.java | 11 +- .../jetty/util/IteratingCallbackTest.java | 12 +- .../eclipse/jetty/util/JavaVersionTest.java | 148 +- .../org/eclipse/jetty/util/LazyListTest.java | 445 +++--- .../eclipse/jetty/util/LeakDetectorTest.java | 9 +- .../org/eclipse/jetty/util/LoaderTest.java | 5 +- .../jetty/util/MultiExceptionTest.java | 70 +- .../org/eclipse/jetty/util/MultiMapTest.java | 300 ++-- .../jetty/util/MultiReleaseJarFileTest.java | 82 +- .../eclipse/jetty/util/PathWatcherDemo.java | 43 +- .../eclipse/jetty/util/PathWatcherTest.java | 353 ++--- .../jetty/util/ProcessorUtilsTest.java | 5 +- .../jetty/util/QueueBenchmarkTest.java | 16 +- .../jetty/util/QuotedStringTokenizerTest.java | 124 +- .../org/eclipse/jetty/util/RegexSetTest.java | 66 +- .../util/RolloverFileOutputStreamTest.java | 240 +-- .../org/eclipse/jetty/util/ScannerTest.java | 107 +- .../eclipse/jetty/util/SearchPatternTest.java | 168 +- .../util/SharedBlockingCallbackTest.java | 108 +- .../eclipse/jetty/util/StringUtilTest.java | 115 +- .../jetty/util/TestIntrospectionUtil.java | 87 +- .../jetty/util/TopologicalSortTest.java | 186 +-- .../java/org/eclipse/jetty/util/TrieTest.java | 264 ++-- .../org/eclipse/jetty/util/TypeUtilTest.java | 136 +- .../jetty/util/URIUtilCanonicalPathTest.java | 153 +- .../org/eclipse/jetty/util/URIUtilTest.java | 333 ++-- .../eclipse/jetty/util/URLEncodedTest.java | 97 +- .../org/eclipse/jetty/util/UptimeTest.java | 2 +- .../util/UrlEncodedInvalidEncodingTest.java | 35 +- .../jetty/util/UrlEncodedUtf8Test.java | 71 +- .../jetty/util/Utf8AppendableTest.java | 124 +- .../jetty/util/Utf8LineParserTest.java | 41 +- .../component/ContainerLifeCycleTest.java | 16 +- .../jetty/util/component/DumpableTest.java | 8 +- .../LifeCycleListenerNestedTest.java | 50 +- .../util/component/LifeCycleListenerTest.java | 35 +- .../java/org/eclipse/jetty/util/log/Blue.java | 5 +- .../jetty/util/log/CapturingJULHandler.java | 7 +- .../org/eclipse/jetty/util/log/Green.java | 5 +- .../jetty/util/log/JavaUtilLogTest.java | 48 +- .../org/eclipse/jetty/util/log/LogTest.java | 10 +- .../eclipse/jetty/util/log/NamedLogTest.java | 8 +- .../java/org/eclipse/jetty/util/log/Red.java | 5 +- .../eclipse/jetty/util/log/Slf4jHelper.java | 6 +- .../eclipse/jetty/util/log/StdErrCapture.java | 12 +- .../eclipse/jetty/util/log/StdErrLogTest.java | 277 ++-- .../util/resource/ClassPathResourceTest.java | 24 +- .../util/resource/FileSystemResourceTest.java | 313 ++-- .../jetty/util/resource/JarResourceTest.java | 75 +- .../jetty/util/resource/JrtResourceTest.java | 41 +- .../util/resource/ResourceAliasTest.java | 38 +- .../util/resource/ResourceCollectionTest.java | 42 +- .../jetty/util/resource/ResourceTest.java | 203 ++- .../jetty/util/security/CredentialTest.java | 56 +- .../jetty/util/security/PasswordTest.java | 13 +- .../jetty/util/ssl/SslContextFactoryTest.java | 33 +- .../util/ssl/X509CertificateAdapter.java | 50 +- .../org/eclipse/jetty/util/ssl/X509Test.java | 22 +- .../util/statistic/CounterStatisticTest.java | 95 +- .../util/statistic/RateStatisticTest.java | 74 +- .../util/statistic/SampleStatisticTest.java | 53 +- .../util/thread/AbstractThreadPoolTest.java | 28 +- .../jetty/util/thread/EatWhatYouKillTest.java | 12 +- .../eclipse/jetty/util/thread/LockerTest.java | 11 +- .../util/thread/QueuedThreadPoolTest.java | 394 ++--- .../thread/ReservedThreadExecutorTest.java | 64 +- .../jetty/util/thread/SchedulerTest.java | 63 +- .../jetty/util/thread/SweeperTest.java | 9 +- .../thread/ThreadClassLoaderScopeTest.java | 26 +- .../strategy/ExecuteProduceConsumeTest.java | 73 +- .../strategy/ExecutionStrategyTest.java | 66 +- jetty-webapp/pom.xml | 9 +- jetty-webapp/src/main/java/module-info.java | 22 +- .../jetty/webapp/AbsoluteOrdering.java | 35 +- .../jetty/webapp/AbstractConfiguration.java | 35 +- .../webapp/CachingWebAppClassLoader.java | 35 +- .../eclipse/jetty/webapp/ClassMatcher.java | 205 ++- .../eclipse/jetty/webapp/Configuration.java | 112 +- .../eclipse/jetty/webapp/Configurations.java | 276 ++-- .../jetty/webapp/DefaultsDescriptor.java | 1 - .../org/eclipse/jetty/webapp/Descriptor.java | 34 +- .../jetty/webapp/DescriptorProcessor.java | 4 +- .../jetty/webapp/DiscoveredAnnotation.java | 34 +- .../jetty/webapp/FragmentConfiguration.java | 20 +- .../jetty/webapp/FragmentDescriptor.java | 85 +- .../webapp/IterativeDescriptorProcessor.java | 24 +- .../jetty/webapp/JaasConfiguration.java | 6 +- .../webapp/JettyWebXmlConfiguration.java | 63 +- .../jetty/webapp/JmxConfiguration.java | 5 +- .../jetty/webapp/JndiConfiguration.java | 6 +- .../jetty/webapp/JspConfiguration.java | 7 +- .../org/eclipse/jetty/webapp/MetaData.java | 250 ++- .../jetty/webapp/MetaDataComplete.java | 5 +- .../jetty/webapp/MetaInfConfiguration.java | 378 +++-- .../org/eclipse/jetty/webapp/Ordering.java | 4 +- .../java/org/eclipse/jetty/webapp/Origin.java | 5 +- .../jetty/webapp/OverrideDescriptor.java | 2 - .../jetty/webapp/RelativeOrdering.java | 64 +- .../jetty/webapp/ServletsConfiguration.java | 7 +- .../webapp/StandardDescriptorProcessor.java | 533 +++---- .../jetty/webapp/WebAppClassLoader.java | 405 +++-- .../jetty/webapp/WebAppConfiguration.java | 3 +- .../eclipse/jetty/webapp/WebAppContext.java | 570 ++++--- .../eclipse/jetty/webapp/WebDescriptor.java | 277 ++-- .../jetty/webapp/WebInfConfiguration.java | 224 ++- .../jetty/webapp/WebXmlConfiguration.java | 49 +- .../java/org/acme/webapp/ClassInJarA.java | 2 +- .../jetty/webapp/ClassMatcherTest.java | 21 +- .../jetty/webapp/ConfigurationsTest.java | 362 +++-- .../webapp/MetaInfConfigurationTest.java | 28 +- .../eclipse/jetty/webapp/OrderingTest.java | 296 ++-- .../jetty/webapp/URLStreamHandlerUtil.java | 28 +- .../jetty/webapp/WebAppClassLoaderTest.java | 202 +-- .../WebAppClassLoaderUrlStreamTest.java | 30 +- .../jetty/webapp/WebAppContextTest.java | 38 +- .../javax-websocket-client/pom.xml | 7 +- .../client/AnnotatedClientEndpointConfig.java | 14 +- .../client/EmptyClientEndpointConfig.java | 8 +- .../javax/client/EmptyConfigurator.java | 4 +- .../client/JavaxClientUpgradeRequest.java | 1 - .../client/JavaxWebSocketClientContainer.java | 11 +- ...JavaxWebSocketClientContainerProvider.java | 6 +- ...vaxWebSocketClientFrameHandlerFactory.java | 8 +- .../javax/client/JsrUpgradeListener.java | 14 +- .../javax-websocket-common/pom.xml | 4 +- .../javax/common/BasicEndpointConfig.java | 6 +- .../common/CompletableFutureCallback.java | 4 +- .../common/JavaxWebSocketAsyncRemote.java | 3 +- .../common/JavaxWebSocketBasicRemote.java | 1 - .../javax/common/JavaxWebSocketContainer.java | 3 +- .../javax/common/JavaxWebSocketExtension.java | 10 +- .../common/JavaxWebSocketExtensionConfig.java | 4 +- .../common/JavaxWebSocketFrameHandler.java | 29 +- .../JavaxWebSocketFrameHandlerFactory.java | 31 +- .../JavaxWebSocketFrameHandlerMetadata.java | 10 +- .../common/JavaxWebSocketPongMessage.java | 6 +- .../common/JavaxWebSocketRemoteEndpoint.java | 2 - .../javax/common/JavaxWebSocketSession.java | 11 +- .../common/JavaxWebSocketUpgradeResponse.java | 4 +- .../websocket/javax/common/MessageSink.java | 2 +- .../javax/common/SendHandlerCallback.java | 4 +- .../javax/common/SessionTracker.java | 1 - .../javax/common/UpgradeResponse.java | 4 +- .../javax/common/UpgradeResponseAdapter.java | 4 +- .../common/decoders/ByteArrayDecoder.java | 6 +- .../common/decoders/ByteBufferDecoder.java | 2 +- .../common/decoders/InputStreamDecoder.java | 4 +- .../common/decoders/PongMessageDecoder.java | 6 +- .../javax/common/decoders/ReaderDecoder.java | 4 +- .../common/encoders/ByteArrayEncoder.java | 2 +- .../common/encoders/ByteBufferEncoder.java | 2 +- .../common/encoders/EncodeFailedFuture.java | 2 +- .../common/messages/AbstractMessageSink.java | 6 +- .../common/messages/ByteArrayMessageSink.java | 16 +- .../messages/ByteBufferMessageSink.java | 8 +- .../javax/common/messages/CallbackBuffer.java | 6 +- .../messages/DecodedBinaryMessageSink.java | 20 +- .../DecodedBinaryStreamMessageSink.java | 18 +- .../common/messages/DecodedMessageSink.java | 10 +- .../messages/DecodedTextMessageSink.java | 20 +- .../DecodedTextStreamMessageSink.java | 18 +- .../messages/DispatchedMessageSink.java | 10 +- .../messages/InputStreamMessageSink.java | 6 +- .../common/messages/MessageInputStream.java | 16 +- .../common/messages/MessageOutputStream.java | 2 +- .../javax/common/messages/MessageReader.java | 6 +- .../javax/common/messages/MessageWriter.java | 2 +- .../messages/PartialByteArrayMessageSink.java | 10 +- .../PartialByteBufferMessageSink.java | 6 +- .../messages/PartialStringMessageSink.java | 8 +- .../common/messages/ReaderMessageSink.java | 6 +- .../common/messages/StringMessageSink.java | 6 +- .../util/DuplicateAnnotationException.java | 4 +- .../util/InvalidSignatureException.java | 5 +- .../javax/common/util/InvokerUtils.java | 52 +- .../javax/common/util/ReflectUtils.java | 16 +- ...bstractJavaxWebSocketFrameHandlerTest.java | 1 - .../javax/common/DummyContainer.java | 1 - .../common/DummyFrameHandlerFactory.java | 4 +- ...bSocketFrameHandler_BadSignaturesTest.java | 8 +- ...avaxWebSocketFrameHandler_OnCloseTest.java | 1 - ...avaxWebSocketFrameHandler_OnErrorTest.java | 1 - ...ameHandler_OnMessage_BinaryStreamTest.java | 1 - ...cketFrameHandler_OnMessage_BinaryTest.java | 1 - ...FrameHandler_OnMessage_TextStreamTest.java | 1 - ...SocketFrameHandler_OnMessage_TextTest.java | 1 - ...JavaxWebSocketFrameHandler_OnOpenTest.java | 1 - .../common/coders/tests/BadDualDecoder.java | 10 +- .../common/coders/tests/BadDualEncoder.java | 4 +- .../coders/tests/FruitBinaryEncoder.java | 8 +- .../common/coders/tests/FruitDecoder.java | 4 +- .../endpoints/AbstractStringEndpoint.java | 18 +- .../handlers/ByteBufferPartialHandler.java | 2 +- .../handlers/ByteBufferWholeHandler.java | 2 +- .../common/handlers/ComboMessageHandler.java | 2 +- .../handlers/ExtendedMessageHandler.java | 2 +- .../handlers/InputStreamWholeHandler.java | 2 +- .../common/handlers/ReaderWholeHandler.java | 2 +- .../messages/AbstractMessageSinkTest.java | 4 +- .../DecodedBinaryMessageSinkTest.java | 2 +- .../DecodedBinaryStreamMessageSinkTest.java | 2 +- .../messages/DecodedTextMessageSinkTest.java | 2 +- .../DecodedTextStreamMessageSinkTest.java | 2 +- .../common/messages/MessageWriterTest.java | 2 +- .../javax/common/sockets/TrackingSocket.java | 2 +- .../javax/common/util/InvokerUtilsTest.java | 48 +- .../util/InvokerUtils_StaticParamsTest.java | 18 +- .../common/util/NameParamIdentifier.java | 4 +- .../javax/common/util/ReflectUtilsTest.java | 6 +- .../jsr356/server/RestartContextTest.java | 7 +- .../javax-websocket-server/pom.xml | 9 +- .../server/ContainerDefaultConfigurator.java | 10 +- .../server/JavaxWebSocketServerContainer.java | 17 +- ...xWebSocketServletContainerInitializer.java | 29 +- .../AnnotatedServerEndpointConfig.java | 26 +- .../internal/JavaxWebSocketCreator.java | 26 +- .../server/internal/JsrHandshakeRequest.java | 8 +- .../server/internal/JsrHandshakeResponse.java | 6 +- .../server/internal/PathParamIdentifier.java | 8 +- .../PathParamServerEndpointConfig.java | 8 +- .../internal/ServerEndpointConfigWrapper.java | 4 +- .../UndefinedServerEndpointConfig.java | 12 +- .../internal/UpgradeResponseAdapter.java | 4 +- .../websocket/javax/server/PathParamTest.java | 8 +- .../browser/JsrBrowserConfigurator.java | 1 - .../server/browser/JsrBrowserSocket.java | 3 +- .../server/examples/GetHttpSessionSocket.java | 1 - .../server/examples/MyAuthedConfigurator.java | 1 - .../server/examples/StreamingEchoSocket.java | 1 - jetty-websocket/javax-websocket-tests/pom.xml | 4 +- .../javax/tests/BiConsumerServiceServlet.java | 4 +- .../tests/CompletableFutureMethodHandle.java | 6 +- .../websocket/javax/tests/CoreServer.java | 2 +- .../websocket/javax/tests/EventSocket.java | 3 +- .../jetty/websocket/javax/tests/Fuzzer.java | 20 +- .../websocket/javax/tests/LocalFuzzer.java | 4 +- .../websocket/javax/tests/LocalServer.java | 29 +- .../javax/tests/RawFrameBuilder.java | 10 +- .../javax/tests/SessionMatchers.java | 6 +- .../jetty/websocket/javax/tests/Sha1Sum.java | 7 +- .../websocket/javax/tests/UnitGenerator.java | 4 +- .../websocket/javax/tests/UpgradeUtils.java | 6 +- .../javax/tests/WSEndpointTracker.java | 30 +- .../websocket/javax/tests/WSEventTracker.java | 38 +- .../jetty/websocket/javax/tests/WSServer.java | 1 - .../jetty/websocket/javax/tests/WSURI.java | 4 +- .../javax/tests/framehandlers/FrameEcho.java | 3 +- .../framehandlers/FrameHandlerTracker.java | 7 +- .../tests/framehandlers/WholeMessageEcho.java | 4 +- .../tests/client/AnnotatedEchoClient.java | 6 +- .../client/AnnotatedEndpointConfigTest.java | 28 +- .../javax/tests/client/ConfiguratorTest.java | 19 +- .../client/DecoderReaderManySmallTest.java | 3 +- .../tests/client/DelayedStartClientTest.java | 16 +- .../client/JsrClientEchoTrackingSocket.java | 12 +- .../tests/client/JsrClientTrackingSocket.java | 12 +- .../tests/client/MessageReceivingTest.java | 4 +- .../javax/tests/client/OnCloseTest.java | 3 +- .../client/SessionAddMessageHandlerTest.java | 3 +- .../javax/tests/client/WriteTimeoutTest.java | 5 +- .../misbehaving/AnnotatedRuntimeOnOpen.java | 4 +- .../misbehaving/EndpointRuntimeOnOpen.java | 4 +- .../misbehaving/MisbehavingClassTest.java | 2 - .../samples/CloseEndpointConfigSocket.java | 4 +- .../samples/CloseReasonSessionSocket.java | 4 +- .../client/samples/CloseReasonSocket.java | 4 +- .../samples/CloseSessionReasonSocket.java | 4 +- .../client/samples/CloseSessionSocket.java | 4 +- .../tests/client/samples/CloseSocket.java | 4 +- .../javax/tests/client/samples/IntSocket.java | 6 +- .../javax/tests/coders/BadDualDecoder.java | 10 +- .../javax/tests/coders/BadDualEncoder.java | 4 +- .../tests/coders/CoderEventTracking.java | 4 +- .../javax/tests/coders/DateDecoder.java | 6 +- .../javax/tests/coders/DateEncoder.java | 6 +- .../javax/tests/coders/DateTimeDecoder.java | 6 +- .../javax/tests/coders/DateTimeEncoder.java | 6 +- .../tests/coders/DecoderTextStreamTest.java | 18 +- .../javax/tests/coders/DecoderTextTest.java | 6 +- .../javax/tests/coders/FloatDecoderTest.java | 4 +- .../tests/coders/FruitBinaryEncoder.java | 8 +- .../javax/tests/coders/FruitDecoder.java | 4 +- .../tests/coders/IntegerDecoderTest.java | 5 +- .../javax/tests/coders/LongDecoderTest.java | 4 +- .../javax/tests/coders/QuotesDecoder.java | 12 +- .../javax/tests/coders/QuotesUtil.java | 13 +- .../javax/tests/coders/ShortDecoderTest.java | 5 +- .../javax/tests/coders/TimeDecoder.java | 6 +- .../javax/tests/coders/TimeEncoder.java | 6 +- .../javax/tests/coders/ValidDualDecoder.java | 6 +- .../javax/tests/coders/ValidDualEncoder.java | 6 +- .../handlers/ByteBufferPartialHandler.java | 2 +- .../handlers/ByteBufferWholeHandler.java | 2 +- .../tests/handlers/ComboMessageHandler.java | 2 +- .../handlers/ExtendedMessageHandler.java | 2 +- .../handlers/InputStreamWholeHandler.java | 2 +- .../tests/handlers/ReaderWholeHandler.java | 2 +- .../javax/tests/quotes/QuotesDecoder.java | 12 +- .../javax/tests/quotes/QuotesDecoderTest.java | 2 +- .../javax/tests/quotes/QuotesEncoderTest.java | 37 +- .../javax/tests/quotes/QuotesSocket.java | 10 +- .../javax/tests/quotes/QuotesUtil.java | 13 +- ...tJavaxWebSocketServerFrameHandlerTest.java | 1 - .../server/AnnotatedServerEndpointTest.java | 14 +- ...asicEchoEndpointConfigContextListener.java | 4 +- .../BasicEchoEndpointContextListener.java | 4 +- .../BasicEchoSocketConfigContextListener.java | 4 +- .../BasicEchoSocketContextListener.java | 4 +- .../javax/tests/server/BinaryStreamTest.java | 26 +- .../javax/tests/server/ConfiguratorTest.java | 10 +- .../tests/server/EndpointViaConfigTest.java | 1 - .../server/IdleTimeoutContextListener.java | 4 +- .../tests/server/InputStreamEchoTest.java | 18 +- ...FrameHandler_OnMessage_TextStreamTest.java | 2 - .../JettyServerEndpointConfiguratorTest.java | 8 +- .../javax/tests/server/JsrBatchModeTest.java | 20 +- .../javax/tests/server/JsrEchoTest.java | 24 +- .../tests/server/LargeAnnotatedTest.java | 1 - .../tests/server/LargeContainerTest.java | 1 - .../javax/tests/server/MemoryUsageTest.java | 2 +- .../tests/server/OnMessageReturnTest.java | 2 - .../javax/tests/server/PingPongTest.java | 1 - .../tests/server/PongContextListener.java | 4 +- .../javax/tests/server/PongSocket.java | 10 +- .../server/PrimitivesBinaryEchoTest.java | 18 +- .../tests/server/PrimitivesTextEchoTest.java | 18 +- .../javax/tests/server/ReaderEchoTest.java | 18 +- .../javax/tests/server/SessionTest.java | 34 +- .../tests/server/SessionTrackingTest.java | 3 +- .../javax/tests/server/StreamTest.java | 48 +- .../javax/tests/server/TextStreamTest.java | 24 +- .../server/UriTemplateParameterTest.java | 16 +- .../WebSocketServerContainerExecutorTest.java | 3 +- .../configs/EchoSocketConfigurator.java | 2 +- .../BasicBinaryMessageByteBufferSocket.java | 2 +- .../server/sockets/ByteBufferSocket.java | 14 +- .../server/sockets/ConfiguredEchoSocket.java | 18 +- .../tests/server/sockets/DateTextSocket.java | 18 +- .../sockets/InvalidOpenSessionIntSocket.java | 2 +- .../tests/server/sockets/TrackingSocket.java | 2 +- .../sockets/binary/ByteBufferSocket.java | 14 +- .../sockets/echo/EchoBasicTextSocket.java | 2 +- .../sockets/echo/EchoReturnEndpoint.java | 4 +- .../echo/EchoStatelessBasicTextSocket.java | 2 +- .../partial/PartialTextSessionSocket.java | 10 +- .../sockets/partial/PartialTextSocket.java | 10 +- .../partial/PartialTrackingSocket.java | 6 +- .../sockets/pong/PongMessageEndpoint.java | 6 +- .../BooleanObjectTextParamSocket.java | 10 +- .../primitives/BooleanObjectTextSocket.java | 10 +- .../primitives/BooleanTextParamSocket.java | 10 +- .../sockets/primitives/BooleanTextSocket.java | 10 +- .../primitives/ByteObjectTextSocket.java | 10 +- .../sockets/primitives/ByteTextSocket.java | 10 +- .../sockets/primitives/CharTextSocket.java | 10 +- .../primitives/CharacterObjectTextSocket.java | 10 +- .../primitives/DoubleObjectTextSocket.java | 12 +- .../sockets/primitives/DoubleTextSocket.java | 12 +- .../primitives/FloatObjectTextSocket.java | 12 +- .../sockets/primitives/FloatTextSocket.java | 12 +- .../primitives/IntParamTextSocket.java | 10 +- .../sockets/primitives/IntTextSocket.java | 10 +- .../IntegerObjectParamTextSocket.java | 10 +- .../primitives/IntegerObjectTextSocket.java | 10 +- .../primitives/LongObjectTextSocket.java | 10 +- .../sockets/primitives/LongTextSocket.java | 10 +- .../primitives/ShortObjectTextSocket.java | 10 +- .../sockets/primitives/ShortTextSocket.java | 10 +- .../sockets/streaming/InputStreamSocket.java | 14 +- .../sockets/streaming/ReaderParamSocket.java | 14 +- .../sockets/streaming/ReaderSocket.java | 14 +- .../StringReturnReaderParamSocket.java | 14 +- jetty-websocket/jetty-websocket-api/pom.xml | 4 +- .../jetty/websocket/api/BatchMode.java | 2 +- .../jetty/websocket/api/CloseException.java | 1 - .../jetty/websocket/api/CloseStatus.java | 2 +- .../jetty/websocket/api/RemoteEndpoint.java | 16 +- .../eclipse/jetty/websocket/api/Session.java | 3 +- .../jetty/websocket/api/StatusCode.java | 34 +- .../jetty/websocket/api/UpgradeRequest.java | 4 +- .../jetty/websocket/api/UpgradeResponse.java | 8 +- .../api/WebSocketConnectionListener.java | 2 +- .../websocket/api/WebSocketListener.java | 6 +- .../api/WebSocketPartialListener.java | 18 +- .../api/annotations/OnWebSocketClose.java | 6 +- .../api/annotations/OnWebSocketConnect.java | 6 +- .../api/annotations/OnWebSocketError.java | 6 +- .../api/annotations/OnWebSocketFrame.java | 2 +- .../api/annotations/OnWebSocketMessage.java | 6 +- .../websocket/api/annotations/WebSocket.java | 2 +- .../jetty/websocket/api/util/WSURI.java | 4 +- .../jetty-websocket-client/pom.xml | 4 +- .../client/ClientUpgradeRequest.java | 12 +- .../client/JettyUpgradeListener.java | 8 +- .../websocket/client/WebSocketClient.java | 16 +- .../impl/JettyClientUpgradeRequest.java | 4 +- .../src/test/java/examples/ClientDemo.java | 19 +- .../test/java/examples/SimpleEchoClient.java | 6 +- .../test/java/examples/SimpleEchoSocket.java | 6 +- .../client/WebSocketClientBadUriTest.java | 32 +- .../jetty-websocket-common/pom.xml | 3 +- .../common/CompletableFutureCallback.java | 4 +- .../common/FunctionCallException.java | 4 +- .../common/JettyWebSocketFrameHandler.java | 54 +- .../JettyWebSocketFrameHandlerFactory.java | 22 +- .../common/JettyWebSocketRemoteEndpoint.java | 12 +- .../jetty/websocket/common/MessageSink.java | 2 +- .../websocket/common/WebSocketSession.java | 6 +- .../invoke/InvalidSignatureException.java | 7 +- .../websocket/common/invoke/InvokerUtils.java | 31 +- .../common/message/ByteArrayMessageSink.java | 4 +- .../common/message/CallbackBuffer.java | 4 +- .../common/message/DispatchedMessageSink.java | 10 +- .../message/InputStreamMessageSink.java | 6 +- .../common/message/MessageInputStream.java | 14 +- .../common/message/MessageOutputStream.java | 2 +- .../common/message/MessageReader.java | 6 +- .../common/message/MessageWriter.java | 2 +- .../message/PartialBinaryMessageSink.java | 6 +- .../message/PartialTextMessageSink.java | 6 +- .../common/message/ReaderMessageSink.java | 4 +- .../util/DuplicateAnnotationException.java | 4 +- .../websocket/common/util/ReflectUtils.java | 16 +- .../websocket/common/util/Utf8CharBuffer.java | 6 +- .../endpoints/adapters/AdapterEchoSocket.java | 4 +- .../annotated/AnnotatedBinaryArraySocket.java | 1 - .../AnnotatedBinaryStreamSocket.java | 4 +- .../annotated/AnnotatedTextStreamSocket.java | 4 +- .../annotated/BadBinarySignatureSocket.java | 6 +- .../annotated/BadDuplicateBinarySocket.java | 8 +- .../annotated/BadTextSignatureSocket.java | 2 +- .../annotated/MyEchoBinarySocket.java | 6 +- .../endpoints/annotated/MyEchoSocket.java | 4 +- .../listeners/ListenerPartialSocket.java | 4 +- .../listeners/ListenerPingPongSocket.java | 4 +- .../common/handshake/DummyUpgradeRequest.java | 6 +- .../handshake/DummyUpgradeResponse.java | 6 +- .../common/invoke/InvokerUtilsTest.java | 48 +- .../common/invoke/NameParamIdentifier.java | 4 +- .../common/util/Utf8CharBufferTest.java | 6 +- .../jetty-websocket-server/pom.xml | 4 +- .../server/JettyServerUpgradeRequest.java | 3 +- .../server/JettyServerUpgradeResponse.java | 4 +- .../server/JettyWebSocketCreator.java | 3 +- .../server/JettyWebSocketServerContainer.java | 17 +- .../server/JettyWebSocketServlet.java | 2 +- .../server/JettyWebSocketServletFactory.java | 3 +- .../config/JettyWebSocketConfiguration.java | 4 +- ...yWebSocketServletContainerInitializer.java | 15 +- .../JettyServerFrameHandlerFactory.java | 2 +- .../internal/UpgradeRequestAdapter.java | 4 +- .../internal/UpgradeResponseAdapter.java | 8 +- .../server/browser/BrowserDebugTool.java | 19 +- .../server/browser/BrowserSocket.java | 38 +- jetty-websocket/jetty-websocket-tests/pom.xml | 4 +- .../tests/AnnoMaxMessageEndpoint.java | 2 +- .../tests/CloseTrackingEndpoint.java | 8 +- .../jetty/websocket/tests/EventSocket.java | 3 +- .../tests/JettyWebSocketFilterTest.java | 4 +- .../tests/JettyWebSocketNegotiationTest.java | 6 +- .../tests/JettyWebSocketServletTest.java | 6 +- .../websocket/tests/SuspendResumeTest.java | 6 +- .../tests/WebSocketServletExamplesTest.java | 11 +- .../websocket/tests/WebSocketStatsTest.java | 11 +- .../tests/client/ClientCloseTest.java | 21 +- .../tests/client/ClientConfigTest.java | 2 +- .../tests/client/ClientConnectTest.java | 1 - .../tests/client/ClientSessionsTest.java | 7 +- .../tests/client/ClientWriteThread.java | 6 +- .../tests/client/WebSocketClientTest.java | 4 +- .../tests/examples/MyAdvancedEchoServlet.java | 3 +- .../tests/examples/MyBinaryEchoSocket.java | 2 +- .../tests/examples/MyEchoServlet.java | 3 +- .../tests/server/AbstractCloseEndpoint.java | 4 +- .../tests/server/ContainerEndpoint.java | 6 +- .../tests/server/FastFailEndpoint.java | 2 +- .../tests/server/ServerCloseCreator.java | 3 +- .../tests/server/ServerCloseTest.java | 7 +- .../tests/server/ServerConfigTest.java | 20 +- .../tests/util/FutureWriteCallback.java | 2 +- .../jetty/websocket/tests/util/WSURITest.java | 1 - jetty-websocket/pom.xml | 3 +- jetty-websocket/websocket-core/pom.xml | 3 +- .../src/main/java/module-info.java | 12 +- .../jetty/websocket/core/CloseException.java | 1 - .../jetty/websocket/core/CloseStatus.java | 6 +- .../jetty/websocket/core/Extension.java | 2 - .../jetty/websocket/core/ExtensionConfig.java | 2 + .../eclipse/jetty/websocket/core/Frame.java | 37 +- .../jetty/websocket/core/FrameHandler.java | 57 +- .../jetty/websocket/core/IncomingFrames.java | 2 +- .../jetty/websocket/core/MessageHandler.java | 24 +- .../eclipse/jetty/websocket/core/OpCode.java | 1 - .../jetty/websocket/core/OutgoingFrames.java | 4 +- .../websocket/core/WebSocketComponents.java | 1 - .../websocket/core/WebSocketConstants.java | 2 +- .../core/client/ClientUpgradeRequest.java | 24 +- .../core/client/UpgradeListener.java | 8 +- .../core/client/XmlHttpClientProvider.java | 4 +- .../core/internal/ExtensionStack.java | 10 +- .../core/internal/FragmentExtension.java | 12 +- .../core/internal/FrameCaptureExtension.java | 24 +- .../websocket/core/internal/FrameFlusher.java | 19 +- .../websocket/core/internal/Generator.java | 14 +- .../websocket/core/internal/Negotiated.java | 14 +- .../jetty/websocket/core/internal/Parser.java | 19 +- .../core/internal/WebSocketConnection.java | 21 +- .../core/internal/WebSocketCore.java | 1 - .../core/internal/WebSocketCoreSession.java | 93 +- .../core/internal/WebSocketSessionState.java | 30 +- .../internal/compress/ByteAccumulator.java | 8 +- .../internal/compress/CompressExtension.java | 15 +- .../compress/PerMessageDeflateExtension.java | 8 +- .../websocket/core/server/Handshaker.java | 8 +- .../websocket/core/server/Negotiation.java | 20 +- .../core/server/WebSocketNegotiator.java | 4 +- .../core/server/WebSocketUpgradeHandler.java | 16 +- .../server/internal/RFC6455Handshaker.java | 5 +- .../core/AbstractTestFrameHandler.java | 25 +- .../websocket/core/CapturedHexPayloads.java | 6 +- .../jetty/websocket/core/CloseStatusTest.java | 10 +- .../jetty/websocket/core/GeneratorTest.java | 83 +- .../websocket/core/IncomingFramesCapture.java | 4 +- .../websocket/core/MessageHandlerTest.java | 3 +- .../core/OutgoingNetworkBytesCapture.java | 10 +- .../jetty/websocket/core/ParserCapture.java | 2 +- .../jetty/websocket/core/ParserTest.java | 90 +- .../jetty/websocket/core/RawFrameBuilder.java | 13 +- .../core/SynchronousFrameHandler.java | 25 +- .../websocket/core/TestFrameHandler.java | 2 +- .../websocket/core/TestUpgradeHandler.java | 10 +- .../core/TestWebSocketUpgradeHandler.java | 10 +- .../websocket/core/WebSocketCloseTest.java | 14 +- .../core/WebSocketNegotiationTest.java | 4 +- .../websocket/core/WebSocketOpenTest.java | 65 +- .../jetty/websocket/core/WebSocketTester.java | 10 +- .../core/autobahn/AutobahnFrameHandler.java | 8 +- .../autobahn/AutobahnWebSocketNegotiator.java | 5 +- .../autobahn/AutobahnWebSocketServer.java | 6 +- .../client/AbstractClientFrameHandler.java | 4 +- .../client/AutobahnWebSocketClient.java | 12 +- .../core/autobahn/client/EchoHandler.java | 10 +- .../autobahn/client/UpdateReportsHandler.java | 4 +- .../core/chat/ChatWebSocketClient.java | 6 +- .../core/chat/ChatWebSocketServer.java | 10 +- .../extensions/DeflateFrameExtensionTest.java | 3 +- .../core/extensions/ExtensionConfigTest.java | 10 +- .../core/extensions/ExtensionStackTest.java | 2 - .../core/extensions/ExtensionTool.java | 4 +- .../extensions/FragmentExtensionTest.java | 18 +- .../extensions/IdentityExtensionTest.java | 8 +- .../PerMessageDeflateExtensionTest.java | 35 +- .../extensions/ValidationExtensionTest.java | 12 +- .../core/internal/FrameFlusherTest.java | 21 +- .../core/server/WebSocketServerTest.java | 1 - jetty-websocket/websocket-servlet/pom.xml | 3 +- .../servlet/FrameHandlerFactory.java | 6 +- .../servlet/ServletUpgradeRequest.java | 5 +- .../servlet/ServletUpgradeResponse.java | 1 - .../websocket/servlet/WebSocketCreator.java | 2 +- .../websocket/servlet/WebSocketMapping.java | 18 +- .../websocket/servlet/WebSocketServlet.java | 5 +- .../servlet/WebSocketServletFactory.java | 3 +- .../servlet/WebSocketUpgradeFilter.java | 11 +- .../internal/UpgradeHttpServletRequest.java | 1 - jetty-xml/pom.xml | 9 +- .../org/eclipse/jetty/xml/XmlAppendable.java | 97 +- .../eclipse/jetty/xml/XmlConfiguration.java | 73 +- .../java/org/eclipse/jetty/xml/XmlParser.java | 146 +- .../jetty/xml/ConstructorArgTestClass.java | 4 +- .../jetty/xml/DefaultTestConfiguration.java | 5 +- .../eclipse/jetty/xml/TestConfiguration.java | 41 +- .../eclipse/jetty/xml/XmlAppendableTest.java | 9 +- .../jetty/xml/XmlConfigurationTest.java | 330 ++-- .../org/eclipse/jetty/xml/XmlParserTest.java | 6 +- pom.xml | 4 +- tests/jetty-http-tools/pom.xml | 4 +- .../eclipse/jetty/http/tools/HttpTester.java | 17 +- .../matchers/HttpFieldsContainsHeaderKey.java | 3 +- .../HttpFieldsContainsHeaderValue.java | 2 +- .../tools/matchers/HttpFieldsMatchers.java | 12 +- .../jetty/http/tools/HttpTesterTest.java | 366 +++-- .../matchers/HttpFieldsMatchersTest.java | 12 +- tests/jetty-jmh/pom.xml | 3 +- .../jetty/io/jmh/ByteBufferBenchmark.java | 29 +- .../requestlog/jmh/RequestLogBenchmark.java | 37 +- .../server/jmh/DeflaterPoolBenchmark.java | 17 +- .../jetty/server/jmh/ListVsMapBenchmark.java | 83 +- .../jetty/util/StringIsEmptyBenchmark.java | 13 +- .../jetty/util/jmh/DateCacheBenchmark.java | 40 +- .../jetty/util/jmh/DateCacheNoTick.java | 125 +- .../util/jmh/DateCacheNoTickBenchmark.java | 40 +- .../util/jmh/DateCacheSimpleDateFormat.java | 122 +- .../DateCacheSimpleDateFormatBenchmark.java | 40 +- .../LogCondensePackageStringBenchmark.java | 5 +- .../util/thread/jmh/ThreadPoolBenchmark.java | 41 +- .../thread/strategy/jmh/EWYKBenchmark.java | 101 +- .../thread/strategy/jmh/TestConnection.java | 77 +- .../util/thread/strategy/jmh/TestServer.java | 34 +- tests/test-distribution/pom.xml | 3 +- .../distribution/DistributionTester.java | 22 +- .../jetty/tests/distribution/BadAppTests.java | 28 +- .../jetty/tests/distribution/CDITests.java | 16 +- .../tests/distribution/DistributionTests.java | 49 +- tests/test-http-client-transport/pom.xml | 3 +- .../jetty/http/client/AsyncIOServletTest.java | 393 ++--- .../http/client/AsyncRequestContentTest.java | 93 +- .../http/client/ConnectionStatisticsTest.java | 8 +- .../jetty/http/client/EmptyServerHandler.java | 1 - .../client/HttpChannelAssociationTest.java | 20 +- .../client/HttpClientConnectTimeoutTest.java | 22 +- .../http/client/HttpClientContinueTest.java | 335 ++-- .../client/HttpClientIdleTimeoutTest.java | 27 +- .../jetty/http/client/HttpClientLoadTest.java | 26 +- .../http/client/HttpClientStreamTest.java | 312 ++-- .../jetty/http/client/HttpClientTest.java | 113 +- .../http/client/HttpClientTimeoutTest.java | 99 +- .../HttpClientTransportDynamicTest.java | 91 +- .../jetty/http/client/HttpTrailersTest.java | 72 +- .../client/RoundRobinConnectionPoolTest.java | 30 +- .../jetty/http/client/ServerTimeoutsTest.java | 155 +- .../eclipse/jetty/http/client/Transport.java | 1 - .../jetty/http/client/TransportProvider.java | 4 +- tests/test-integration/pom.xml | 2 +- .../test/AnnotatedAsyncListenerTest.java | 1 - .../jetty/test/DefaultHandlerTest.java | 17 +- .../test/DeploymentErrorInitializer.java | 2 +- .../jetty/test/DeploymentErrorTest.java | 27 +- .../eclipse/jetty/test/DigestPostTest.java | 208 ++- .../jetty/test/HttpInputIntegrationTest.java | 345 ++--- .../jetty/test/jsp/FakeJspServlet.java | 19 +- .../jsp/JspAndDefaultWithAliasesTest.java | 48 +- .../jsp/JspAndDefaultWithoutAliasesTest.java | 45 +- .../jetty/test/rfcs/RFC2616BaseTest.java | 327 ++-- .../jetty/test/rfcs/RFC2616NIOHttpsTest.java | 2 +- .../jetty/test/support/EchoHandler.java | 1 - .../jetty/test/support/JettyDistro.java | 233 ++- .../jetty/test/support/StringUtil.java | 15 +- .../test/support/XmlBasedJettyServer.java | 29 +- .../rawhttp/HttpRequestTesterTest.java | 6 +- .../rawhttp/HttpResponseTesterTest.java | 8 +- .../test/support/rawhttp/HttpSocketImpl.java | 2 +- .../test/support/rawhttp/HttpTesting.java | 118 +- .../test/support/rawhttp/HttpsSocketImpl.java | 8 +- .../test/websocket/JavaxSimpleEchoSocket.java | 7 +- .../test/websocket/JavaxWebSocketTest.java | 5 +- .../test/websocket/JettySimpleEchoSocket.java | 1 - .../test/websocket/JettyWebSocketTest.java | 6 +- .../org/eclipse/jetty/test/jmx/JmxIT.java | 3 +- .../jetty/test/jmx/CommonComponent.java | 4 +- .../test/jmx/MyContainerInitializer.java | 9 +- .../eclipse/jetty/test/jmx/PingServlet.java | 5 +- .../org/eclipse/jetty/test/jmx/Pinger.java | 4 +- .../jetty/test/jmx/jmx/EchoerMBean.java | 2 +- tests/test-loginservice/pom.xml | 96 +- .../jetty/DataSourceLoginServiceTest.java | 227 ++- .../jetty/DatabaseLoginServiceTestServer.java | 64 +- .../eclipse/jetty/JdbcLoginServiceTest.java | 318 ++-- .../quickstart/AttributeNormalizerTest.java | 76 +- ...ttributeNormalizer_ToCanonicalUriTest.java | 29 +- .../eclipse/jetty/quickstart/EnvUtils.java | 2 +- .../jetty/quickstart/PreconfigureJNDIWar.java | 15 +- .../jetty/quickstart/PreconfigureSpecWar.java | 6 +- .../PreconfigureStandardTestWar.java | 21 +- .../jetty/quickstart/QuickStartJNDIWar.java | 8 +- .../jetty/quickstart/QuickStartSpecWar.java | 11 +- .../quickstart/QuickStartStandardTestWar.java | 8 +- .../jetty/quickstart/QuickStartTest.java | 80 +- .../eclipse/jetty/quickstart/Quickstart.java | 23 +- tests/test-sessions/pom.xml | 3 +- .../test-sessions/test-file-sessions/pom.xml | 40 +- .../session/ClusteredOrphanedSessionTest.java | 11 +- .../session/FileSessionDataStoreTest.java | 32 +- .../jetty/server/session/FileTestHelper.java | 118 +- .../server/session/TestFileSessions.java | 185 +-- .../test-gcloud-sessions/pom.xml | 98 +- .../session/ClusteredOrphanedSessionTest.java | 11 +- .../ClusteredSessionScavengingTest.java | 12 +- .../session/GCloudSessionDataStoreTest.java | 34 +- .../session/GCloudSessionTestSupport.java | 190 ++- .../session/InvalidationSessionTest.java | 11 +- .../test-hazelcast-sessions/pom.xml | 3 +- .../session/ClusteredOrphanedSessionTest.java | 1 - .../ClusteredSessionScavengingTest.java | 2 - ...lcastClusteredInvalidationSessionTest.java | 2 +- .../HazelcastSessionDataStoreTest.java | 19 +- .../session/HazelcastTestHelper.java | 70 +- .../client/ClientOrphanedSessionTest.java | 2 - .../client/ClientSessionScavengingTest.java | 1 - .../client/HazelcastSessionDataStoreTest.java | 12 +- .../test-infinispan-sessions/pom.xml | 6 +- .../session/ClusteredOrphanedSessionTest.java | 18 +- .../ClusteredSessionScavengingTest.java | 7 +- .../InfinispanSessionDataStoreTest.java | 82 +- .../server/session/InfinispanTestSupport.java | 124 +- ...emoteClusteredInvalidationSessionTest.java | 29 +- .../RemoteClusteredSessionScavengingTest.java | 25 +- .../RemoteInfinispanSessionDataStoreTest.java | 64 +- .../remote/RemoteInfinispanTestSupport.java | 102 +- .../test-sessions/test-jdbc-sessions/pom.xml | 64 +- .../ClusteredInvalidationSessionTest.java | 9 +- .../session/ClusteredOrphanedSessionTest.java | 8 +- .../ClusteredSessionMigrationTest.java | 43 +- .../ClusteredSessionScavengingTest.java | 7 +- .../session/JDBCSessionDataStoreTest.java | 46 +- .../jetty/server/session/JdbcTestHelper.java | 235 ++- .../ReloadedSessionMissingClassTest.java | 69 +- .../session/SessionTableSchemaTest.java | 108 +- .../session/WebAppObjectInSessionTest.java | 15 +- .../test-memcached-sessions/pom.xml | 92 +- .../sessions/CachingSessionDataStoreTest.java | 43 +- .../sessions/MemcachedTestHelper.java | 32 +- .../test-mongodb-sessions/pom.xml | 184 +-- .../nosql/mongodb/AttributeNameTest.java | 64 +- .../ClusteredInvalidateSessionTest.java | 8 +- .../mongodb/ClusteredOrphanedSessionTest.java | 8 +- .../ClusteredSessionScavengingTest.java | 4 +- .../mongodb/MongoSessionDataStoreTest.java | 71 +- .../jetty/nosql/mongodb/MongoTestHelper.java | 192 ++- .../test-sessions-common/pom.xml | 11 +- ...tractClusteredInvalidationSessionTest.java | 46 +- .../AbstractClusteredOrphanedSessionTest.java | 19 +- ...bstractClusteredSessionScavengingTest.java | 56 +- .../session/AbstractSessionDataStoreTest.java | 594 ++++--- .../server/session/AbstractTestBase.java | 5 +- .../AbstractWebAppObjectInSessionTest.java | 29 +- .../org/eclipse/jetty/server/session/Foo.java | 5 +- .../server/session/FooInvocationHandler.java | 13 +- .../session/TestContextScopeListener.java | 1 - .../eclipse/jetty/server/session/TestFoo.java | 11 +- .../session/TestHttpSessionListener.java | 5 - ...tHttpSessionListenerWithWebappClasses.java | 8 +- .../jetty/server/session/TestServer.java | 30 +- .../server/session/TestSessionDataStore.java | 25 +- .../session/TestSessionDataStoreFactory.java | 12 +- .../server/session/TestSessionHandler.java | 9 +- .../session/WebAppObjectInSessionServlet.java | 20 +- .../src/main/resources/Foo.java | 2 +- .../src/main/resources/ProxyableFactory.java | 5 +- .../resources/ProxyableInvocationHandler.java | 7 +- .../jetty/server/session/AsyncTest.java | 37 +- .../ClientCrossContextSessionTest.java | 22 +- .../jetty/server/session/CreationTest.java | 101 +- .../session/DefaultSessionCacheTest.java | 1083 +++++++------ .../session/DeleteUnloadableSessionTest.java | 68 +- .../server/session/DirtyAttributeTest.java | 102 +- .../jetty/server/session/IdleSessionTest.java | 73 +- .../server/session/ImmortalSessionTest.java | 46 +- .../ModifyMaxInactiveIntervalTest.java | 258 ++-- .../NonClusteredSessionScavengingTest.java | 91 +- .../server/session/NullSessionCacheTest.java | 21 +- .../server/session/RedirectSessionTest.java | 21 +- .../session/ReentrantRequestSessionTest.java | 35 +- .../server/session/RemoveSessionTest.java | 48 +- .../SameContextForwardedSessionTest.java | 50 +- .../server/session/SameNodeLoadTest.java | 81 +- .../server/session/SaveOptimizeTest.java | 108 +- .../session/SessionEvictionFailureTest.java | 67 +- .../SessionInvalidateCreateScavengeTest.java | 41 +- .../server/session/SessionListenerTest.java | 106 +- .../server/session/SessionRenewTest.java | 72 +- tests/test-webapps/test-cdi2-webapp/pom.xml | 4 +- .../eclipse/jetty/test/ManifestServerID.java | 4 +- tests/test-webapps/test-felix-webapp/pom.xml | 4 +- .../jetty/test/webapp/HTTP1Servlet.java | 1 - .../jetty/test/webapp/HTTP2Servlet.java | 1 - .../jetty/test/webapp/HTTP2FromWebAppIT.java | 8 +- tests/test-webapps/test-jaas-webapp/pom.xml | 10 +- tests/test-webapps/test-jetty-webapp/pom.xml | 60 +- .../src/main/java/com/acme/ChatServlet.java | 3 - .../src/main/java/com/acme/CookieDump.java | 55 +- .../src/main/java/com/acme/Counter.java | 10 +- .../src/main/java/com/acme/Date2Tag.java | 19 +- .../src/main/java/com/acme/DateTag.java | 60 +- .../main/java/com/acme/DispatchServlet.java | 119 +- .../src/main/java/com/acme/Dump.java | 593 +++---- .../src/main/java/com/acme/HelloWorld.java | 7 +- .../java/com/acme/JavaxWebSocketChat.java | 23 +- .../src/main/java/com/acme/LoginServlet.java | 27 +- .../src/main/java/com/acme/RegTest.java | 103 +- .../main/java/com/acme/RewriteServlet.java | 13 +- .../main/java/com/acme/SecureModeServlet.java | 18 +- .../src/main/java/com/acme/SessionDump.java | 98 +- .../src/main/java/com/acme/TagListener.java | 37 +- .../src/main/java/com/acme/TestFilter.java | 43 +- .../src/main/java/com/acme/TestListener.java | 69 +- .../java/com/acme/WebSocketChatServlet.java | 10 +- .../org/eclipse/jetty/ChatServletTest.java | 7 +- .../eclipse/jetty/DispatchServletTest.java | 31 +- .../java/org/eclipse/jetty/TestServer.java | 28 +- tests/test-webapps/test-jndi-webapp/pom.xml | 24 +- .../src/main/java/com/acme/JNDITest.java | 90 +- .../test-webapps/test-mock-resources/pom.xml | 10 +- .../main/java/com/acme/MockDataSource.java | 20 +- .../src/main/java/com/acme/MockTransport.java | 9 +- .../java/com/acme/MockUserTransaction.java | 21 +- .../jetty/TestTransparentProxyServer.java | 40 +- .../test-container-initializer/pom.xml | 26 +- .../main/java/com/acme/initializer/Foo.java | 3 +- .../com/acme/initializer/FooInitializer.java | 26 +- .../test-spec-webapp/pom.xml | 50 +- .../java/com/acme/test/AnnotatedListener.java | 17 +- .../java/com/acme/test/AnnotationTest.java | 334 ++-- .../com/acme/test/AsyncListenerServlet.java | 48 +- .../src/main/java/com/acme/test/Bar.java | 12 +- .../com/acme/test/ClassLoaderServlet.java | 12 +- .../java/com/acme/test/MultiPartTest.java | 40 +- .../com/acme/test/RoleAnnotationTest.java | 35 +- .../java/com/acme/test/SecuredServlet.java | 18 +- .../main/java/com/acme/test/TestListener.java | 48 +- .../com/acme/fragment/FragmentServlet.java | 22 +- .../tests/webapp/HttpMethodsServlet.java | 9 +- 2314 files changed, 62953 insertions(+), 67347 deletions(-) diff --git a/Jenkinsfile b/Jenkinsfile index f9cc7d719b5..452e0be92cf 100644 --- a/Jenkinsfile +++ b/Jenkinsfile @@ -60,6 +60,7 @@ pipeline { } } */ +/* stage("Checkstyle ") { agent { node { label 'linux' } } options { timeout(time: 30, unit: 'MINUTES') } @@ -67,11 +68,11 @@ pipeline { mavenBuild("jdk11", "install checkstyle:checkstyle -DskipTests", "maven3", true) recordIssues( enabledForFailure: true, aggregatingResults: true, - tools: [java(), checkStyle(pattern: '**/target/checkstyle-result.xml', reportEncoding: 'UTF-8')] + tools: [java(), checkStyle(pattern: '** /target/checkstyle-result.xml', reportEncoding: 'UTF-8')] ) } } - +*/ } } } diff --git a/aggregates/jetty-websocket-all/pom.xml b/aggregates/jetty-websocket-all/pom.xml index e402bec529c..df9eb5f59b5 100644 --- a/aggregates/jetty-websocket-all/pom.xml +++ b/aggregates/jetty-websocket-all/pom.xml @@ -63,8 +63,7 @@ - - + development http://eclipse.org/jetty diff --git a/apache-jsp/pom.xml b/apache-jsp/pom.xml index f33dc95b24a..4220f823685 100644 --- a/apache-jsp/pom.xml +++ b/apache-jsp/pom.xml @@ -1,5 +1,4 @@ - + org.eclipse.jetty jetty-project @@ -24,11 +23,9 @@ Jetty-specific ServletContainerInitializer for Jasper - org.eclipse.jetty.apache.jsp.*;version="${parsedVersion.majorVersion}.${parsedVersion.minorVersion}.${parsedVersion.incrementalVersion}", - org.eclipse.jetty.jsp.*;version="${parsedVersion.majorVersion}.${parsedVersion.minorVersion}.${parsedVersion.incrementalVersion}" + org.eclipse.jetty.apache.jsp.*;version="${parsedVersion.majorVersion}.${parsedVersion.minorVersion}.${parsedVersion.incrementalVersion}", org.eclipse.jetty.jsp.*;version="${parsedVersion.majorVersion}.${parsedVersion.minorVersion}.${parsedVersion.incrementalVersion}" - osgi.extender; - filter:="(osgi.extender=osgi.serviceloader.registrar)";resolution:=optional + osgi.extender; filter:="(osgi.extender=osgi.serviceloader.registrar)";resolution:=optional osgi.serviceloader;osgi.serviceloader=javax.servlet.ServletContainerInitializer,osgi.serviceloader;osgi.serviceloader=org.apache.juli.logging.Log diff --git a/apache-jsp/src/main/java/org/eclipse/jetty/apache/jsp/JettyJasperInitializer.java b/apache-jsp/src/main/java/org/eclipse/jetty/apache/jsp/JettyJasperInitializer.java index 50dde16f958..9538da980c2 100644 --- a/apache-jsp/src/main/java/org/eclipse/jetty/apache/jsp/JettyJasperInitializer.java +++ b/apache-jsp/src/main/java/org/eclipse/jetty/apache/jsp/JettyJasperInitializer.java @@ -23,7 +23,6 @@ import java.net.URL; import java.util.Collection; import java.util.Collections; import java.util.List; - import javax.servlet.ServletContext; import org.apache.jasper.servlet.JasperInitializer; @@ -37,7 +36,8 @@ import org.xml.sax.SAXException; */ public class JettyJasperInitializer extends JasperInitializer { - private static final Log LOG = LogFactory.getLog(JasperInitializer.class); + private static final Log LOG = LogFactory.getLog(JasperInitializer.class); + /** * NullTldScanner * @@ -47,10 +47,7 @@ public class JettyJasperInitializer extends JasperInitializer private final class NullTldScanner extends TldScanner { /** - * @param context - * @param namespaceAware - * @param validation - * @param blockExternal + * */ private NullTldScanner(ServletContext context, boolean namespaceAware, boolean validation, boolean blockExternal) { @@ -81,7 +78,7 @@ public class JettyJasperInitializer extends JasperInitializer @Override public void scanJars() { - return; //do nothing + return; //do nothing } } @@ -91,22 +88,25 @@ public class JettyJasperInitializer extends JasperInitializer */ @Override public TldScanner newTldScanner(ServletContext context, boolean namespaceAware, boolean validate, boolean blockExternal) - { + { String tmp = context.getInitParameter("org.eclipse.jetty.jsp.precompiled"); - if (tmp!=null && !tmp.equals("") && Boolean.valueOf(tmp)) + if (tmp != null && !tmp.equals("") && Boolean.valueOf(tmp)) { - if (LOG.isDebugEnabled()) LOG.debug("Jsp precompilation detected"); + if (LOG.isDebugEnabled()) + LOG.debug("Jsp precompilation detected"); return new NullTldScanner(context, namespaceAware, validate, blockExternal); } - + Collection tldUrls = (Collection)context.getAttribute("org.eclipse.jetty.tlds"); if (tldUrls != null) { - if (LOG.isDebugEnabled()) LOG.debug("Tld pre-scan detected"); - return new JettyTldPreScanned(context,namespaceAware,validate,blockExternal,tldUrls); + if (LOG.isDebugEnabled()) + LOG.debug("Tld pre-scan detected"); + return new JettyTldPreScanned(context, namespaceAware, validate, blockExternal, tldUrls); } - - if (LOG.isDebugEnabled()) LOG.debug("Defaulting to jasper tld scanning"); + + if (LOG.isDebugEnabled()) + LOG.debug("Defaulting to jasper tld scanning"); return super.newTldScanner(context, namespaceAware, validate, blockExternal); } } diff --git a/apache-jsp/src/main/java/org/eclipse/jetty/apache/jsp/JettyTldPreScanned.java b/apache-jsp/src/main/java/org/eclipse/jetty/apache/jsp/JettyTldPreScanned.java index 10e8b0db609..f7d8b15f598 100644 --- a/apache-jsp/src/main/java/org/eclipse/jetty/apache/jsp/JettyTldPreScanned.java +++ b/apache-jsp/src/main/java/org/eclipse/jetty/apache/jsp/JettyTldPreScanned.java @@ -16,12 +16,10 @@ // ======================================================================== // - package org.eclipse.jetty.apache.jsp; import java.net.URL; import java.util.Collection; - import javax.servlet.ServletContext; import org.apache.jasper.servlet.TldPreScanned; @@ -33,25 +31,24 @@ import org.apache.tomcat.util.descriptor.tld.TldResourcePath; * Change to TldPreScanned to not require that the tlds have been * pre-scanned from a jar file, but rather may be files in the * file system. - * + * * This is important for running in the jetty maven plugin * environment in multi-module builds, where modules that contain tlds * may be in the reactor at the same time as a webapp being run with the * plugin. That means that the tlds will be used from their location in * the file system, rather than from their assembled jar. - * */ public class JettyTldPreScanned extends TldPreScanned { private final Collection _jettyPreScannedURLs; - + public JettyTldPreScanned(ServletContext context, boolean namespaceAware, boolean validation, boolean blockExternal, Collection preScannedTlds) { super(context, namespaceAware, validation, blockExternal, preScannedTlds); _jettyPreScannedURLs = preScannedTlds; } - /** + /** * @see org.apache.jasper.servlet.TldPreScanned#scanJars() */ @Override @@ -65,8 +62,8 @@ public class JettyTldPreScanned extends TldPreScanned int a = str.indexOf("jar:"); int b = str.indexOf("META-INF"); if (b < 0) - throw new IllegalStateException("Bad tld url: "+str); - + throw new IllegalStateException("Bad tld url: " + str); + String path = str.substring(b); if (a >= 0) { @@ -95,5 +92,4 @@ public class JettyTldPreScanned extends TldPreScanned } } } - } diff --git a/apache-jsp/src/main/java/org/eclipse/jetty/apache/jsp/JuliLog.java b/apache-jsp/src/main/java/org/eclipse/jetty/apache/jsp/JuliLog.java index 7a16fe33425..04218fcc081 100644 --- a/apache-jsp/src/main/java/org/eclipse/jetty/apache/jsp/JuliLog.java +++ b/apache-jsp/src/main/java/org/eclipse/jetty/apache/jsp/JuliLog.java @@ -18,28 +18,28 @@ package org.eclipse.jetty.apache.jsp; -public class JuliLog implements org.apache.juli.logging.Log +public class JuliLog implements org.apache.juli.logging.Log { public static org.apache.juli.logging.Log getInstance(String name) { return new JuliLog(name); } - + private final org.eclipse.jetty.util.log.Logger _logger; private final org.eclipse.jetty.util.log.StdErrLog _stdErrLog; public JuliLog() - { - _logger=org.eclipse.jetty.util.log.Log.getRootLogger(); - _stdErrLog=(_logger instanceof org.eclipse.jetty.util.log.StdErrLog) ? (org.eclipse.jetty.util.log.StdErrLog)_logger:null; + { + _logger = org.eclipse.jetty.util.log.Log.getRootLogger(); + _stdErrLog = (_logger instanceof org.eclipse.jetty.util.log.StdErrLog) ? (org.eclipse.jetty.util.log.StdErrLog)_logger : null; } - + public JuliLog(String name) { - _logger=org.eclipse.jetty.util.log.Log.getLogger(name); - _stdErrLog=(_logger instanceof org.eclipse.jetty.util.log.StdErrLog) ? (org.eclipse.jetty.util.log.StdErrLog)_logger:null; + _logger = org.eclipse.jetty.util.log.Log.getLogger(name); + _stdErrLog = (_logger instanceof org.eclipse.jetty.util.log.StdErrLog) ? (org.eclipse.jetty.util.log.StdErrLog)_logger : null; } - + @Override public boolean isDebugEnabled() { @@ -49,31 +49,31 @@ public class JuliLog implements org.apache.juli.logging.Log @Override public boolean isErrorEnabled() { - return _stdErrLog==null?true:_stdErrLog.getLevel()<=org.eclipse.jetty.util.log.StdErrLog.LEVEL_WARN; + return _stdErrLog == null ? true : _stdErrLog.getLevel() <= org.eclipse.jetty.util.log.StdErrLog.LEVEL_WARN; } @Override public boolean isFatalEnabled() { - return _stdErrLog==null?true:_stdErrLog.getLevel()<=org.eclipse.jetty.util.log.StdErrLog.LEVEL_WARN; + return _stdErrLog == null ? true : _stdErrLog.getLevel() <= org.eclipse.jetty.util.log.StdErrLog.LEVEL_WARN; } @Override public boolean isInfoEnabled() { - return _stdErrLog==null?true:_stdErrLog.getLevel()<=org.eclipse.jetty.util.log.StdErrLog.LEVEL_INFO; + return _stdErrLog == null ? true : _stdErrLog.getLevel() <= org.eclipse.jetty.util.log.StdErrLog.LEVEL_INFO; } @Override public boolean isTraceEnabled() { - return _stdErrLog==null?true:_stdErrLog.getLevel()<=org.eclipse.jetty.util.log.StdErrLog.LEVEL_DEBUG; + return _stdErrLog == null ? true : _stdErrLog.getLevel() <= org.eclipse.jetty.util.log.StdErrLog.LEVEL_DEBUG; } @Override public boolean isWarnEnabled() { - return _stdErrLog==null?true:_stdErrLog.getLevel()<=org.eclipse.jetty.util.log.StdErrLog.LEVEL_WARN; + return _stdErrLog == null ? true : _stdErrLog.getLevel() <= org.eclipse.jetty.util.log.StdErrLog.LEVEL_WARN; } @Override @@ -82,16 +82,16 @@ public class JuliLog implements org.apache.juli.logging.Log if (message instanceof String) _logger.debug((String)message); else - _logger.debug("{}",message); + _logger.debug("{}", message); } @Override public void trace(Object message, Throwable t) { if (message instanceof String) - _logger.debug((String)message,t); + _logger.debug((String)message, t); else - _logger.debug("{}",message,t); + _logger.debug("{}", message, t); } @Override @@ -100,16 +100,16 @@ public class JuliLog implements org.apache.juli.logging.Log if (message instanceof String) _logger.debug((String)message); else - _logger.debug("{}",message); + _logger.debug("{}", message); } @Override public void debug(Object message, Throwable t) { if (message instanceof String) - _logger.debug((String)message,t); + _logger.debug((String)message, t); else - _logger.debug("{}",message,t); + _logger.debug("{}", message, t); } @Override @@ -118,16 +118,16 @@ public class JuliLog implements org.apache.juli.logging.Log if (message instanceof String) _logger.info((String)message); else - _logger.info("{}",message); + _logger.info("{}", message); } @Override public void info(Object message, Throwable t) { if (message instanceof String) - _logger.info((String)message,t); + _logger.info((String)message, t); else - _logger.info("{}",message,t); + _logger.info("{}", message, t); } @Override @@ -136,16 +136,16 @@ public class JuliLog implements org.apache.juli.logging.Log if (message instanceof String) _logger.warn((String)message); else - _logger.warn("{}",message); + _logger.warn("{}", message); } @Override public void warn(Object message, Throwable t) { if (message instanceof String) - _logger.warn((String)message,t); + _logger.warn((String)message, t); else - _logger.warn("{}",message,t); + _logger.warn("{}", message, t); } @Override @@ -154,16 +154,16 @@ public class JuliLog implements org.apache.juli.logging.Log if (message instanceof String) _logger.warn((String)message); else - _logger.warn("{}",message); + _logger.warn("{}", message); } @Override public void error(Object message, Throwable t) { if (message instanceof String) - _logger.warn((String)message,t); + _logger.warn((String)message, t); else - _logger.warn("{}",message,t); + _logger.warn("{}", message, t); } @Override @@ -172,16 +172,16 @@ public class JuliLog implements org.apache.juli.logging.Log if (message instanceof String) _logger.warn((String)message); else - _logger.warn("{}",message); + _logger.warn("{}", message); } @Override public void fatal(Object message, Throwable t) { if (message instanceof String) - _logger.warn((String)message,t); + _logger.warn((String)message, t); else - _logger.warn("{}",message,t); + _logger.warn("{}", message, t); } } diff --git a/apache-jsp/src/main/java/org/eclipse/jetty/jsp/JettyJspServlet.java b/apache-jsp/src/main/java/org/eclipse/jetty/jsp/JettyJspServlet.java index fd2b9f63307..222c4924190 100644 --- a/apache-jsp/src/main/java/org/eclipse/jetty/jsp/JettyJspServlet.java +++ b/apache-jsp/src/main/java/org/eclipse/jetty/jsp/JettyJspServlet.java @@ -22,7 +22,6 @@ import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; - import javax.servlet.RequestDispatcher; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; @@ -30,11 +29,10 @@ import javax.servlet.http.HttpServletResponse; import org.apache.jasper.servlet.JspServlet; - /** * JettyJspServlet * - * Wrapper for the jsp servlet that handles receiving requests mapped from + * Wrapper for the jsp servlet that handles receiving requests mapped from * jsp-property-groups. Mappings could be wildcard urls like "/*", which would * include welcome files, but we need those to be handled by the DefaultServlet. */ @@ -42,14 +40,10 @@ public class JettyJspServlet extends JspServlet { /** - * + * */ private static final long serialVersionUID = -5387857473125086791L; - - - - @Override public void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { @@ -59,16 +53,16 @@ public class JettyJspServlet extends JspServlet else throw new ServletException("Request not HttpServletRequest"); - String servletPath=null; - String pathInfo=null; - if (request.getAttribute(RequestDispatcher.INCLUDE_REQUEST_URI)!=null) + String servletPath = null; + String pathInfo = null; + if (request.getAttribute(RequestDispatcher.INCLUDE_REQUEST_URI) != null) { - servletPath=(String)request.getAttribute(RequestDispatcher.INCLUDE_SERVLET_PATH); - pathInfo=(String)request.getAttribute(RequestDispatcher.INCLUDE_PATH_INFO); - if (servletPath==null) + servletPath = (String)request.getAttribute(RequestDispatcher.INCLUDE_SERVLET_PATH); + pathInfo = (String)request.getAttribute(RequestDispatcher.INCLUDE_PATH_INFO); + if (servletPath == null) { - servletPath=request.getServletPath(); - pathInfo=request.getPathInfo(); + servletPath = request.getServletPath(); + pathInfo = request.getPathInfo(); } } else @@ -76,9 +70,9 @@ public class JettyJspServlet extends JspServlet servletPath = request.getServletPath(); pathInfo = request.getPathInfo(); } - - String pathInContext = addPaths(servletPath,pathInfo); - + + String pathInContext = addPaths(servletPath, pathInfo); + String jspFile = getInitParameter("jspFile"); //if this is a forced-path from a jsp-file, we want the jsp servlet to handle it, @@ -92,7 +86,7 @@ public class JettyJspServlet extends JspServlet return; } else - { + { //check if it resolves to a directory String realPath = getServletContext().getRealPath(pathInContext); if (realPath != null) @@ -107,7 +101,7 @@ public class JettyJspServlet extends JspServlet } } } - + //fall through to the normal jsp servlet handling super.service(req, resp); } @@ -121,10 +115,10 @@ public class JettyJspServlet extends JspServlet { if (servletPath.isEmpty()) return pathInfo; - - if (pathInfo==null) + + if (pathInfo == null) return servletPath; - - return servletPath+pathInfo; + + return servletPath + pathInfo; } } diff --git a/apache-jsp/src/test/java/org/eclipse/jetty/jsp/TestJettyJspServlet.java b/apache-jsp/src/test/java/org/eclipse/jetty/jsp/TestJettyJspServlet.java index 5bc7e6b9c9f..1963fc1ccf4 100644 --- a/apache-jsp/src/test/java/org/eclipse/jetty/jsp/TestJettyJspServlet.java +++ b/apache-jsp/src/test/java/org/eclipse/jetty/jsp/TestJettyJspServlet.java @@ -22,7 +22,6 @@ import java.io.File; import java.io.IOException; import java.net.URL; import java.net.URLClassLoader; - import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; @@ -54,7 +53,7 @@ public class TestJettyJspServlet private File _dir; private ServletTester _tester; - + public static class DfltServlet extends HttpServlet { @@ -62,8 +61,8 @@ public class TestJettyJspServlet { super(); } - - /** + + /** * @see javax.servlet.http.HttpServlet#doGet(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse) */ @Override @@ -72,11 +71,10 @@ public class TestJettyJspServlet resp.setContentType("html/text"); resp.getOutputStream().println("This.Is.The.Default."); } - } - + @BeforeEach - public void setUp () throws Exception + public void setUp() throws Exception { JspFactory.setDefaultFactory(new JspFactoryImpl()); _dir = MavenTestingUtils.getTestResourceDir("base"); @@ -88,12 +86,12 @@ public class TestJettyJspServlet _tester.getContext().setAttribute(InstanceManager.class.getName(), new SimpleInstanceManager()); ServletHolder dfltHolder = new ServletHolder(); dfltHolder.setName("default"); - dfltHolder.setHeldClass( DfltServlet.class); + dfltHolder.setHeldClass(DfltServlet.class); _tester.getContext().addServlet(dfltHolder, "/"); _tester.start(); } - + @AfterEach public void tearDown() throws Exception { @@ -105,8 +103,8 @@ public class TestJettyJspServlet public void testWithJsp() throws Exception { //test that an ordinary jsp is served by jsp servlet - String request = "" + - "GET /context/foo.jsp HTTP/1.1\r\n" + + String request = + "GET /context/foo.jsp HTTP/1.1\r\n" + "Host: localhost\r\n" + "Connection: close\r\n" + "\r\n"; @@ -115,14 +113,13 @@ public class TestJettyJspServlet HttpTester.Response response = HttpTester.parseResponse(rawResponse); assertThat(response.toString(), response.getContent(), not(containsString("This.Is.The.Default."))); } - - + @Test public void testWithDirectory() throws Exception { //test that a dir is served by the default servlet - String request = "" + - "GET /context/dir HTTP/1.1\r\n" + + String request = + "GET /context/dir HTTP/1.1\r\n" + "Host: localhost\r\n" + "Connection: close\r\n" + "\r\n"; diff --git a/apache-jsp/src/test/java/org/eclipse/jetty/jsp/TestJettyTldPreScanned.java b/apache-jsp/src/test/java/org/eclipse/jetty/jsp/TestJettyTldPreScanned.java index 55fdaa1ebaf..6dcc79e267b 100644 --- a/apache-jsp/src/test/java/org/eclipse/jetty/jsp/TestJettyTldPreScanned.java +++ b/apache-jsp/src/test/java/org/eclipse/jetty/jsp/TestJettyTldPreScanned.java @@ -16,11 +16,8 @@ // ======================================================================== // - package org.eclipse.jetty.jsp; -import static org.junit.jupiter.api.Assertions.*; - import java.io.File; import java.net.URL; import java.util.ArrayList; @@ -34,10 +31,12 @@ import org.eclipse.jetty.servlet.ServletContextHandler; import org.eclipse.jetty.toolchain.test.MavenTestingUtils; import org.junit.jupiter.api.Test; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.fail; + /** * TestJettyTldPreScanned - * - * */ public class TestJettyTldPreScanned { @@ -47,21 +46,21 @@ public class TestJettyTldPreScanned */ @Test public void testIt() - throws Exception + throws Exception { File jar = MavenTestingUtils.getTestResourceFile("taglib.jar"); File tld = MavenTestingUtils.getTestResourceFile("META-INF/foo-taglib.tld"); - + List list = new ArrayList<>(); - list.add(new URL("jar:"+jar.toURI().toURL().toString()+"!/META-INF/bar-taglib.tld")); + list.add(new URL("jar:" + jar.toURI().toURL().toString() + "!/META-INF/bar-taglib.tld")); list.add(tld.toURI().toURL()); - - JettyTldPreScanned preScanned = new JettyTldPreScanned(new ServletContextHandler().getServletContext(),false,false,false,list); + + JettyTldPreScanned preScanned = new JettyTldPreScanned(new ServletContextHandler().getServletContext(), false, false, false, list); preScanned.scanJars(); Map map = preScanned.getTldResourcePathTaglibXmlMap(); assertNotNull(map); assertEquals(2, map.size()); - for (TldResourcePath p: map.keySet()) + for (TldResourcePath p : map.keySet()) { URL u = p.getUrl(); TaglibXml tlx = map.get(p); @@ -70,5 +69,4 @@ public class TestJettyTldPreScanned fail("unknown tag"); } } - } diff --git a/apache-jsp/src/test/java/org/eclipse/jetty/jsp/TestJspFileNameToClass.java b/apache-jsp/src/test/java/org/eclipse/jetty/jsp/TestJspFileNameToClass.java index fda5f84224c..4d43f01756c 100644 --- a/apache-jsp/src/test/java/org/eclipse/jetty/jsp/TestJspFileNameToClass.java +++ b/apache-jsp/src/test/java/org/eclipse/jetty/jsp/TestJspFileNameToClass.java @@ -18,12 +18,11 @@ package org.eclipse.jetty.jsp; -import static org.junit.jupiter.api.Assertions.assertEquals; - import org.eclipse.jetty.servlet.ServletHolder; - import org.junit.jupiter.api.Test; +import static org.junit.jupiter.api.Assertions.assertEquals; + public class TestJspFileNameToClass { @@ -33,18 +32,17 @@ public class TestJspFileNameToClass ServletHolder h = new ServletHolder(); h.setName("test"); + assertEquals(null, h.getClassNameForJsp(null)); - assertEquals(null, h.getClassNameForJsp(null)); + assertEquals(null, h.getClassNameForJsp("")); - assertEquals(null, h.getClassNameForJsp("")); + assertEquals(null, h.getClassNameForJsp("/blah/")); - assertEquals(null, h.getClassNameForJsp("/blah/")); + assertEquals(null, h.getClassNameForJsp("//blah///")); - assertEquals(null, h.getClassNameForJsp("//blah///")); + assertEquals(null, h.getClassNameForJsp("/a/b/c/blah/")); - assertEquals(null, h.getClassNameForJsp("/a/b/c/blah/")); - - assertEquals("org.apache.jsp.a.b.c.blah", h.getClassNameForJsp("/a/b/c/blah")); + assertEquals("org.apache.jsp.a.b.c.blah", h.getClassNameForJsp("/a/b/c/blah")); assertEquals("org.apache.jsp.blah_jsp", h.getClassNameForJsp("/blah.jsp")); @@ -56,5 +54,4 @@ public class TestJspFileNameToClass assertEquals("org.apache.jsp.a.b.c.blah_jsp", h.getClassNameForJsp("a/b/c/blah.jsp")); } - } diff --git a/apache-jstl/pom.xml b/apache-jstl/pom.xml index 91335a7d7f8..df81b031bca 100644 --- a/apache-jstl/pom.xml +++ b/apache-jstl/pom.xml @@ -10,17 +10,17 @@ http://tomcat.apache.org/taglibs/standard/ jar - ${project.groupId}.apache.jstl + ${project.groupId}.apache.jstl - org.apache.maven.plugins - maven-surefire-plugin - - false - + org.apache.maven.plugins + maven-surefire-plugin + + false + org.jacoco @@ -35,36 +35,36 @@ - org.apache.taglibs - taglibs-standard-spec + org.apache.taglibs + taglibs-standard-spec - org.apache.taglibs - taglibs-standard-impl - - - - org.eclipse.jetty.toolchain - jetty-test-helper - test - - - - org.eclipse.jetty - apache-jsp - ${project.version} - test + org.apache.taglibs + taglibs-standard-impl - org.eclipse.jetty - jetty-annotations - ${project.version} - test + org.eclipse.jetty.toolchain + jetty-test-helper + test - + + + org.eclipse.jetty + apache-jsp + ${project.version} + test + + + + org.eclipse.jetty + jetty-annotations + ${project.version} + test + + org.eclipse.jetty jetty-webapp diff --git a/apache-jstl/src/test/java/org/eclipse/jetty/jstl/JspConfig.java b/apache-jstl/src/test/java/org/eclipse/jetty/jstl/JspConfig.java index 226e5e2859f..c75507f80dc 100644 --- a/apache-jstl/src/test/java/org/eclipse/jetty/jstl/JspConfig.java +++ b/apache-jstl/src/test/java/org/eclipse/jetty/jstl/JspConfig.java @@ -33,7 +33,7 @@ public class JspConfig { context.setAttribute("javax.servlet.context.tempdir", scratchDir); context.setAttribute("org.eclipse.jetty.server.webapp.ContainerIncludeJarPattern", - ".*/jetty-servlet-api-[^/]*\\.jar$|.*javax.servlet.jsp.jstl-[^/]*\\.jar|.*taglibs-standard-impl-.*\\.jar"); + ".*/jetty-servlet-api-[^/]*\\.jar$|.*javax.servlet.jsp.jstl-[^/]*\\.jar|.*taglibs-standard-impl-.*\\.jar"); context.setWar(baseUri.toASCIIString()); context.setResourceBase(baseUri.toASCIIString()); } diff --git a/apache-jstl/src/test/java/org/eclipse/jetty/jstl/JspIncludeTest.java b/apache-jstl/src/test/java/org/eclipse/jetty/jstl/JspIncludeTest.java index 8488790eba7..d1785cf0747 100644 --- a/apache-jstl/src/test/java/org/eclipse/jetty/jstl/JspIncludeTest.java +++ b/apache-jstl/src/test/java/org/eclipse/jetty/jstl/JspIncludeTest.java @@ -18,10 +18,6 @@ package org.eclipse.jetty.jstl; -import static org.hamcrest.Matchers.containsString; -import static org.hamcrest.Matchers.is; -import static org.hamcrest.MatcherAssert.assertThat; - import java.io.File; import java.io.IOException; import java.io.InputStream; @@ -37,7 +33,6 @@ import org.eclipse.jetty.toolchain.test.FS; import org.eclipse.jetty.toolchain.test.IO; import org.eclipse.jetty.toolchain.test.JAR; import org.eclipse.jetty.toolchain.test.MavenTestingUtils; -import org.eclipse.jetty.webapp.Configuration; import org.eclipse.jetty.webapp.Configurations; import org.eclipse.jetty.webapp.JettyWebXmlConfiguration; import org.eclipse.jetty.webapp.WebAppContext; @@ -45,11 +40,15 @@ import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.containsString; +import static org.hamcrest.Matchers.is; + public class JspIncludeTest { private static Server server; private static URI baseUri; - + @BeforeAll public static void startServer() throws Exception { @@ -58,31 +57,31 @@ public class JspIncludeTest ServerConnector connector = new ServerConnector(server); connector.setPort(0); server.addConnector(connector); - + // Setup WebAppContext File testWebAppDir = MavenTestingUtils.getProjectDir("src/test/webapp"); - + // Prepare WebApp libs File libDir = new File(testWebAppDir, "WEB-INF/lib"); FS.ensureDirExists(libDir); File testTagLibDir = MavenTestingUtils.getProjectDir("src/test/taglibjar"); JAR.create(testTagLibDir, new File(libDir, "testtaglib.jar")); - + // Configure WebAppContext - Configurations.setServerDefault(server).add(new JettyWebXmlConfiguration(),new AnnotationConfiguration()); - + Configurations.setServerDefault(server).add(new JettyWebXmlConfiguration(), new AnnotationConfiguration()); + WebAppContext context = new WebAppContext(); context.setContextPath("/"); - + File scratchDir = MavenTestingUtils.getTargetFile("tests/" + JspIncludeTest.class.getSimpleName() + "-scratch"); FS.ensureEmpty(scratchDir); JspConfig.init(context, testWebAppDir.toURI(), scratchDir); - + server.setHandler(context); - + // Start Server server.start(); - + // Figure out Base URI String host = connector.getHost(); if (host == null) @@ -92,13 +91,13 @@ public class JspIncludeTest int port = connector.getLocalPort(); baseUri = new URI(String.format("http://%s:%d/", host, port)); } - + @AfterAll public static void stopServer() throws Exception { server.stop(); } - + @Test public void testTopWithIncluded() throws IOException { @@ -111,13 +110,13 @@ public class JspIncludeTest try { - connection = (HttpURLConnection) uri.toURL().openConnection(); + connection = (HttpURLConnection)uri.toURL().openConnection(); connection.connect(); if (HttpURLConnection.HTTP_OK != connection.getResponseCode()) { String body = getPotentialBody(connection); String err = String.format("GET request failed (%d %s) %s%n%s", connection.getResponseCode(), connection.getResponseMessage(), - uri.toASCIIString(), body); + uri.toASCIIString(), body); throw new IOException(err); } in = connection.getInputStream(); diff --git a/apache-jstl/src/test/java/org/eclipse/jetty/jstl/JstlTest.java b/apache-jstl/src/test/java/org/eclipse/jetty/jstl/JstlTest.java index 734d9b97bd4..8580f2aa867 100644 --- a/apache-jstl/src/test/java/org/eclipse/jetty/jstl/JstlTest.java +++ b/apache-jstl/src/test/java/org/eclipse/jetty/jstl/JstlTest.java @@ -18,18 +18,12 @@ package org.eclipse.jetty.jstl; -import static org.hamcrest.Matchers.containsString; -import static org.hamcrest.Matchers.is; -import static org.hamcrest.Matchers.not; -import static org.hamcrest.MatcherAssert.assertThat; - import java.io.File; import java.io.IOException; import java.io.InputStream; import java.net.HttpURLConnection; import java.net.URI; import java.nio.charset.StandardCharsets; - import javax.servlet.jsp.JspException; import org.eclipse.jetty.annotations.AnnotationConfiguration; @@ -39,17 +33,21 @@ import org.eclipse.jetty.toolchain.test.FS; import org.eclipse.jetty.toolchain.test.JAR; import org.eclipse.jetty.toolchain.test.MavenTestingUtils; import org.eclipse.jetty.util.IO; -import org.eclipse.jetty.webapp.Configuration; import org.eclipse.jetty.webapp.WebAppContext; import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.containsString; +import static org.hamcrest.Matchers.is; +import static org.hamcrest.Matchers.not; + public class JstlTest { private static Server server; private static URI baseUri; - + @BeforeAll public static void startServer() throws Exception { @@ -58,32 +56,31 @@ public class JstlTest ServerConnector connector = new ServerConnector(server); connector.setPort(0); server.addConnector(connector); - + // Setup WebAppContext File testWebAppDir = MavenTestingUtils.getProjectDir("src/test/webapp"); - + // Prepare WebApp libs File libDir = new File(testWebAppDir, "WEB-INF/lib"); FS.ensureDirExists(libDir); File testTagLibDir = MavenTestingUtils.getProjectDir("src/test/taglibjar"); - JAR.create(testTagLibDir,new File(libDir, "testtaglib.jar")); - + JAR.create(testTagLibDir, new File(libDir, "testtaglib.jar")); + // Configure WebAppCont WebAppContext context = new WebAppContext(); context.setContextPath("/"); - + File scratchDir = MavenTestingUtils.getTargetFile("tests/" + JstlTest.class.getSimpleName() + "-scratch"); FS.ensureEmpty(scratchDir); - JspConfig.init(context,testWebAppDir.toURI(),scratchDir); - + JspConfig.init(context, testWebAppDir.toURI(), scratchDir); + context.addConfiguration(new AnnotationConfiguration()); - - + server.setHandler(context); - + // Start Server server.start(); - + // Figure out Base URI String host = connector.getHost(); if (host == null) @@ -91,22 +88,22 @@ public class JstlTest host = "localhost"; } int port = connector.getLocalPort(); - baseUri = new URI(String.format("http://%s:%d/",host,port)); + baseUri = new URI(String.format("http://%s:%d/", host, port)); } - + @AfterAll public static void stopServer() throws Exception { if (server != null) server.stop(); } - + @Test public void testUrlsBasic() throws IOException { - HttpURLConnection http = (HttpURLConnection) baseUri.resolve("/urls.jsp").toURL().openConnection(); + HttpURLConnection http = (HttpURLConnection)baseUri.resolve("/urls.jsp").toURL().openConnection(); assertThat("http response", http.getResponseCode(), is(200)); - try(InputStream input = http.getInputStream()) + try (InputStream input = http.getInputStream()) { String resp = IO.toString(input, StandardCharsets.UTF_8); assertThat("Response should be JSP processed", resp, not(containsString(""))); diff --git a/build-resources/jetty-codestyle-intellij.xml b/build-resources/jetty-codestyle-intellij.xml index 69cdd3f5655..1f276e4f415 100644 --- a/build-resources/jetty-codestyle-intellij.xml +++ b/build-resources/jetty-codestyle-intellij.xml @@ -1,4 +1,5 @@ - + + - + - - org.apache.felix - maven-bundle-plugin - true - - - Conscrypt Client ALPN - org.conscrypt;version="${conscrypt.version}",* - * - osgi.extender; filter:="(osgi.extender=osgi.serviceloader.registrar)";resolution:=optional - osgi.serviceloader; osgi.serviceloader=org.eclipse.jetty.io.ssl.ALPNProcessor$Client - <_nouses>true - - - + + org.apache.felix + maven-bundle-plugin + true + + + Conscrypt Client ALPN + org.conscrypt;version="${conscrypt.version}",* + * + osgi.extender; filter:="(osgi.extender=osgi.serviceloader.registrar)";resolution:=optional + osgi.serviceloader; osgi.serviceloader=org.eclipse.jetty.io.ssl.ALPNProcessor$Client + <_nouses>true + + + diff --git a/jetty-alpn/jetty-alpn-conscrypt-client/src/main/java/org/eclipse/jetty/alpn/conscrypt/client/ConscryptClientALPNProcessor.java b/jetty-alpn/jetty-alpn-conscrypt-client/src/main/java/org/eclipse/jetty/alpn/conscrypt/client/ConscryptClientALPNProcessor.java index 5fd47d2f2f6..2c80c687c44 100644 --- a/jetty-alpn/jetty-alpn-conscrypt-client/src/main/java/org/eclipse/jetty/alpn/conscrypt/client/ConscryptClientALPNProcessor.java +++ b/jetty-alpn/jetty-alpn-conscrypt-client/src/main/java/org/eclipse/jetty/alpn/conscrypt/client/ConscryptClientALPNProcessor.java @@ -61,7 +61,7 @@ public class ConscryptClientALPNProcessor implements ALPNProcessor.Client String[] protocols = alpn.getProtocols().toArray(new String[0]); Conscrypt.setApplicationProtocols(sslEngine, protocols); ((SslConnection.DecryptedEndPoint)connection.getEndPoint()).getSslConnection() - .addHandshakeListener(new ALPNListener(alpn)); + .addHandshakeListener(new ALPNListener(alpn)); } catch (RuntimeException x) { diff --git a/jetty-alpn/jetty-alpn-conscrypt-server/pom.xml b/jetty-alpn/jetty-alpn-conscrypt-server/pom.xml index 346eae08d92..b12dd062925 100644 --- a/jetty-alpn/jetty-alpn-conscrypt-server/pom.xml +++ b/jetty-alpn/jetty-alpn-conscrypt-server/pom.xml @@ -1,6 +1,5 @@ - + org.eclipse.jetty jetty-alpn-parent @@ -67,25 +66,24 @@ - org.apache.felix - maven-bundle-plugin - true - - - Conscrypt ALPN - org.conscrypt;version="${conscrypt.version}",* - osgi.extender; filter:="(osgi.extender=osgi.serviceloader.registrar)";resolution:=optional - osgi.serviceloader;osgi.serviceloader=org.eclipse.jetty.io.ssl.ALPNProcessor$Server - <_nouses>true - - + org.apache.felix + maven-bundle-plugin + true + + + Conscrypt ALPN + org.conscrypt;version="${conscrypt.version}",* + osgi.extender; filter:="(osgi.extender=osgi.serviceloader.registrar)";resolution:=optional + osgi.serviceloader;osgi.serviceloader=org.eclipse.jetty.io.ssl.ALPNProcessor$Server + <_nouses>true + + maven-surefire-plugin - @{argLine} ${jetty.surefire.argLine} - --add-reads org.eclipse.jetty.alpn.conscrypt.server=org.eclipse.jetty.server + @{argLine} ${jetty.surefire.argLine} --add-reads org.eclipse.jetty.alpn.conscrypt.server=org.eclipse.jetty.server diff --git a/jetty-alpn/jetty-alpn-conscrypt-server/src/main/java/org/eclipse/jetty/alpn/conscrypt/server/ConscryptServerALPNProcessor.java b/jetty-alpn/jetty-alpn-conscrypt-server/src/main/java/org/eclipse/jetty/alpn/conscrypt/server/ConscryptServerALPNProcessor.java index 6f050e82fe5..3e5a4ca2598 100644 --- a/jetty-alpn/jetty-alpn-conscrypt-server/src/main/java/org/eclipse/jetty/alpn/conscrypt/server/ConscryptServerALPNProcessor.java +++ b/jetty-alpn/jetty-alpn-conscrypt-server/src/main/java/org/eclipse/jetty/alpn/conscrypt/server/ConscryptServerALPNProcessor.java @@ -76,7 +76,6 @@ public class ConscryptServerALPNProcessor implements ALPNProcessor.Server { private final ALPNServerConnection alpnConnection; - private ALPNCallback(ALPNServerConnection connection) { alpnConnection = connection; diff --git a/jetty-alpn/jetty-alpn-java-client/pom.xml b/jetty-alpn/jetty-alpn-java-client/pom.xml index 6054bc0d7a6..fb8b4a1bb2a 100644 --- a/jetty-alpn/jetty-alpn-java-client/pom.xml +++ b/jetty-alpn/jetty-alpn-java-client/pom.xml @@ -1,7 +1,5 @@ - + org.eclipse.jetty diff --git a/jetty-alpn/jetty-alpn-java-client/src/main/java/org/eclipse/jetty/alpn/java/client/JDK9ClientALPNProcessor.java b/jetty-alpn/jetty-alpn-java-client/src/main/java/org/eclipse/jetty/alpn/java/client/JDK9ClientALPNProcessor.java index f33a97e6a3a..f8e444b051e 100644 --- a/jetty-alpn/jetty-alpn-java-client/src/main/java/org/eclipse/jetty/alpn/java/client/JDK9ClientALPNProcessor.java +++ b/jetty-alpn/jetty-alpn-java-client/src/main/java/org/eclipse/jetty/alpn/java/client/JDK9ClientALPNProcessor.java @@ -19,7 +19,6 @@ package org.eclipse.jetty.alpn.java.client; import java.util.List; - import javax.net.ssl.SSLEngine; import javax.net.ssl.SSLParameters; @@ -39,15 +38,15 @@ public class JDK9ClientALPNProcessor implements ALPNProcessor.Client @Override public void init() { - if (JavaVersion.VERSION.getPlatform()<9) - throw new IllegalStateException(this + " not applicable for java "+JavaVersion.VERSION); + if (JavaVersion.VERSION.getPlatform() < 9) + throw new IllegalStateException(this + " not applicable for java " + JavaVersion.VERSION); } @Override public boolean appliesTo(SSLEngine sslEngine) { Module module = sslEngine.getClass().getModule(); - return module!=null && "java.base".equals(module.getName()); + return module != null && "java.base".equals(module.getName()); } @Override @@ -59,7 +58,7 @@ public class JDK9ClientALPNProcessor implements ALPNProcessor.Client sslParameters.setApplicationProtocols(protocols.toArray(new String[protocols.size()])); sslEngine.setSSLParameters(sslParameters); ((DecryptedEndPoint)connection.getEndPoint()).getSslConnection() - .addHandshakeListener(new ALPNListener(alpn)); + .addHandshakeListener(new ALPNListener(alpn)); } private final class ALPNListener implements SslHandshakeListener diff --git a/jetty-alpn/jetty-alpn-java-server/pom.xml b/jetty-alpn/jetty-alpn-java-server/pom.xml index 617e180865b..918725febde 100644 --- a/jetty-alpn/jetty-alpn-java-server/pom.xml +++ b/jetty-alpn/jetty-alpn-java-server/pom.xml @@ -1,7 +1,5 @@ - + org.eclipse.jetty jetty-alpn-parent @@ -22,8 +20,7 @@ maven-surefire-plugin - @{argLine} ${jetty.surefire.argLine} - --add-reads org.eclipse.jetty.alpn.java.server=org.eclipse.jetty.server + @{argLine} ${jetty.surefire.argLine} --add-reads org.eclipse.jetty.alpn.java.server=org.eclipse.jetty.server diff --git a/jetty-alpn/jetty-alpn-java-server/src/main/java/org/eclipse/jetty/alpn/java/server/JDK9ServerALPNProcessor.java b/jetty-alpn/jetty-alpn-java-server/src/main/java/org/eclipse/jetty/alpn/java/server/JDK9ServerALPNProcessor.java index fbacbdac97f..ca091a96e15 100644 --- a/jetty-alpn/jetty-alpn-java-server/src/main/java/org/eclipse/jetty/alpn/java/server/JDK9ServerALPNProcessor.java +++ b/jetty-alpn/jetty-alpn-java-server/src/main/java/org/eclipse/jetty/alpn/java/server/JDK9ServerALPNProcessor.java @@ -20,7 +20,6 @@ package org.eclipse.jetty.alpn.java.server; import java.util.List; import java.util.function.BiFunction; - import javax.net.ssl.SSLEngine; import org.eclipse.jetty.alpn.server.ALPNServerConnection; @@ -39,15 +38,15 @@ public class JDK9ServerALPNProcessor implements ALPNProcessor.Server, SslHandsha @Override public void init() { - if (JavaVersion.VERSION.getPlatform()<9) - throw new IllegalStateException(this + " not applicable for java "+JavaVersion.VERSION); + if (JavaVersion.VERSION.getPlatform() < 9) + throw new IllegalStateException(this + " not applicable for java " + JavaVersion.VERSION); } @Override public boolean appliesTo(SSLEngine sslEngine) { Module module = sslEngine.getClass().getModule(); - return module!=null && "java.base".equals(module.getName()); + return module != null && "java.base".equals(module.getName()); } @Override @@ -56,7 +55,7 @@ public class JDK9ServerALPNProcessor implements ALPNProcessor.Server, SslHandsha sslEngine.setHandshakeApplicationProtocolSelector(new ALPNCallback((ALPNServerConnection)connection)); } - private final class ALPNCallback implements BiFunction,String>, SslHandshakeListener + private final class ALPNCallback implements BiFunction, String>, SslHandshakeListener { private final ALPNServerConnection alpnConnection; @@ -81,7 +80,7 @@ public class JDK9ServerALPNProcessor implements ALPNProcessor.Server, SslHandsha String protocol = alpnConnection.getProtocol(); if (LOG.isDebugEnabled()) LOG.debug("TLS handshake succeeded, protocol={} for {}", protocol, alpnConnection); - if (protocol ==null) + if (protocol == null) alpnConnection.unsupported(); } diff --git a/jetty-alpn/jetty-alpn-java-server/src/test/java/org/eclipse/jetty/alpn/java/server/JDK9ALPNTest.java b/jetty-alpn/jetty-alpn-java-server/src/test/java/org/eclipse/jetty/alpn/java/server/JDK9ALPNTest.java index 5fcc2feca09..ef58bf7ca8f 100644 --- a/jetty-alpn/jetty-alpn-java-server/src/test/java/org/eclipse/jetty/alpn/java/server/JDK9ALPNTest.java +++ b/jetty-alpn/jetty-alpn-java-server/src/test/java/org/eclipse/jetty/alpn/java/server/JDK9ALPNTest.java @@ -23,7 +23,6 @@ import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.nio.charset.StandardCharsets; - import javax.net.ssl.SSLContext; import javax.net.ssl.SSLParameters; import javax.net.ssl.SSLSocket; @@ -105,8 +104,8 @@ public class JDK9ALPNTest client.startHandshake(); OutputStream output = client.getOutputStream(); - output.write(("" + - "GET / HTTP/1.1\r\n" + + output.write(( + "GET / HTTP/1.1\r\n" + "Host: localhost\r\n" + "Connection: close\r\n" + "\r\n" + @@ -150,8 +149,8 @@ public class JDK9ALPNTest client.startHandshake(); OutputStream output = client.getOutputStream(); - output.write(("" + - "GET / HTTP/1.1\r\n" + + output.write(( + "GET / HTTP/1.1\r\n" + "Host: localhost\r\n" + "Connection: close\r\n" + "\r\n" + diff --git a/jetty-alpn/jetty-alpn-server/pom.xml b/jetty-alpn/jetty-alpn-server/pom.xml index de37e4ca99f..0cf6794b9fa 100644 --- a/jetty-alpn/jetty-alpn-server/pom.xml +++ b/jetty-alpn/jetty-alpn-server/pom.xml @@ -15,8 +15,8 @@ - org.apache.maven.plugins - maven-source-plugin + org.apache.maven.plugins + maven-source-plugin org.codehaus.mojo @@ -29,11 +29,11 @@ org.apache.felix maven-bundle-plugin - - ${bundle-symbolic-name};singleton:=true - org.eclipse.jetty.alpn.server,* - osgi.extender; filter:="(osgi.extender=osgi.serviceloader.processor)";resolution:=optional, osgi.serviceloader; filter:="(osgi.serviceloader=org.eclipse.jetty.io.ssl.ALPNProcessor$Server)";resolution:=optional;cardinality:=multiple - + + ${bundle-symbolic-name};singleton:=true + org.eclipse.jetty.alpn.server,* + osgi.extender; filter:="(osgi.extender=osgi.serviceloader.processor)";resolution:=optional, osgi.serviceloader; filter:="(osgi.serviceloader=org.eclipse.jetty.io.ssl.ALPNProcessor$Server)";resolution:=optional;cardinality:=multiple + diff --git a/jetty-alpn/jetty-alpn-server/src/main/java/org/eclipse/jetty/alpn/server/ALPNServerConnection.java b/jetty-alpn/jetty-alpn-server/src/main/java/org/eclipse/jetty/alpn/server/ALPNServerConnection.java index 0d724f74abe..bdc448be261 100644 --- a/jetty-alpn/jetty-alpn-server/src/main/java/org/eclipse/jetty/alpn/server/ALPNServerConnection.java +++ b/jetty-alpn/jetty-alpn-server/src/main/java/org/eclipse/jetty/alpn/server/ALPNServerConnection.java @@ -20,7 +20,6 @@ package org.eclipse.jetty.alpn.server; import java.util.Collections; import java.util.List; - import javax.net.ssl.SSLEngine; import javax.net.ssl.SSLSession; @@ -44,7 +43,7 @@ public class ALPNServerConnection extends NegotiatingServerConnection { select(Collections.emptyList()); } - + public void select(List clientProtocols) { SSLEngine sslEngine = getSSLEngine(); diff --git a/jetty-alpn/jetty-alpn-server/src/main/java/org/eclipse/jetty/alpn/server/ALPNServerConnectionFactory.java b/jetty-alpn/jetty-alpn-server/src/main/java/org/eclipse/jetty/alpn/server/ALPNServerConnectionFactory.java index fdf65b9d379..452431863e2 100644 --- a/jetty-alpn/jetty-alpn-server/src/main/java/org/eclipse/jetty/alpn/server/ALPNServerConnectionFactory.java +++ b/jetty-alpn/jetty-alpn-server/src/main/java/org/eclipse/jetty/alpn/server/ALPNServerConnectionFactory.java @@ -23,7 +23,6 @@ import java.util.Arrays; import java.util.Iterator; import java.util.List; import java.util.ServiceLoader; - import javax.net.ssl.SSLEngine; import org.eclipse.jetty.io.AbstractConnection; @@ -45,21 +44,21 @@ public class ALPNServerConnectionFactory extends NegotiatingServerConnectionFact { this(protocols.trim().split(",", 0)); } - + public ALPNServerConnectionFactory(@Name("protocols") String... protocols) { super("alpn", protocols); IllegalStateException failure = new IllegalStateException("No Server ALPNProcessors!"); // Use a for loop on iterator so load exceptions can be caught and ignored - for (Iterator i = ServiceLoader.load(Server.class).iterator(); i.hasNext();) + for (Iterator i = ServiceLoader.load(Server.class).iterator(); i.hasNext(); ) { Server processor; try { processor = i.next(); } - catch(Throwable x) + catch (Throwable x) { if (LOG.isDebugEnabled()) LOG.debug(x); @@ -81,7 +80,7 @@ public class ALPNServerConnectionFactory extends NegotiatingServerConnectionFact failure.addSuppressed(x); } } - + if (LOG.isDebugEnabled()) { LOG.debug("protocols: {}", Arrays.asList(protocols)); @@ -106,9 +105,9 @@ public class ALPNServerConnectionFactory extends NegotiatingServerConnectionFact return connection; } } - + if (LOG.isDebugEnabled()) - LOG.debug("No ALPNProcessor: {} {}",engine,endPoint); + LOG.debug("No ALPNProcessor: {} {}", engine, endPoint); throw new IllegalStateException("Connection rejected: No ALPN Processor for " + engine.getClass().getName() + " from " + processors); } } diff --git a/jetty-alpn/pom.xml b/jetty-alpn/pom.xml index 5b8fde10bb6..7263f3de469 100644 --- a/jetty-alpn/pom.xml +++ b/jetty-alpn/pom.xml @@ -1,6 +1,4 @@ - + org.eclipse.jetty jetty-project diff --git a/jetty-annotations/pom.xml b/jetty-annotations/pom.xml index 9dbc7522bc1..8eadf27f3b3 100644 --- a/jetty-annotations/pom.xml +++ b/jetty-annotations/pom.xml @@ -1,5 +1,4 @@ - + org.eclipse.jetty jetty-project @@ -21,8 +20,7 @@ maven-surefire-plugin - @{argLine} ${jetty.surefire.argLine} - --add-opens org.eclipse.jetty.annotations/org.eclipse.jetty.annotations.resources=org.eclipse.jetty.plus + @{argLine} ${jetty.surefire.argLine} --add-opens org.eclipse.jetty.annotations/org.eclipse.jetty.annotations.resources=org.eclipse.jetty.plus @@ -33,9 +31,7 @@ org.objectweb.asm;version="5",* - osgi.serviceloader; - filter:="(osgi.serviceloader=javax.servlet.ServletContainerInitializer)";resolution:=optional;cardinality:=multiple, - osgi.extender; filter:="(osgi.extender=osgi.serviceloader.processor)";resolution:=optional + osgi.serviceloader; filter:="(osgi.serviceloader=javax.servlet.ServletContainerInitializer)";resolution:=optional;cardinality:=multiple, osgi.extender; filter:="(osgi.extender=osgi.serviceloader.processor)";resolution:=optional diff --git a/jetty-annotations/src/main/java/org/eclipse/jetty/annotations/AbstractDiscoverableAnnotationHandler.java b/jetty-annotations/src/main/java/org/eclipse/jetty/annotations/AbstractDiscoverableAnnotationHandler.java index ab9a418c84c..220f5c8040e 100644 --- a/jetty-annotations/src/main/java/org/eclipse/jetty/annotations/AbstractDiscoverableAnnotationHandler.java +++ b/jetty-annotations/src/main/java/org/eclipse/jetty/annotations/AbstractDiscoverableAnnotationHandler.java @@ -26,22 +26,18 @@ import org.eclipse.jetty.webapp.WebAppContext; * DiscoverableAnnotationHandler * * Base class for handling the discovery of an annotation. - * */ public abstract class AbstractDiscoverableAnnotationHandler extends AbstractHandler { protected WebAppContext _context; - public AbstractDiscoverableAnnotationHandler(WebAppContext context) { _context = context; } - - public void addAnnotation (DiscoveredAnnotation a) + public void addAnnotation(DiscoveredAnnotation a) { _context.getMetaData().addDiscoveredAnnotation(a); } - } diff --git a/jetty-annotations/src/main/java/org/eclipse/jetty/annotations/AnnotationConfiguration.java b/jetty-annotations/src/main/java/org/eclipse/jetty/annotations/AnnotationConfiguration.java index 950491573f3..071cfe89651 100644 --- a/jetty-annotations/src/main/java/org/eclipse/jetty/annotations/AnnotationConfiguration.java +++ b/jetty-annotations/src/main/java/org/eclipse/jetty/annotations/AnnotationConfiguration.java @@ -70,30 +70,29 @@ import org.eclipse.jetty.webapp.WebXmlConfiguration; public class AnnotationConfiguration extends AbstractConfiguration { private static final Logger LOG = Log.getLogger(AnnotationConfiguration.class); - + public static final String SERVLET_CONTAINER_INITIALIZER_EXCLUSION_PATTERN = "org.eclipse.jetty.containerInitializerExclusionPattern"; public static final String SERVLET_CONTAINER_INITIALIZER_ORDER = "org.eclipse.jetty.containerInitializerOrder"; - public static final String CLASS_INHERITANCE_MAP = "org.eclipse.jetty.classInheritanceMap"; + public static final String CLASS_INHERITANCE_MAP = "org.eclipse.jetty.classInheritanceMap"; public static final String CONTAINER_INITIALIZERS = "org.eclipse.jetty.containerInitializers"; public static final String CONTAINER_INITIALIZER_STARTER = "org.eclipse.jetty.containerInitializerStarter"; public static final String MULTI_THREADED = "org.eclipse.jetty.annotations.multiThreaded"; public static final String MAX_SCAN_WAIT = "org.eclipse.jetty.annotations.maxWait"; - - - public static final int DEFAULT_MAX_SCAN_WAIT = 60; /* time in sec */ + + public static final int DEFAULT_MAX_SCAN_WAIT = 60; /* time in sec */ public static final boolean DEFAULT_MULTI_THREADED = true; - + protected final List _discoverableAnnotationHandlers = new ArrayList<>(); protected ClassInheritanceHandler _classInheritanceHandler; protected final List _containerInitializerAnnotationHandlers = new ArrayList<>(); - + protected List _parserTasks; protected CounterStatistic _containerPathStats; protected CounterStatistic _webInfLibStats; protected CounterStatistic _webInfClassesStats; protected Pattern _sciExcludePattern; - protected List _initializers; + protected List _initializers; public AnnotationConfiguration() { @@ -102,50 +101,47 @@ public class AnnotationConfiguration extends AbstractConfiguration protectAndExpose("org.eclipse.jetty.util.annotations."); hide("org.objectweb.asm."); } - + /** * TimeStatistic * * Simple class to capture elapsed time of an operation. - * */ - public class TimeStatistic + public class TimeStatistic { public long _start = 0; public long _end = 0; - - public void start () + + public void start() { _start = System.nanoTime(); } - - public void end () + + public void end() { _end = System.nanoTime(); } - + public long getStart() { return _start; } - - public long getEnd () + + public long getEnd() { return _end; } - - public long getElapsed () + + public long getElapsed() { - return (_end > _start?(_end-_start):0); + return (_end > _start ? (_end - _start) : 0); } } - - + /** * ParserTask * * Task to executing scanning of a resource for annotations. - * */ public class ParserTask implements Callable { @@ -154,43 +150,42 @@ public class AnnotationConfiguration extends AbstractConfiguration protected final Set _handlers; protected final Resource _resource; protected TimeStatistic _stat; - - public ParserTask (AnnotationParser parser, Sethandlers, Resource resource) + + public ParserTask(AnnotationParser parser, Set handlers, Resource resource) { _parser = parser; _handlers = handlers; _resource = resource; } - + public void setStatistic(TimeStatistic stat) { - _stat = stat; + _stat = stat; } @Override public Void call() throws Exception - { + { if (_stat != null) _stat.start(); if (_parser != null) - _parser.parse(_handlers, _resource); + _parser.parse(_handlers, _resource); if (_stat != null) _stat.end(); return null; } - + public TimeStatistic getStatistic() { return _stat; } - + public Resource getResource() { return _resource; - } + } } - - + /** * ServletContainerInitializerOrdering * @@ -199,35 +194,34 @@ public class AnnotationConfiguration extends AbstractConfiguration * wildcard which matches any other ServletContainerInitializer name not already * matched. */ - public class ServletContainerInitializerOrdering + public class ServletContainerInitializerOrdering { private Map _indexMap = new HashMap(); private Integer _star = null; private String _ordering = null; - - public ServletContainerInitializerOrdering (String ordering) + + public ServletContainerInitializerOrdering(String ordering) { if (ordering != null) { _ordering = ordering; - + String[] tmp = StringUtil.csvSplit(ordering); - - for (int i=0; i { private ServletContainerInitializerOrdering _ordering; - - - public ServletContainerInitializerComparator (ServletContainerInitializerOrdering ordering) + + public ServletContainerInitializerComparator(ServletContainerInitializerOrdering ordering) { _ordering = ordering; } @@ -308,74 +302,75 @@ public class AnnotationConfiguration extends AbstractConfiguration @Override public int compare(ServletContainerInitializer sci1, ServletContainerInitializer sci2) { - String c1 = (sci1 != null? sci1.getClass().getName() : null); - String c2 = (sci2 != null? sci2.getClass().getName() : null); + String c1 = (sci1 != null ? sci1.getClass().getName() : null); + String c2 = (sci2 != null ? sci2.getClass().getName() : null); if (c1 == null && c2 == null) return 0; - + int i1 = _ordering.getIndexOf(c1); if (i1 < 0 && _ordering.hasWildcard()) i1 = _ordering.getWildcardIndex(); int i2 = _ordering.getIndexOf(c2); if (i2 < 0 && _ordering.hasWildcard()) i2 = _ordering.getWildcardIndex(); - + return Integer.compare(i1, i2); } } - + @Override public void preConfigure(final WebAppContext context) throws Exception { String tmp = (String)context.getAttribute(SERVLET_CONTAINER_INITIALIZER_EXCLUSION_PATTERN); - _sciExcludePattern = (tmp==null?null:Pattern.compile(tmp)); + _sciExcludePattern = (tmp == null ? null : Pattern.compile(tmp)); } - + public void addDiscoverableAnnotationHandler(AbstractDiscoverableAnnotationHandler handler) { _discoverableAnnotationHandlers.add(handler); } - /** + /** * @see org.eclipse.jetty.webapp.AbstractConfiguration#configure(org.eclipse.jetty.webapp.WebAppContext) */ @Override public void configure(WebAppContext context) throws Exception { - context.getObjectFactory().addDecorator(new AnnotationDecorator(context)); + context.getObjectFactory().addDecorator(new AnnotationDecorator(context)); - if (!context.getMetaData().isMetaDataComplete()) - { - //If metadata isn't complete, if this is a servlet 3 webapp or isConfigDiscovered is true, we need to search for annotations - if (context.getServletContext().getEffectiveMajorVersion() >= 3 || context.isConfigurationDiscovered()) - { - _discoverableAnnotationHandlers.add(new WebServletAnnotationHandler(context)); - _discoverableAnnotationHandlers.add(new WebFilterAnnotationHandler(context)); - _discoverableAnnotationHandlers.add(new WebListenerAnnotationHandler(context)); - } - } - - //Regardless of metadata, if there are any ServletContainerInitializers with @HandlesTypes, then we need to scan all the - //classes so we can call their onStartup() methods correctly - createServletContainerInitializerAnnotationHandlers(context, getNonExcludedInitializers(context)); + if (!context.getMetaData().isMetaDataComplete()) + { + //If metadata isn't complete, if this is a servlet 3 webapp or isConfigDiscovered is true, we need to search for annotations + if (context.getServletContext().getEffectiveMajorVersion() >= 3 || context.isConfigurationDiscovered()) + { + _discoverableAnnotationHandlers.add(new WebServletAnnotationHandler(context)); + _discoverableAnnotationHandlers.add(new WebFilterAnnotationHandler(context)); + _discoverableAnnotationHandlers.add(new WebListenerAnnotationHandler(context)); + } + } - if (!_discoverableAnnotationHandlers.isEmpty() || _classInheritanceHandler != null || !_containerInitializerAnnotationHandlers.isEmpty()) - scanForAnnotations(context); + //Regardless of metadata, if there are any ServletContainerInitializers with @HandlesTypes, then we need to scan all the + //classes so we can call their onStartup() methods correctly + createServletContainerInitializerAnnotationHandlers(context, getNonExcludedInitializers(context)); - // Resolve container initializers - List initializers = - (List)context.getAttribute(AnnotationConfiguration.CONTAINER_INITIALIZERS); - if (initializers != null && initializers.size()>0) - { - Map> map = ( Map>) context.getAttribute(AnnotationConfiguration.CLASS_INHERITANCE_MAP); - for (ContainerInitializer i : initializers) - i.resolveClasses(context,map); - } + if (!_discoverableAnnotationHandlers.isEmpty() || _classInheritanceHandler != null || !_containerInitializerAnnotationHandlers.isEmpty()) + scanForAnnotations(context); + + // Resolve container initializers + List initializers = + (List)context.getAttribute(AnnotationConfiguration.CONTAINER_INITIALIZERS); + if (initializers != null && initializers.size() > 0) + { + Map> map = (Map>)context.getAttribute(AnnotationConfiguration.CLASS_INHERITANCE_MAP); + for (ContainerInitializer i : initializers) + { + i.resolveClasses(context, map); + } + } } - - /** + /** * @see org.eclipse.jetty.webapp.AbstractConfiguration#postConfigure(org.eclipse.jetty.webapp.WebAppContext) */ @Override @@ -390,7 +385,7 @@ public class AnnotationConfiguration extends AbstractConfiguration if (initializers != null) initializers.clear(); context.removeAttribute(CONTAINER_INITIALIZERS); - + if (_discoverableAnnotationHandlers != null) _discoverableAnnotationHandlers.clear(); @@ -416,37 +411,33 @@ public class AnnotationConfiguration extends AbstractConfiguration super.postConfigure(context); } - - - + /** * Perform scanning of classes for annotations - * + * * @param context the context for the scan * @throws Exception if unable to scan */ - protected void scanForAnnotations (WebAppContext context) - throws Exception + protected void scanForAnnotations(WebAppContext context) + throws Exception { int javaPlatform = 0; Object target = context.getAttribute(JavaVersion.JAVA_TARGET_PLATFORM); - if (target!=null) + if (target != null) javaPlatform = Integer.parseInt(target.toString()); AnnotationParser parser = createAnnotationParser(javaPlatform); _parserTasks = new ArrayList(); - long start = 0; - + long start = 0; if (LOG.isDebugEnabled()) - LOG.debug("Annotation scanning commencing: webxml={}, metadatacomplete={}, configurationDiscovered={}, multiThreaded={}, maxScanWait={}", - context.getServletContext().getEffectiveMajorVersion(), - context.getMetaData().isMetaDataComplete(), - context.isConfigurationDiscovered(), - isUseMultiThreading(context), - getMaxScanWait(context)); + LOG.debug("Annotation scanning commencing: webxml={}, metadatacomplete={}, configurationDiscovered={}, multiThreaded={}, maxScanWait={}", + context.getServletContext().getEffectiveMajorVersion(), + context.getMetaData().isMetaDataComplete(), + context.isConfigurationDiscovered(), + isUseMultiThreading(context), + getMaxScanWait(context)); - parseContainerPath(context, parser); //email from Rajiv Mordani jsrs 315 7 April 2010 // If there is a then the ordering should be @@ -454,16 +445,16 @@ public class AnnotationConfiguration extends AbstractConfiguration // In case there is no others then it is // WEB-INF/classes + order of the elements. parseWebInfClasses(context, parser); - parseWebInfLib (context, parser); - + parseWebInfLib(context, parser); + start = System.nanoTime(); - + //execute scan, either effectively synchronously (1 thread only), or asynchronously (limited by number of processors available) - final Semaphore task_limit = (isUseMultiThreading(context)? new Semaphore(ProcessorUtils.availableProcessors()):new Semaphore( 1)); + final Semaphore task_limit = (isUseMultiThreading(context) ? new Semaphore(ProcessorUtils.availableProcessors()) : new Semaphore(1)); final CountDownLatch latch = new CountDownLatch(_parserTasks.size()); final MultiException me = new MultiException(); - - for (final ParserTask p:_parserTasks) + + for (final ParserTask p : _parserTasks) { task_limit.acquire(); context.getServer().getThreadPool().execute(new Runnable() @@ -471,48 +462,48 @@ public class AnnotationConfiguration extends AbstractConfiguration @Override public void run() { - try - { - p.call(); - } - catch (Exception e) - { - me.add(e); - } - finally - { - task_limit.release(); - latch.countDown(); - } - } + try + { + p.call(); + } + catch (Exception e) + { + me.add(e); + } + finally + { + task_limit.release(); + latch.countDown(); + } + } }); } - + boolean timeout = !latch.await(getMaxScanWait(context), TimeUnit.SECONDS); - long elapsedMs = TimeUnit.MILLISECONDS.convert(System.nanoTime()-start, TimeUnit.NANOSECONDS); - - LOG.info("Scanning elapsed time={}ms",elapsedMs); - + long elapsedMs = TimeUnit.MILLISECONDS.convert(System.nanoTime() - start, TimeUnit.NANOSECONDS); + + LOG.info("Scanning elapsed time={}ms", elapsedMs); + if (LOG.isDebugEnabled()) { - for (ParserTask p:_parserTasks) + for (ParserTask p : _parserTasks) + { LOG.debug("Scanned {} in {}ms", p.getResource(), TimeUnit.MILLISECONDS.convert(p.getStatistic().getElapsed(), TimeUnit.NANOSECONDS)); + } LOG.debug("Scanned {} container path jars, {} WEB-INF/lib jars, {} WEB-INF/classes dirs in {}ms for context {}", - (_containerPathStats==null?-1:_containerPathStats.getTotal()), - (_webInfLibStats==null?-1:_webInfLibStats.getTotal()), - (_webInfClassesStats==null?-1:_webInfClassesStats.getTotal()), - elapsedMs, - context); + (_containerPathStats == null ? -1 : _containerPathStats.getTotal()), + (_webInfLibStats == null ? -1 : _webInfLibStats.getTotal()), + (_webInfClassesStats == null ? -1 : _webInfClassesStats.getTotal()), + elapsedMs, + context); } if (timeout) me.add(new Exception("Timeout scanning annotations")); - me.ifExceptionThrow(); + me.ifExceptionThrow(); } - - /** * @param javaPlatform The java platform to scan for. * @return a new AnnotationParser. This method can be overridden to use a different implementation of @@ -522,9 +513,10 @@ public class AnnotationConfiguration extends AbstractConfiguration { return new AnnotationParser(javaPlatform); } - + /** * Check if we should use multiple threads to scan for annotations or not + * * @param context the context of the multi threaded setting * @return true if multi threading is enabled on the context, server, or via a System property. * @see #MULTI_THREADED @@ -547,16 +539,14 @@ public class AnnotationConfiguration extends AbstractConfiguration return Boolean.parseBoolean(System.getProperty(MULTI_THREADED, Boolean.toString(DEFAULT_MULTI_THREADED))); } - - /** * Work out how long we should wait for the async scanning to occur. - * + * * @param context the context of the max scan wait setting * @return the max scan wait setting on the context, or server, or via a System property. * @see #MAX_SCAN_WAIT */ - protected int getMaxScanWait (WebAppContext context) + protected int getMaxScanWait(WebAppContext context) { //try context attribute to get max time in sec to wait for scan completion Object o = context.getAttribute(MAX_SCAN_WAIT); @@ -573,8 +563,8 @@ public class AnnotationConfiguration extends AbstractConfiguration //try system property to get max time in sec to wait for scan completion return Integer.getInteger(MAX_SCAN_WAIT, DEFAULT_MAX_SCAN_WAIT).intValue(); } - - /** + + /** * @see org.eclipse.jetty.webapp.AbstractConfiguration#cloneConfigure(org.eclipse.jetty.webapp.WebAppContext, org.eclipse.jetty.webapp.WebAppContext) */ @Override @@ -583,8 +573,8 @@ public class AnnotationConfiguration extends AbstractConfiguration context.getObjectFactory().addDecorator(new AnnotationDecorator(context)); } - public void createServletContainerInitializerAnnotationHandlers (WebAppContext context, List scis) - throws Exception + public void createServletContainerInitializerAnnotationHandlers(WebAppContext context, List scis) + throws Exception { if (scis == null || scis.isEmpty()) return; // nothing to do @@ -597,14 +587,17 @@ public class AnnotationConfiguration extends AbstractConfiguration HandlesTypes annotation = service.getClass().getAnnotation(HandlesTypes.class); ContainerInitializer initializer = null; if (annotation != null) - { + { //There is a HandlesTypes annotation on the on the ServletContainerInitializer Class[] classes = annotation.value(); if (classes != null) { - if (LOG.isDebugEnabled()){LOG.debug("HandlesTypes {} on initializer {}",Arrays.asList(classes),service.getClass());} - + if (LOG.isDebugEnabled()) + { + LOG.debug("HandlesTypes {} on initializer {}", Arrays.asList(classes), service.getClass()); + } + initializer = new ContainerInitializer(service, classes); //If we haven't already done so, we need to register a handler that will @@ -617,33 +610,35 @@ public class AnnotationConfiguration extends AbstractConfiguration _classInheritanceHandler = new ClassInheritanceHandler(map); } - for (Class c: classes) + for (Class c : classes) { //The value of one of the HandlesTypes classes is actually an Annotation itself so //register a handler for it if (c.isAnnotation()) { - if (LOG.isDebugEnabled()) LOG.debug("Registering annotation handler for "+c.getName()); - _containerInitializerAnnotationHandlers.add(new ContainerInitializerAnnotationHandler(initializer, c)); + if (LOG.isDebugEnabled()) + LOG.debug("Registering annotation handler for " + c.getName()); + _containerInitializerAnnotationHandlers.add(new ContainerInitializerAnnotationHandler(initializer, c)); } } } else { initializer = new ContainerInitializer(service, null); - if (LOG.isDebugEnabled()) LOG.debug("No classes in HandlesTypes on initializer "+service.getClass()); + if (LOG.isDebugEnabled()) + LOG.debug("No classes in HandlesTypes on initializer " + service.getClass()); } } else { initializer = new ContainerInitializer(service, null); - if (LOG.isDebugEnabled()) LOG.debug("No HandlesTypes annotation on initializer "+service.getClass()); + if (LOG.isDebugEnabled()) + LOG.debug("No HandlesTypes annotation on initializer " + service.getClass()); } - + initializers.add(initializer); } - - + //add a bean to the context which will call the servletcontainerinitializers when appropriate ServletContainerInitializersStarter starter = (ServletContainerInitializersStarter)context.getAttribute(CONTAINER_INITIALIZER_STARTER); if (starter != null) @@ -653,72 +648,72 @@ public class AnnotationConfiguration extends AbstractConfiguration context.addBean(starter, true); } - public Resource getJarFor (ServletContainerInitializer service) - throws MalformedURLException, IOException + public Resource getJarFor(ServletContainerInitializer service) + throws MalformedURLException, IOException { URI uri = TypeUtil.getLocationOfClass(service.getClass()); if (uri == null) return null; return Resource.newResource(uri); } - + /** * Check to see if the ServletContainerIntializer loaded via the ServiceLoader came * from a jar that is excluded by the fragment ordering. See ServletSpec 3.0 p.85. - * + * * @param context the context for the jars * @param sci the servlet container initializer - * @param sciResource the resource for the servlet container initializer + * @param sciResource the resource for the servlet container initializer * @return true if excluded * @throws Exception if unable to determine exclusion */ - public boolean isFromExcludedJar (WebAppContext context, ServletContainerInitializer sci, Resource sciResource) - throws Exception + public boolean isFromExcludedJar(WebAppContext context, ServletContainerInitializer sci, Resource sciResource) + throws Exception { if (sci == null) throw new IllegalArgumentException("ServletContainerInitializer null"); if (context == null) throw new IllegalArgumentException("WebAppContext null"); - + //if we don't know where its from it can't be excluded if (sciResource == null) { - if (LOG.isDebugEnabled()) + if (LOG.isDebugEnabled()) LOG.debug("!Excluded {} null resource", sci); - return false; + return false; } - + //A ServletContainerInitialier that came from WEB-INF/classes or equivalent cannot be excluded by an ordering if (isFromWebInfClasses(context, sciResource)) { - if (LOG.isDebugEnabled()) + if (LOG.isDebugEnabled()) LOG.debug("!Excluded {} from web-inf/classes", sci); return false; } - + //A ServletContainerInitializer that came from the container's classpath cannot be excluded by an ordering //of WEB-INF/lib jars if (isFromContainerClassPath(context, sci)) { - if (LOG.isDebugEnabled()) + if (LOG.isDebugEnabled()) LOG.debug("!Excluded {} from container classpath", sci); return false; } - + //If no ordering, nothing is excluded if (context.getMetaData().getOrdering() == null) { - if (LOG.isDebugEnabled()) + if (LOG.isDebugEnabled()) LOG.debug("!Excluded {} no ordering", sci); return false; } - + List orderedJars = context.getMetaData().getOrderedWebInfJars(); //there is an ordering, but there are no jars resulting from the ordering, everything excluded if (orderedJars.isEmpty()) { - if (LOG.isDebugEnabled()) + if (LOG.isDebugEnabled()) LOG.debug("Excluded {} empty ordering", sci); return true; } @@ -733,15 +728,15 @@ public class AnnotationConfiguration extends AbstractConfiguration found = r.getURI().equals(loadingJarURI); } - if (LOG.isDebugEnabled()) - LOG.debug("{}Excluded {} found={}",found?"!":"",sci,found); + if (LOG.isDebugEnabled()) + LOG.debug("{}Excluded {} found={}", found ? "!" : "", sci, found); return !found; } /** - * Test if the ServletContainerIntializer is excluded by the + * Test if the ServletContainerIntializer is excluded by the * o.e.j.containerInitializerExclusionPattern - * + * * @param sci the ServletContainerIntializer * @return true if the ServletContainerIntializer is excluded */ @@ -750,36 +745,35 @@ public class AnnotationConfiguration extends AbstractConfiguration //no exclusion pattern, no SCI is excluded by it if (_sciExcludePattern == null) return false; - + //test if name of class matches the regex - if (LOG.isDebugEnabled()) - LOG.debug("Checking {} against containerInitializerExclusionPattern",sci.getClass().getName()); + if (LOG.isDebugEnabled()) + LOG.debug("Checking {} against containerInitializerExclusionPattern", sci.getClass().getName()); return _sciExcludePattern.matcher(sci.getClass().getName()).matches(); } - - + /** * Test if the ServletContainerInitializer is from the container classpath - * + * * @param context the context for the webapp classpath * @param sci the ServletContainerIntializer * @return true if ServletContainerIntializer is from container classpath */ - public boolean isFromContainerClassPath (WebAppContext context, ServletContainerInitializer sci) + public boolean isFromContainerClassPath(WebAppContext context, ServletContainerInitializer sci) { if (sci == null) return false; - + ClassLoader sciLoader = sci.getClass().getClassLoader(); - + //if loaded by bootstrap loader, then its the container classpath - if ( sciLoader == null) + if (sciLoader == null) return true; - + //if there is no context classloader, then its the container classpath if (context.getClassLoader() == null) return true; - + ClassLoader loader = sciLoader; while (loader != null) { @@ -788,23 +782,23 @@ public class AnnotationConfiguration extends AbstractConfiguration else loader = loader.getParent(); } - + return true; } - - /** + + /** * Test if the ServletContainerInitializer is from WEB-INF/classes - * + * * @param context the webapp to test * @param sci a Resource representing the SCI * @return true if the sci Resource is inside a WEB-INF/classes directory, false otherwise */ - public boolean isFromWebInfClasses (WebAppContext context, Resource sci) + public boolean isFromWebInfClasses(WebAppContext context, Resource sci) { for (Resource dir : context.getMetaData().getWebInfClassesDirs()) - { + { if (dir.equals(sci)) - { + { return true; } } @@ -813,45 +807,46 @@ public class AnnotationConfiguration extends AbstractConfiguration /** * Get SCIs that are not excluded from consideration - * @param context the web app context + * + * @param context the web app context * @return the list of non-excluded servlet container initializers - * @throws Exception if unable to get list + * @throws Exception if unable to get list */ - public List getNonExcludedInitializers (WebAppContext context) - throws Exception + public List getNonExcludedInitializers(WebAppContext context) + throws Exception { ArrayList nonExcludedInitializers = new ArrayList(); - + //We use the ServiceLoader mechanism to find the ServletContainerInitializer classes to inspect long start = 0; if (LOG.isDebugEnabled()) start = System.nanoTime(); ServiceLoader loader = ServiceLoader.load(ServletContainerInitializer.class); if (LOG.isDebugEnabled()) - LOG.debug("Service loaders found in {}ms", (TimeUnit.MILLISECONDS.convert((System.nanoTime()-start), TimeUnit.NANOSECONDS))); - - Map sciResourceMap = new HashMap(); + LOG.debug("Service loaders found in {}ms", (TimeUnit.MILLISECONDS.convert((System.nanoTime() - start), TimeUnit.NANOSECONDS))); + + Map sciResourceMap = new HashMap(); ServletContainerInitializerOrdering initializerOrdering = getInitializerOrdering(context); //Get initial set of SCIs that aren't from excluded jars or excluded by the containerExclusionPattern, or excluded //because containerInitializerOrdering omits it Iterator iter = loader.iterator(); - while(iter.hasNext()) - { + while (iter.hasNext()) + { ServletContainerInitializer sci; try { - sci=iter.next(); + sci = iter.next(); } - catch(Error e) + catch (Error e) { // Probably a SCI discovered on the system classpath that is hidden by the context classloader - LOG.info("Error: "+e.getMessage()+" for "+context); + LOG.info("Error: " + e.getMessage() + " for " + context); LOG.debug(e); continue; } - - if (matchesExclusionPattern(sci)) + + if (matchesExclusionPattern(sci)) { if (LOG.isDebugEnabled()) LOG.debug("{} excluded by pattern", sci); @@ -859,23 +854,22 @@ public class AnnotationConfiguration extends AbstractConfiguration } Resource sciResource = getJarFor(sci); - if (isFromExcludedJar(context, sci, sciResource)) - { + if (isFromExcludedJar(context, sci, sciResource)) + { if (LOG.isDebugEnabled()) LOG.debug("{} is from excluded jar", sci); continue; } - + //check containerInitializerOrdering doesn't exclude it String name = sci.getClass().getName(); - if (initializerOrdering != null - && (!initializerOrdering.hasWildcard() && initializerOrdering.getIndexOf(name) < 0)) + if (initializerOrdering != null && (!initializerOrdering.hasWildcard() && initializerOrdering.getIndexOf(name) < 0)) { if (LOG.isDebugEnabled()) LOG.debug("{} is excluded by ordering", sci); continue; } - + sciResourceMap.put(sci, sciResource); } @@ -883,7 +877,7 @@ public class AnnotationConfiguration extends AbstractConfiguration if (initializerOrdering != null && !initializerOrdering.isDefaultOrder()) { if (LOG.isDebugEnabled()) - LOG.debug("Ordering ServletContainerInitializers with "+initializerOrdering); + LOG.debug("Ordering ServletContainerInitializers with " + initializerOrdering); //There is an ordering that is not just "*". //Arrange ServletContainerInitializers according to the ordering of classnames given, irrespective of coming from container or webapp classpaths @@ -895,12 +889,12 @@ public class AnnotationConfiguration extends AbstractConfiguration //No jetty-specific ordering specified, or just the wildcard value "*" specified. //Fallback to ordering the ServletContainerInitializers according to: //container classpath first, WEB-INF/classes then WEB-INF/lib (obeying any web.xml jar ordering) - + //First add in all SCIs that can't be excluded int lastContainerSCI = -1; - for (Map.Entry entry:sciResourceMap.entrySet()) + for (Map.Entry entry : sciResourceMap.entrySet()) { - if (entry.getKey().getClass().getClassLoader()==context.getClassLoader().getParent()) + if (entry.getKey().getClass().getClassLoader() == context.getClassLoader().getParent()) { nonExcludedInitializers.add(++lastContainerSCI, entry.getKey()); //add all container SCIs before any webapp SCIs } @@ -911,19 +905,21 @@ public class AnnotationConfiguration extends AbstractConfiguration else { for (Resource dir : context.getMetaData().getWebInfClassesDirs()) - { + { if (dir.equals(entry.getValue()))//from WEB-INF/classes so can't be ordered/excluded - { + { nonExcludedInitializers.add(entry.getKey()); } } } } - + //throw out the ones we've already accounted for - for (ServletContainerInitializer s:nonExcludedInitializers) + for (ServletContainerInitializer s : nonExcludedInitializers) + { sciResourceMap.remove(s); - + } + if (context.getMetaData().getOrdering() == null) { if (LOG.isDebugEnabled()) @@ -934,20 +930,20 @@ public class AnnotationConfiguration extends AbstractConfiguration else { if (LOG.isDebugEnabled()) - LOG.debug("Ordering ServletContainerInitializers with ordering {}",context.getMetaData().getOrdering()); - + LOG.debug("Ordering ServletContainerInitializers with ordering {}", context.getMetaData().getOrdering()); + //add SCIs according to the ordering of its containing jar - for (Resource webInfJar:context.getMetaData().getOrderedWebInfJars()) + for (Resource webInfJar : context.getMetaData().getOrderedWebInfJars()) { - for (Map.Entry entry:sciResourceMap.entrySet()) + for (Map.Entry entry : sciResourceMap.entrySet()) { - if (webInfJar.equals(entry.getValue())) + if (webInfJar.equals(entry.getValue())) nonExcludedInitializers.add(entry.getKey()); } } } } - + //final pass over the non-excluded SCIs if the webapp version is < 3, in which case //we will only call SCIs that are on the server's classpath if (context.getServletContext().getEffectiveMajorVersion() < 3 && !context.isConfigurationDiscovered()) @@ -955,56 +951,56 @@ public class AnnotationConfiguration extends AbstractConfiguration ListIterator it = nonExcludedInitializers.listIterator(); while (it.hasNext()) { - ServletContainerInitializer sci = it.next(); + ServletContainerInitializer sci = it.next(); if (!isFromContainerClassPath(context, sci)) { if (LOG.isDebugEnabled()) LOG.debug("Ignoring SCI {}: old web.xml version {}.{}", sci.getClass().getName(), - context.getServletContext().getEffectiveMajorVersion(), - context.getServletContext().getEffectiveMinorVersion()); + context.getServletContext().getEffectiveMajorVersion(), + context.getServletContext().getEffectiveMinorVersion()); it.remove(); } } } - if (LOG.isDebugEnabled()) + if (LOG.isDebugEnabled()) { - int i=0; - for (ServletContainerInitializer sci:nonExcludedInitializers) - LOG.debug("ServletContainerInitializer: {} {} from {}",(++i), sci.getClass().getName(), sciResourceMap.get(sci)); - } - + int i = 0; + for (ServletContainerInitializer sci : nonExcludedInitializers) + { + LOG.debug("ServletContainerInitializer: {} {} from {}", (++i), sci.getClass().getName(), sciResourceMap.get(sci)); + } + } + return nonExcludedInitializers; } - /** * Jetty-specific extension that allows an ordering to be applied across ALL ServletContainerInitializers. - * - * @param context the context for the initializer ordering configuration + * + * @param context the context for the initializer ordering configuration * @return the ordering of the ServletContainerIntializer's */ - public ServletContainerInitializerOrdering getInitializerOrdering (WebAppContext context) + public ServletContainerInitializerOrdering getInitializerOrdering(WebAppContext context) { if (context == null) return null; - + String tmp = (String)context.getAttribute(SERVLET_CONTAINER_INITIALIZER_ORDER); if (tmp == null || "".equals(tmp.trim())) return null; - + return new ServletContainerInitializerOrdering(tmp); } - /** * Scan jars on container path. - * + * * @param context the context for the scan * @param parser the parser to scan with * @throws Exception if unable to scan */ - public void parseContainerPath (final WebAppContext context, final AnnotationParser parser) throws Exception + public void parseContainerPath(final WebAppContext context, final AnnotationParser parser) throws Exception { //always parse for discoverable annotations as well as class hierarchy and servletcontainerinitializer related annotations final Set handlers = new HashSet(); @@ -1022,26 +1018,25 @@ public class AnnotationConfiguration extends AbstractConfiguration if (_parserTasks != null) { ParserTask task = new ParserTask(parser, handlers, r); - _parserTasks.add(task); + _parserTasks.add(task); if (LOG.isDebugEnabled()) { _containerPathStats.increment(); task.setStatistic(new TimeStatistic()); } } - } + } } - /** * Scan jars in WEB-INF/lib - * + * * @param context the context for the scan * @param parser the annotation parser to use * @throws Exception if unable to scan and/or parse */ - public void parseWebInfLib (final WebAppContext context, final AnnotationParser parser) throws Exception - { + public void parseWebInfLib(final WebAppContext context, final AnnotationParser parser) throws Exception + { List frags = context.getMetaData().getFragments(); //email from Rajiv Mordani jsrs 315 7 April 2010 @@ -1074,7 +1069,7 @@ public class AnnotationConfiguration extends AbstractConfiguration // but yet we still need to do the scanning for the classes on behalf of the servletcontainerinitializers //if a jar has no web-fragment.xml we scan it (because it is not excluded by the ordering) //or if it has a fragment we scan it if it is not metadata complete - if (f == null || !isMetaDataComplete(f) || _classInheritanceHandler != null || !_containerInitializerAnnotationHandlers.isEmpty()) + if (f == null || !isMetaDataComplete(f) || _classInheritanceHandler != null || !_containerInitializerAnnotationHandlers.isEmpty()) { //register the classinheritance handler if there is one if (_classInheritanceHandler != null) @@ -1089,8 +1084,8 @@ public class AnnotationConfiguration extends AbstractConfiguration if (_parserTasks != null) { - ParserTask task = new ParserTask(parser, handlers,r); - _parserTasks.add (task); + ParserTask task = new ParserTask(parser, handlers, r); + _parserTasks.add(task); if (LOG.isDebugEnabled()) { _webInfLibStats.increment(); @@ -1101,16 +1096,15 @@ public class AnnotationConfiguration extends AbstractConfiguration } } - /** * Scan classes in WEB-INF/classes - * + * * @param context the context for the scan * @param parser the annotation parser to use * @throws Exception if unable to scan and/or parse */ - public void parseWebInfClasses (final WebAppContext context, final AnnotationParser parser) - throws Exception + public void parseWebInfClasses(final WebAppContext context, final AnnotationParser parser) + throws Exception { Set handlers = new HashSet(); handlers.addAll(_discoverableAnnotationHandlers); @@ -1136,25 +1130,23 @@ public class AnnotationConfiguration extends AbstractConfiguration } } - - /** * Get the web-fragment.xml from a jar - * + * * @param jar the jar to look in for a fragment * @param frags the fragments previously found * @return true if the fragment if found, or null of not found * @throws Exception if unable to determine the the fragment contains */ - public FragmentDescriptor getFragmentFromJar (Resource jar, List frags) - throws Exception + public FragmentDescriptor getFragmentFromJar(Resource jar, List frags) + throws Exception { //check if the jar has a web-fragment.xml FragmentDescriptor d = null; - for (FragmentDescriptor frag: frags) + for (FragmentDescriptor frag : frags) { Resource fragResource = frag.getResource(); //eg jar:file:///a/b/c/foo.jar!/META-INF/web-fragment.xml - if (Resource.isContainedIn(fragResource,jar)) + if (Resource.isContainedIn(fragResource, jar)) { d = frag; break; @@ -1163,18 +1155,18 @@ public class AnnotationConfiguration extends AbstractConfiguration return d; } - public boolean isMetaDataComplete (WebDescriptor d) + public boolean isMetaDataComplete(WebDescriptor d) { - return (d!=null && d.getMetaDataComplete() == MetaDataComplete.True); + return (d != null && d.getMetaDataComplete() == MetaDataComplete.True); } public static class ClassInheritanceMap extends ConcurrentHashMap> { - + @Override public String toString() { - return String.format("ClassInheritanceMap@%x{size=%d}",hashCode(),size()); + return String.format("ClassInheritanceMap@%x{size=%d}", hashCode(), size()); } } } diff --git a/jetty-annotations/src/main/java/org/eclipse/jetty/annotations/AnnotationDecorator.java b/jetty-annotations/src/main/java/org/eclipse/jetty/annotations/AnnotationDecorator.java index bd516a4bde5..ed9a16e8bce 100644 --- a/jetty-annotations/src/main/java/org/eclipse/jetty/annotations/AnnotationDecorator.java +++ b/jetty-annotations/src/main/java/org/eclipse/jetty/annotations/AnnotationDecorator.java @@ -30,10 +30,10 @@ public class AnnotationDecorator implements Decorator public AnnotationDecorator(WebAppContext context) { - registerHandlers(context); + registerHandlers(context); } - - public void registerHandlers (WebAppContext context) + + public void registerHandlers(WebAppContext context) { _introspector.registerHandler(new ResourceAnnotationHandler(context)); _introspector.registerHandler(new ResourcesAnnotationHandler(context)); @@ -54,9 +54,10 @@ public class AnnotationDecorator implements Decorator *
  • PreDestroy
  • *
  • ServletSecurity?
  • * + * * @param o the object ot introspect */ - protected void introspect (Object o) + protected void introspect(Object o) { _introspector.introspect(o.getClass()); } @@ -64,13 +65,13 @@ public class AnnotationDecorator implements Decorator @Override public Object decorate(Object o) { - introspect(o); - return o; + introspect(o); + return o; } @Override public void destroy(Object o) { - + } } diff --git a/jetty-annotations/src/main/java/org/eclipse/jetty/annotations/AnnotationIntrospector.java b/jetty-annotations/src/main/java/org/eclipse/jetty/annotations/AnnotationIntrospector.java index e5b8714d5e8..5a47cb97d3e 100644 --- a/jetty-annotations/src/main/java/org/eclipse/jetty/annotations/AnnotationIntrospector.java +++ b/jetty-annotations/src/main/java/org/eclipse/jetty/annotations/AnnotationIntrospector.java @@ -23,14 +23,11 @@ import java.util.List; /** * AnnotationIntrospector - * - * */ public class AnnotationIntrospector -{ +{ protected List _handlers = new ArrayList(); - - + /** * IntrospectableAnnotationHandler * @@ -40,57 +37,54 @@ public class AnnotationIntrospector { public void handle(Class clazz); } - - - + /** * AbstractIntrospectableAnnotationHandler * * Base class for handlers that introspect a class to find a particular annotation. * A handler can optionally introspect the parent hierarchy of a class. */ - public static abstract class AbstractIntrospectableAnnotationHandler implements IntrospectableAnnotationHandler + public abstract static class AbstractIntrospectableAnnotationHandler implements IntrospectableAnnotationHandler { private boolean _introspectAncestors; - + public abstract void doHandle(Class clazz); - - + public AbstractIntrospectableAnnotationHandler(boolean introspectAncestors) { _introspectAncestors = introspectAncestors; } - + @Override public void handle(Class clazz) { Class c = clazz; - + //process the whole inheritance hierarchy for the class - while (c!=null && (!c.equals(Object.class))) + while (c != null && (!c.equals(Object.class))) { doHandle(c); if (!_introspectAncestors) break; - + c = c.getSuperclass(); - } + } } } - - public void registerHandler (IntrospectableAnnotationHandler handler) + + public void registerHandler(IntrospectableAnnotationHandler handler) { _handlers.add(handler); } - - public void introspect (Class clazz) + + public void introspect(Class clazz) { if (_handlers == null) return; if (clazz == null) return; - - for (IntrospectableAnnotationHandler handler:_handlers) + + for (IntrospectableAnnotationHandler handler : _handlers) { try { @@ -105,6 +99,5 @@ public class AnnotationIntrospector throw new RuntimeException(e); } } - } } diff --git a/jetty-annotations/src/main/java/org/eclipse/jetty/annotations/AnnotationParser.java b/jetty-annotations/src/main/java/org/eclipse/jetty/annotations/AnnotationParser.java index 41cdffcff70..a81135dd908 100644 --- a/jetty-annotations/src/main/java/org/eclipse/jetty/annotations/AnnotationParser.java +++ b/jetty-annotations/src/main/java/org/eclipse/jetty/annotations/AnnotationParser.java @@ -54,8 +54,8 @@ import org.objectweb.asm.Opcodes; *

    * Use asm to scan classes for annotations. A SAX-style parsing is done. * Handlers are registered which will be called back when various types of - * entity are encountered, eg a class, a method, a field. - *

    + * entity are encountered, eg a class, a method, a field. + *

    * Handlers are not called back in any particular order and are assumed * to be order-independent. *

    @@ -72,19 +72,20 @@ public class AnnotationParser private static final Logger LOG = Log.getLogger(AnnotationParser.class); protected static int ASM_OPCODE_VERSION = Opcodes.ASM7; //compatibility of api protected static String ASM_OPCODE_VERSION_STR = "ASM7"; - + /** * Map of classnames scanned and the first location from which scan occurred */ protected Map _parsedClassNames = new ConcurrentHashMap<>(); private final int _javaPlatform; private int _asmVersion; - + /** * Determine the runtime version of asm. + * * @return the org.objectweb.asm.Opcode matching the runtime version of asm. */ - public static int asmVersion () + public static int asmVersion() { int asmVersion = ASM_OPCODE_VERSION; String version = ManifestUtils.getVersion(Opcodes.class).orElse(null); @@ -137,54 +138,56 @@ public class AnnotationParser /** * Convert internal name to simple name - * + * * @param name the internal name * @return the simple name */ - public static String normalize (String name) + public static String normalize(String name) { - if (name==null) + if (name == null) return null; if (name.startsWith("L") && name.endsWith(";")) - name = name.substring(1, name.length()-1); + name = name.substring(1, name.length() - 1); if (name.endsWith(".class")) - name = name.substring(0, name.length()-".class".length()); + name = name.substring(0, name.length() - ".class".length()); - return StringUtil.replace(name,'/', '.'); + return StringUtil.replace(name, '/', '.'); } - + /** * Convert internal names to simple names. - * + * * @param list the list of internal names * @return the list of simple names */ - public static String[] normalize (String[] list) + public static String[] normalize(String[] list) { if (list == null) - return null; + return null; String[] normalList = new String[list.length]; - int i=0; + int i = 0; for (String s : list) + { normalList[i++] = normalize(s); + } return normalList; } /** * Immutable information gathered by parsing class header. */ - public class ClassInfo + public class ClassInfo { final Resource _containingResource; final String _className; final int _version; final int _access; final String _signature; - final String _superName; + final String _superName; final String[] _interfaces; - + public ClassInfo(Resource resource, String className, int version, int access, String signature, String superName, String[] interfaces) { super(); @@ -239,12 +242,12 @@ public class AnnotationParser public class MethodInfo { final ClassInfo _classInfo; - final String _methodName; + final String _methodName; final int _access; - final String _desc; + final String _desc; final String _signature; final String[] _exceptions; - + public MethodInfo(ClassInfo classInfo, String methodName, int access, String desc, String signature, String[] exceptions) { super(); @@ -298,7 +301,7 @@ public class AnnotationParser final String _fieldType; final String _signature; final Object _value; - + public FieldInfo(ClassInfo classInfo, String fieldName, int access, String fieldType, String signature, Object value) { super(); @@ -340,24 +343,29 @@ public class AnnotationParser return _value; } } - + /** * Signature for all handlers that respond to parsing class files. */ public static interface Handler { public void handle(ClassInfo classInfo); + public void handle(MethodInfo methodInfo); - public void handle (FieldInfo fieldInfo); - public void handle (ClassInfo info, String annotationName); - public void handle (MethodInfo info, String annotationName); - public void handle (FieldInfo info, String annotationName); + + public void handle(FieldInfo fieldInfo); + + public void handle(ClassInfo info, String annotationName); + + public void handle(MethodInfo info, String annotationName); + + public void handle(FieldInfo info, String annotationName); } - + /** * Convenience base class to provide no-ops for all Handler methods. */ - public static abstract class AbstractHandler implements Handler + public abstract static class AbstractHandler implements Handler { @Override public void handle(ClassInfo classInfo) @@ -397,7 +405,7 @@ public class AnnotationParser { final MethodInfo _mi; final Set _handlers; - + public MyMethodVisitor(final Set handlers, final ClassInfo classInfo, final int access, @@ -409,7 +417,7 @@ public class AnnotationParser { super(asmVersion); _handlers = handlers; - _mi = new MethodInfo(classInfo, name, access, methodDesc,signature, exceptions); + _mi = new MethodInfo(classInfo, name, access, methodDesc, signature, exceptions); } /** @@ -419,8 +427,10 @@ public class AnnotationParser public AnnotationVisitor visitAnnotation(String desc, boolean visible) { String annotationName = normalize(desc); - for (Handler h:_handlers) + for (Handler h : _handlers) + { h.handle(_mi, annotationName); + } return null; } } @@ -430,7 +440,7 @@ public class AnnotationParser * We are only interested in visiting annotations on Fields. */ public class MyFieldVisitor extends FieldVisitor - { + { final FieldInfo _fieldInfo; final Set _handlers; @@ -456,7 +466,9 @@ public class AnnotationParser { String annotationName = normalize(desc); for (Handler h : _handlers) - h.handle(_fieldInfo, annotationName); + { + h.handle(_fieldInfo, annotationName); + } return null; } @@ -471,7 +483,7 @@ public class AnnotationParser final Resource _containingResource; final Set _handlers; ClassInfo _ci; - + public MyClassVisitor(Set handlers, Resource containingResource, int asmVersion) { super(asmVersion); @@ -481,27 +493,31 @@ public class AnnotationParser } @Override - public void visit (final int version, - final int access, - final String name, - final String signature, - final String superName, - final String[] interfaces) - { + public void visit(final int version, + final int access, + final String name, + final String signature, + final String superName, + final String[] interfaces) + { _ci = new ClassInfo(_containingResource, normalize(name), version, access, signature, normalize(superName), normalize(interfaces)); - for (Handler h:_handlers) - h.handle(_ci); + for (Handler h : _handlers) + { + h.handle(_ci); + } } /** * Visit an annotation on a Class */ @Override - public AnnotationVisitor visitAnnotation (String desc, boolean visible) + public AnnotationVisitor visitAnnotation(String desc, boolean visible) { String annotationName = normalize(desc); for (Handler h : _handlers) + { h.handle(_ci, annotationName); + } return null; } @@ -509,11 +525,11 @@ public class AnnotationParser * Visit a method to extract its annotations */ @Override - public MethodVisitor visitMethod (final int access, - final String name, - final String methodDesc, - final String signature, - final String[] exceptions) + public MethodVisitor visitMethod(final int access, + final String name, + final String methodDesc, + final String signature, + final String[] exceptions) { return new MyMethodVisitor(_handlers, _ci, access, name, methodDesc, signature, exceptions, _asmVersion); } @@ -522,11 +538,11 @@ public class AnnotationParser * Visit a field to extract its annotations */ @Override - public FieldVisitor visitField (final int access, - final String fieldName, - final String fieldType, - final String signature, - final Object value) + public FieldVisitor visitField(final int access, + final String fieldName, + final String fieldType, + final String signature, + final Object value) { return new MyFieldVisitor(_handlers, _ci, access, fieldName, fieldType, signature, value, _asmVersion); } @@ -543,50 +559,49 @@ public class AnnotationParser public AnnotationParser(int javaPlatform) { _asmVersion = asmVersion(); - if (javaPlatform==0) + if (javaPlatform == 0) javaPlatform = JavaVersion.VERSION.getPlatform(); _javaPlatform = javaPlatform; } - - + public AnnotationParser(int javaPlatform, int asmVersion) { - if (javaPlatform==0) + if (javaPlatform == 0) javaPlatform = JavaVersion.VERSION.getPlatform(); _javaPlatform = javaPlatform; - if (asmVersion==0) + if (asmVersion == 0) asmVersion = ASM_OPCODE_VERSION; _asmVersion = asmVersion; } - + /** * Add a class as having been parsed. - * + * * @param classname the name of the class * @param location the fully qualified location of the class */ - public void addParsedClass (String classname, Resource location) + public void addParsedClass(String classname, Resource location) { - Resource existing = _parsedClassNames.putIfAbsent(classname, location); + Resource existing = _parsedClassNames.putIfAbsent(classname, location); if (existing != null) LOG.warn("{} scanned from multiple locations: {}, {}", classname, existing, location); } /** * Parse a given class - * + * * @param handlers the set of handlers to find class * @param className the class name to parse * @throws Exception if unable to parse */ - public void parse (Set handlers, String className) throws Exception + public void parse(Set handlers, String className) throws Exception { if (className == null) return; String classRef = TypeUtil.toClassReference(className); URL resource = Loader.getResource(classRef); - if (resource!= null) + if (resource != null) { Resource r = Resource.newResource(resource); addParsedClass(className, r); @@ -599,24 +614,24 @@ public class AnnotationParser /** * Parse the given class, optionally walking its inheritance hierarchy - * - * @param handlers the handlers to look for class in + * + * @param handlers the handlers to look for class in * @param clazz the class to look for - * @param visitSuperClasses if true, also visit super classes for parse + * @param visitSuperClasses if true, also visit super classes for parse * @throws Exception if unable to parse class */ - public void parse (Set handlers, Class clazz, boolean visitSuperClasses) throws Exception + public void parse(Set handlers, Class clazz, boolean visitSuperClasses) throws Exception { Class cz = clazz; while (cz != Object.class) { String nameAsResource = TypeUtil.toClassReference(cz); URL resource = Loader.getResource(nameAsResource); - if (resource!= null) + if (resource != null) { Resource r = Resource.newResource(resource); addParsedClass(clazz.getName(), r); - try (InputStream is = r.getInputStream()) + try (InputStream is = r.getInputStream()) { scanClass(handlers, null, is); } @@ -631,12 +646,12 @@ public class AnnotationParser /** * Parse the given classes - * - * @param handlers the set of handlers to look for class in + * + * @param handlers the set of handlers to look for class in * @param classNames the class name * @throws Exception if unable to parse */ - public void parse (Set handlers, String[] classNames) throws Exception + public void parse(Set handlers, String[] classNames) throws Exception { if (classNames == null) return; @@ -646,12 +661,12 @@ public class AnnotationParser /** * Parse the given classes - * - * @param handlers the set of handlers to look for class in + * + * @param handlers the set of handlers to look for class in * @param classNames the class names * @throws Exception if unable to parse */ - public void parse (Set handlers, List classNames) throws Exception + public void parse(Set handlers, List classNames) throws Exception { MultiException me = new MultiException(); @@ -661,7 +676,7 @@ public class AnnotationParser { String classRef = TypeUtil.toClassReference(className); URL resource = Loader.getResource(classRef); - if (resource!= null) + if (resource != null) { Resource r = Resource.newResource(resource); addParsedClass(className, r); @@ -673,7 +688,7 @@ public class AnnotationParser } catch (Exception e) { - me.add(new RuntimeException("Error scanning class "+className, e)); + me.add(new RuntimeException("Error scanning class " + className, e)); } } me.ifExceptionThrow(); @@ -681,32 +696,32 @@ public class AnnotationParser /** * Parse all classes in a directory - * - * @param handlers the set of handlers to look for classes in + * + * @param handlers the set of handlers to look for classes in * @param root the resource directory to look for classes * @throws Exception if unable to parse */ - protected void parseDir (Set handlers, Resource root) throws Exception + protected void parseDir(Set handlers, Resource root) throws Exception { if (!root.isDirectory() || !root.exists() || root.getName().startsWith(".")) return; if (LOG.isDebugEnabled()) LOG.debug("Scanning dir {}", root); - + File rootFile = root.getFile(); - + MultiException me = new MultiException(); Collection resources = root.getAllResources(); if (resources != null) { - for (Resource r:resources) + for (Resource r : resources) { if (r.isDirectory()) continue; - File file = r.getFile(); - if (isValidClassFileName((file==null?null:file.getName()))) + File file = r.getFile(); + if (isValidClassFileName((file == null ? null : file.getName()))) { Path classpath = rootFile.toPath().relativize(file.toPath()); String str = classpath.toString(); @@ -718,42 +733,44 @@ public class AnnotationParser if (LOG.isDebugEnabled()) LOG.debug("Scanning class {}", r); addParsedClass(str, r); - try (InputStream is=r.getInputStream()) + try (InputStream is = r.getInputStream()) { scanClass(handlers, Resource.newResource(file.getParentFile()), is); } - } + } catch (Exception ex) { - if (LOG.isDebugEnabled()) LOG.debug("Error scanning file "+file, ex); - me.add(new RuntimeException("Error scanning file "+file,ex)); + if (LOG.isDebugEnabled()) + LOG.debug("Error scanning file " + file, ex); + me.add(new RuntimeException("Error scanning file " + file, ex)); } } else { - if (LOG.isDebugEnabled()) LOG.debug("Skipping scan on invalid file {}", file); + if (LOG.isDebugEnabled()) + LOG.debug("Skipping scan on invalid file {}", file); } } } - + me.ifExceptionThrow(); } /** * Parse classes in the supplied uris. - * - * @param handlers the handlers to look for classes in + * + * @param handlers the handlers to look for classes in * @param uris the uris for the jars * @throws Exception if unable to parse */ - public void parse (final Set handlers, final URI[] uris) throws Exception + public void parse(final Set handlers, final URI[] uris) throws Exception { - if (uris==null) + if (uris == null) return; MultiException me = new MultiException(); - - for (URI uri:uris) + + for (URI uri : uris) { try { @@ -761,7 +778,7 @@ public class AnnotationParser } catch (Exception e) { - me.add(new RuntimeException("Problem parsing classes from "+ uri, e)); + me.add(new RuntimeException("Problem parsing classes from " + uri, e)); } } me.ifExceptionThrow(); @@ -769,31 +786,31 @@ public class AnnotationParser /** * Parse a particular uri - * - * @param handlers the handlers to look for classes in - * @param uri the uri for the jar + * + * @param handlers the handlers to look for classes in + * @param uri the uri for the jar * @throws Exception if unable to parse */ - public void parse (final Set handlers, URI uri) throws Exception + public void parse(final Set handlers, URI uri) throws Exception { if (uri == null) return; - parse (handlers, Resource.newResource(uri)); + parse(handlers, Resource.newResource(uri)); } /** * Parse a resource - * - * @param handlers the handlers to look for classes in + * + * @param handlers the handlers to look for classes in * @param r the resource to parse * @throws Exception if unable to parse */ - public void parse (final Set handlers, Resource r) throws Exception + public void parse(final Set handlers, Resource r) throws Exception { if (r == null) return; - + if (r.exists() && r.isDirectory()) { parseDir(handlers, r); @@ -809,37 +826,38 @@ public class AnnotationParser if (fullname.endsWith(".class")) { - try (InputStream is=r.getInputStream()) + try (InputStream is = r.getInputStream()) { scanClass(handlers, null, is); return; } } - - if (LOG.isDebugEnabled()) LOG.warn("Resource not scannable for classes: {}", r); + + if (LOG.isDebugEnabled()) + LOG.warn("Resource not scannable for classes: {}", r); } /** * Parse a resource that is a jar file. - * - * @param handlers the handlers to look for classes in + * + * @param handlers the handlers to look for classes in * @param jarResource the jar resource to parse * @throws Exception if unable to parse */ - protected void parseJar (Set handlers, Resource jarResource) throws Exception + protected void parseJar(Set handlers, Resource jarResource) throws Exception { if (jarResource == null) return; - + if (jarResource.toString().endsWith(".jar")) { if (LOG.isDebugEnabled()) LOG.debug("Scanning jar {}", jarResource); MultiException me = new MultiException(); - try (MultiReleaseJarFile jarFile = new MultiReleaseJarFile(jarResource.getFile(),_javaPlatform,false)) + try (MultiReleaseJarFile jarFile = new MultiReleaseJarFile(jarResource.getFile(), _javaPlatform, false)) { - jarFile.stream().forEach(e-> + jarFile.stream().forEach(e -> { try { @@ -852,19 +870,19 @@ public class AnnotationParser }); } me.ifExceptionThrow(); - } + } } /** * Parse a single entry in a jar file - * - * @param handlers the handlers to look for classes in + * + * @param handlers the handlers to look for classes in * @param entry the entry in the potentially MultiRelease jar resource to parse * @param jar the jar file * @throws Exception if unable to parse */ - protected void parseJarEntry (Set handlers, Resource jar, MultiReleaseJarFile.VersionedJarEntry entry) - throws Exception + protected void parseJarEntry(Set handlers, Resource jar, MultiReleaseJarFile.VersionedJarEntry entry) + throws Exception { if (jar == null || entry == null) return; @@ -879,7 +897,7 @@ public class AnnotationParser if (isValidClassFileName(name) && isValidClassFilePath(name)) { String shortName = StringUtil.replace(name, '/', '.').substring(0, name.length() - 6); - addParsedClass(shortName, Resource.newResource("jar:"+jar.getURI()+"!/"+entry.getNameInJar())); + addParsedClass(shortName, Resource.newResource("jar:" + jar.getURI() + "!/" + entry.getNameInJar())); if (LOG.isDebugEnabled()) LOG.debug("Scanning class from jar {}!/{}", jar, entry); try (InputStream is = entry.getInputStream()) @@ -891,22 +909,22 @@ public class AnnotationParser /** * Use ASM on a class - * - * @param handlers the handlers to look for classes in + * + * @param handlers the handlers to look for classes in * @param containingResource the dir or jar that the class is contained within, can be null if not known * @param is the input stream to parse * @throws IOException if unable to parse */ - protected void scanClass (Set handlers, Resource containingResource, InputStream is) throws IOException + protected void scanClass(Set handlers, Resource containingResource, InputStream is) throws IOException { ClassReader reader = new ClassReader(is); - reader.accept(new MyClassVisitor(handlers, containingResource, _asmVersion), ClassReader.SKIP_CODE|ClassReader.SKIP_DEBUG|ClassReader.SKIP_FRAMES); + reader.accept(new MyClassVisitor(handlers, containingResource, _asmVersion), ClassReader.SKIP_CODE | ClassReader.SKIP_DEBUG | ClassReader.SKIP_FRAMES); } - + /** * Remove any parsed class names. */ - public void resetParsedClasses () + public void resetParsedClasses() { _parsedClassNames.clear(); } @@ -919,39 +937,43 @@ public class AnnotationParser *

  • it isn't a dot file or in a hidden directory
  • *
  • the name of the class at least begins with a valid identifier for a class name
  • * + * * @param name the class file name * @return whether the class file name is valid */ - private boolean isValidClassFileName (String name) + private boolean isValidClassFileName(String name) { //no name cannot be valid - if (name == null || name.length()==0) + if (name == null || name.length() == 0) return false; //skip anything that is not a class file String lc = name.toLowerCase(Locale.ENGLISH); if (!lc.endsWith(".class")) { - if (LOG.isDebugEnabled()) LOG.debug("Not a class: {}",name); + if (LOG.isDebugEnabled()) + LOG.debug("Not a class: {}", name); return false; } - + if (lc.equals("module-info.class")) { - if (LOG.isDebugEnabled()) LOG.debug("Skipping module-info.class"); + if (LOG.isDebugEnabled()) + LOG.debug("Skipping module-info.class"); return false; } //skip any classfiles that are not a valid java identifier - int c0 = 0; - int ldir = name.lastIndexOf('/', name.length()-6); - c0 = (ldir > -1 ? ldir+1 : c0); + int c0 = 0; + int ldir = name.lastIndexOf('/', name.length() - 6); + c0 = (ldir > -1 ? ldir + 1 : c0); if (!Character.isJavaIdentifierStart(name.charAt(c0))) { - if (LOG.isDebugEnabled()) LOG.debug("Not a java identifier: {}",name); + if (LOG.isDebugEnabled()) + LOG.debug("Not a java identifier: {}", name); return false; } - + return true; } @@ -961,16 +983,17 @@ public class AnnotationParser * @param path the class file path * @return whether the class file path is valid */ - private boolean isValidClassFilePath (String path) + private boolean isValidClassFilePath(String path) { //no path is not valid - if (path == null || path.length()==0) + if (path == null || path.length() == 0) return false; // skip any classfiles that are in a hidden directory if (path.startsWith(".") || path.contains("/.")) { - if (LOG.isDebugEnabled()) LOG.debug("Contains hidden dirs: " + path); + if (LOG.isDebugEnabled()) + LOG.debug("Contains hidden dirs: " + path); return false; } diff --git a/jetty-annotations/src/main/java/org/eclipse/jetty/annotations/ClassInheritanceHandler.java b/jetty-annotations/src/main/java/org/eclipse/jetty/annotations/ClassInheritanceHandler.java index d2093ba258c..a0e9c2bd947 100644 --- a/jetty-annotations/src/main/java/org/eclipse/jetty/annotations/ClassInheritanceHandler.java +++ b/jetty-annotations/src/main/java/org/eclipse/jetty/annotations/ClassInheritanceHandler.java @@ -35,10 +35,9 @@ import org.eclipse.jetty.util.log.Logger; public class ClassInheritanceHandler extends AbstractHandler { private static final Logger LOG = Log.getLogger(ClassInheritanceHandler.class); - + Map> _inheritanceMap; - - + public ClassInheritanceHandler(Map> map) { _inheritanceMap = map; @@ -52,8 +51,8 @@ public class ClassInheritanceHandler extends AbstractHandler //Don't scan Object if ("java.lang.Object".equals(classInfo.getClassName())) return; - - for (int i=0; classInfo.getInterfaces() != null && i < classInfo.getInterfaces().length;i++) + + for (int i = 0; classInfo.getInterfaces() != null && i < classInfo.getInterfaces().length; i++) { addToInheritanceMap(classInfo.getInterfaces()[i], classInfo.getClassName()); } @@ -66,12 +65,12 @@ public class ClassInheritanceHandler extends AbstractHandler catch (Exception e) { LOG.warn(e); - } + } } - - private void addToInheritanceMap (String interfaceOrSuperClassName, String implementingOrExtendingClassName) + + private void addToInheritanceMap(String interfaceOrSuperClassName, String implementingOrExtendingClassName) { - + //As it is likely that the interfaceOrSuperClassName is already in the map, try getting it first Set implementingClasses = _inheritanceMap.get(interfaceOrSuperClassName); //If it isn't in the map, then add it in, but test to make sure that someone else didn't get in @@ -83,7 +82,7 @@ public class ClassInheritanceHandler extends AbstractHandler if (tmp != null) implementingClasses = tmp; } - + implementingClasses.add(implementingOrExtendingClassName); } } diff --git a/jetty-annotations/src/main/java/org/eclipse/jetty/annotations/ContainerInitializerAnnotationHandler.java b/jetty-annotations/src/main/java/org/eclipse/jetty/annotations/ContainerInitializerAnnotationHandler.java index f040f1c2f72..c84910344ad 100644 --- a/jetty-annotations/src/main/java/org/eclipse/jetty/annotations/ContainerInitializerAnnotationHandler.java +++ b/jetty-annotations/src/main/java/org/eclipse/jetty/annotations/ContainerInitializerAnnotationHandler.java @@ -16,10 +16,8 @@ // ======================================================================== // - package org.eclipse.jetty.annotations; - import org.eclipse.jetty.annotations.AnnotationParser.AbstractHandler; import org.eclipse.jetty.annotations.AnnotationParser.ClassInfo; import org.eclipse.jetty.annotations.AnnotationParser.FieldInfo; @@ -29,16 +27,16 @@ import org.eclipse.jetty.plus.annotation.ContainerInitializer; /** * ContainerInitializerAnnotationHandler *

    - * Discovers classes that contain the specified annotation, either at class or - * method level. The specified annotation is derived from an @HandlesTypes on - * a ServletContainerInitializer class. + * Discovers classes that contain the specified annotation, either at class or + * method level. The specified annotation is derived from an @HandlesTypes on + * a ServletContainerInitializer class. */ public class ContainerInitializerAnnotationHandler extends AbstractHandler { final ContainerInitializer _initializer; final Class _annotation; - public ContainerInitializerAnnotationHandler (ContainerInitializer initializer, Class annotation) + public ContainerInitializerAnnotationHandler(ContainerInitializer initializer, Class annotation) { _initializer = initializer; _annotation = annotation; @@ -46,34 +44,34 @@ public class ContainerInitializerAnnotationHandler extends AbstractHandler /** * Handle finding a class that is annotated with the annotation we were constructed with. - * + * * @see org.eclipse.jetty.annotations.AnnotationParser.Handler#handle(org.eclipse.jetty.annotations.AnnotationParser.ClassInfo, String) */ @Override public void handle(ClassInfo info, String annotationName) { if (annotationName == null || !_annotation.getName().equals(annotationName)) - return; - - _initializer.addAnnotatedTypeName(info.getClassName()); + return; + + _initializer.addAnnotatedTypeName(info.getClassName()); } /** * Handle finding a field that is annotated with the annotation we were constructed with. - * + * * @see org.eclipse.jetty.annotations.AnnotationParser.Handler#handle(org.eclipse.jetty.annotations.AnnotationParser.FieldInfo, String) */ @Override public void handle(FieldInfo info, String annotationName) - { + { if (annotationName == null || !_annotation.getName().equals(annotationName)) return; _initializer.addAnnotatedTypeName(info.getClassInfo().getClassName()); } /** - * Handle finding a method that is annotated with the annotation we were constructed with. - * + * Handle finding a method that is annotated with the annotation we were constructed with. + * * @see org.eclipse.jetty.annotations.AnnotationParser.Handler#handle(org.eclipse.jetty.annotations.AnnotationParser.MethodInfo, String) */ @Override @@ -81,10 +79,9 @@ public class ContainerInitializerAnnotationHandler extends AbstractHandler { if (annotationName == null || !_annotation.getName().equals(annotationName)) return; - _initializer.addAnnotatedTypeName(info.getClassInfo().getClassName()); + _initializer.addAnnotatedTypeName(info.getClassInfo().getClassName()); } - public ContainerInitializer getContainerInitializer() { return _initializer; diff --git a/jetty-annotations/src/main/java/org/eclipse/jetty/annotations/DeclareRolesAnnotationHandler.java b/jetty-annotations/src/main/java/org/eclipse/jetty/annotations/DeclareRolesAnnotationHandler.java index c52ba48f3a7..0c5fc003aba 100644 --- a/jetty-annotations/src/main/java/org/eclipse/jetty/annotations/DeclareRolesAnnotationHandler.java +++ b/jetty-annotations/src/main/java/org/eclipse/jetty/annotations/DeclareRolesAnnotationHandler.java @@ -18,7 +18,6 @@ package org.eclipse.jetty.annotations; - import javax.annotation.security.DeclareRoles; import javax.servlet.Servlet; @@ -44,7 +43,6 @@ public class DeclareRolesAnnotationHandler extends AbstractIntrospectableAnnotat _context = context; } - /** * @see org.eclipse.jetty.annotations.AnnotationIntrospector.AbstractIntrospectableAnnotationHandler#doHandle(java.lang.Class) */ @@ -60,7 +58,7 @@ public class DeclareRolesAnnotationHandler extends AbstractIntrospectableAnnotat return; } - DeclareRoles declareRoles = (DeclareRoles) clazz.getAnnotation(DeclareRoles.class); + DeclareRoles declareRoles = (DeclareRoles)clazz.getAnnotation(DeclareRoles.class); if (declareRoles == null) return; @@ -68,9 +66,10 @@ public class DeclareRolesAnnotationHandler extends AbstractIntrospectableAnnotat if (roles != null && roles.length > 0) { - for (String r:roles) + for (String r : roles) + { ((ConstraintSecurityHandler)_context.getSecurityHandler()).addRole(r); + } } } - } diff --git a/jetty-annotations/src/main/java/org/eclipse/jetty/annotations/MultiPartConfigAnnotationHandler.java b/jetty-annotations/src/main/java/org/eclipse/jetty/annotations/MultiPartConfigAnnotationHandler.java index d70bf1b1fcf..920a807c44a 100644 --- a/jetty-annotations/src/main/java/org/eclipse/jetty/annotations/MultiPartConfigAnnotationHandler.java +++ b/jetty-annotations/src/main/java/org/eclipse/jetty/annotations/MultiPartConfigAnnotationHandler.java @@ -30,8 +30,6 @@ import org.eclipse.jetty.webapp.WebAppContext; /** * MultiPartConfigAnnotationHandler - * - * */ public class MultiPartConfigAnnotationHandler extends AbstractIntrospectableAnnotationHandler { @@ -40,10 +38,11 @@ public class MultiPartConfigAnnotationHandler extends AbstractIntrospectableAnno public MultiPartConfigAnnotationHandler(WebAppContext context) { //TODO verify that MultipartConfig is not inheritable - super(false); + super(false); _context = context; } - /** + + /** * @see org.eclipse.jetty.annotations.AnnotationIntrospector.AbstractIntrospectableAnnotationHandler#doHandle(java.lang.Class) */ @Override @@ -51,25 +50,25 @@ public class MultiPartConfigAnnotationHandler extends AbstractIntrospectableAnno { if (!Servlet.class.isAssignableFrom(clazz)) return; - - MultipartConfig multi = (MultipartConfig) clazz.getAnnotation(MultipartConfig.class); + + MultipartConfig multi = (MultipartConfig)clazz.getAnnotation(MultipartConfig.class); if (multi == null) return; - + MetaData metaData = _context.getMetaData(); - + //TODO: The MultipartConfigElement needs to be set on the ServletHolder's Registration. //How to identify the correct Servlet? If the Servlet has no WebServlet annotation on it, does it mean that this MultipartConfig //annotation applies to all declared instances in web.xml/programmatically? //Assuming TRUE for now. for (ServletHolder holder : _context.getServletHandler().getServlets(clazz)) { - Descriptor d = metaData.getOriginDescriptor(holder.getName()+".servlet.multipart-config"); + Descriptor d = metaData.getOriginDescriptor(holder.getName() + ".servlet.multipart-config"); //if a descriptor has already set the value for multipart config, do not //let the annotation override it if (d == null) { - metaData.setOrigin(holder.getName()+".servlet.multipart-config",multi,clazz); + metaData.setOrigin(holder.getName() + ".servlet.multipart-config", multi, clazz); holder.getRegistration().setMultipartConfig(new MultipartConfigElement(multi)); } } diff --git a/jetty-annotations/src/main/java/org/eclipse/jetty/annotations/PostConstructAnnotationHandler.java b/jetty-annotations/src/main/java/org/eclipse/jetty/annotations/PostConstructAnnotationHandler.java index 59d009ac389..e1f637315c8 100644 --- a/jetty-annotations/src/main/java/org/eclipse/jetty/annotations/PostConstructAnnotationHandler.java +++ b/jetty-annotations/src/main/java/org/eclipse/jetty/annotations/PostConstructAnnotationHandler.java @@ -20,7 +20,6 @@ package org.eclipse.jetty.annotations; import java.lang.reflect.Method; import java.lang.reflect.Modifier; - import javax.annotation.PostConstruct; import org.eclipse.jetty.annotations.AnnotationIntrospector.AbstractIntrospectableAnnotationHandler; @@ -34,13 +33,12 @@ public class PostConstructAnnotationHandler extends AbstractIntrospectableAnnota { protected WebAppContext _context; - public PostConstructAnnotationHandler (WebAppContext wac) + public PostConstructAnnotationHandler(WebAppContext wac) { super(true); _context = wac; } - @Override public void doHandle(Class clazz) { @@ -48,19 +46,19 @@ public class PostConstructAnnotationHandler extends AbstractIntrospectableAnnota if (supportsPostConstruct(clazz)) { Method[] methods = clazz.getDeclaredMethods(); - for (int i=0; i> ENV_ENTRY_TYPES = - Arrays.asList(new Class[] {String.class, Character.class, Integer.class, Boolean.class, Double.class, Byte.class, Short.class, Long.class, Float.class}); - + + protected static final List> ENV_ENTRY_TYPES = + Arrays.asList(new Class[]{ + String.class, Character.class, Integer.class, Boolean.class, Double.class, Byte.class, Short.class, Long.class, + Float.class + }); protected WebAppContext _context; - - public ResourceAnnotationHandler (WebAppContext wac) + public ResourceAnnotationHandler(WebAppContext wac) { super(true); _context = wac; } - /** - * Class level Resource annotations declare a name in the - * environment that will be looked up at runtime. They do - * not specify an injection. + * Class level Resource annotations declare a name in the + * environment that will be looked up at runtime. They do + * not specify an injection. */ @Override public void doHandle(Class clazz) @@ -69,37 +68,41 @@ public class ResourceAnnotationHandler extends AbstractIntrospectableAnnotationH handleClass(clazz); Method[] methods = clazz.getDeclaredMethods(); - for (int i=0; i clazz) - { - Resource resource = (Resource)clazz.getAnnotation(Resource.class); - if (resource != null) - { - String name = resource.name(); - String mappedName = resource.mappedName(); + public void handleClass(Class clazz) + { + Resource resource = (Resource)clazz.getAnnotation(Resource.class); + if (resource != null) + { + String name = resource.name(); + String mappedName = resource.mappedName(); - if (name==null || name.trim().equals("")) - throw new IllegalStateException ("Class level Resource annotations must contain a name (Common Annotations Spec Section 2.3)"); + if (name == null || name.trim().equals("")) + throw new IllegalStateException("Class level Resource annotations must contain a name (Common Annotations Spec Section 2.3)"); - try - { - if (!org.eclipse.jetty.plus.jndi.NamingEntryUtil.bindToENC(_context, name,mappedName)) - if (!org.eclipse.jetty.plus.jndi.NamingEntryUtil.bindToENC(_context.getServer(), name,mappedName)) - throw new IllegalStateException("No resource at "+(mappedName==null?name:mappedName)); - } - catch (NamingException e) - { - LOG.warn(e); - } - } + try + { + if (!org.eclipse.jetty.plus.jndi.NamingEntryUtil.bindToENC(_context, name, mappedName)) + if (!org.eclipse.jetty.plus.jndi.NamingEntryUtil.bindToENC(_context.getServer(), name, mappedName)) + throw new IllegalStateException("No resource at " + (mappedName == null ? name : mappedName)); + } + catch (NamingException e) + { + LOG.warn(e); + } + } } public void handleField(Class clazz, Field field) @@ -110,23 +113,23 @@ public class ResourceAnnotationHandler extends AbstractIntrospectableAnnotationH //JavaEE Spec 5.2.3: Field cannot be static if (Modifier.isStatic(field.getModifiers())) { - LOG.warn("Skipping Resource annotation on "+clazz.getName()+"."+field.getName()+": cannot be static"); + LOG.warn("Skipping Resource annotation on " + clazz.getName() + "." + field.getName() + ": cannot be static"); return; } //JavaEE Spec 5.2.3: Field cannot be final if (Modifier.isFinal(field.getModifiers())) { - LOG.warn("Skipping Resource annotation on "+clazz.getName()+"."+field.getName()+": cannot be final"); + LOG.warn("Skipping Resource annotation on " + clazz.getName() + "." + field.getName() + ": cannot be final"); return; } //work out default name - String name = clazz.getCanonicalName()+"/"+field.getName(); + String name = clazz.getCanonicalName() + "/" + field.getName(); //allow @Resource name= to override the field name - name = (resource.name()!=null && !resource.name().trim().equals("")? resource.name(): name); - String mappedName = (resource.mappedName()!=null && !resource.mappedName().trim().equals("")?resource.mappedName():null); + name = (resource.name() != null && !resource.name().trim().equals("") ? resource.name() : name); + String mappedName = (resource.mappedName() != null && !resource.mappedName().trim().equals("") ? resource.mappedName() : null); //get the type of the Field Class type = field.getType(); @@ -134,7 +137,7 @@ public class ResourceAnnotationHandler extends AbstractIntrospectableAnnotationH //If a descriptor has specified at least 1 injection target for this //resource, then it overrides this annotation MetaData metaData = _context.getMetaData(); - if (metaData.getOriginDescriptor("resource-ref."+name+".injection") != null) + if (metaData.getOriginDescriptor("resource-ref." + name + ".injection") != null) { //at least 1 injection was specified for this resource by a descriptor, so //it overrides this annotation @@ -159,15 +162,15 @@ public class ResourceAnnotationHandler extends AbstractIntrospectableAnnotationH if (!bound) bound = org.eclipse.jetty.plus.jndi.NamingEntryUtil.bindToENC(_context.getServer(), name, mappedName); if (!bound) - bound = org.eclipse.jetty.plus.jndi.NamingEntryUtil.bindToENC(null, name, mappedName); + bound = org.eclipse.jetty.plus.jndi.NamingEntryUtil.bindToENC(null, name, mappedName); if (!bound) { //see if there is an env-entry value been bound try { InitialContext ic = new InitialContext(); - String nameInEnvironment = (mappedName!=null?mappedName:name); - ic.lookup("java:comp/env/"+nameInEnvironment); + String nameInEnvironment = (mappedName != null ? mappedName : name); + ic.lookup("java:comp/env/" + nameInEnvironment); bound = true; } catch (NameNotFoundException e) @@ -178,7 +181,7 @@ public class ResourceAnnotationHandler extends AbstractIntrospectableAnnotationH //Check there is a JNDI entry for this annotation if (bound) { - LOG.debug("Bound "+(mappedName==null?name:mappedName) + " as "+ name); + LOG.debug("Bound " + (mappedName == null ? name : mappedName) + " as " + name); // Make the Injection for it if the binding succeeded injection = new Injection(); injection.setTarget(clazz, field, type); @@ -187,7 +190,7 @@ public class ResourceAnnotationHandler extends AbstractIntrospectableAnnotationH injections.add(injection); //TODO - an @Resource is equivalent to a resource-ref, resource-env-ref, message-destination - metaData.setOrigin("resource-ref."+name+".injection",resource,clazz); + metaData.setOrigin("resource-ref." + name + ".injection", resource, clazz); } else if (!isEnvEntryType(type)) { @@ -195,7 +198,7 @@ public class ResourceAnnotationHandler extends AbstractIntrospectableAnnotationH //an error, it just means that perhaps the code will use a default value instead // JavaEE Spec. sec 5.4.1.3 - throw new IllegalStateException("No resource at "+(mappedName==null?name:mappedName)); + throw new IllegalStateException("No resource at " + (mappedName == null ? name : mappedName)); } } catch (NamingException e) @@ -210,14 +213,13 @@ public class ResourceAnnotationHandler extends AbstractIntrospectableAnnotationH } } - /** * Process a Resource annotation on a Method. *

    * This will generate a JNDI entry, and an Injection to be * processed when an instance of the class is created. - * - * @param clazz the class to process + * + * @param clazz the class to process * @param method the method to process */ public void handleMethod(Class clazz, Method method) @@ -246,7 +248,7 @@ public class ResourceAnnotationHandler extends AbstractIntrospectableAnnotationH //JavaEE Spec 5.2.3: Method cannot be static if (Modifier.isStatic(method.getModifiers())) { - LOG.warn("Skipping Resource annotation on "+clazz.getName()+"."+method.getName()+": cannot be static"); + LOG.warn("Skipping Resource annotation on " + clazz.getName() + "." + method.getName() + ": cannot be static"); return; } @@ -254,30 +256,29 @@ public class ResourceAnnotationHandler extends AbstractIntrospectableAnnotationH // only 1 parameter if (!method.getName().startsWith("set")) { - LOG.warn("Skipping Resource annotation on "+clazz.getName()+"."+method.getName()+": invalid java bean, does not start with 'set'"); + LOG.warn("Skipping Resource annotation on " + clazz.getName() + "." + method.getName() + ": invalid java bean, does not start with 'set'"); return; } if (method.getParameterCount() != 1) { - LOG.warn("Skipping Resource annotation on "+clazz.getName()+"."+method.getName()+": invalid java bean, not single argument to method"); + LOG.warn("Skipping Resource annotation on " + clazz.getName() + "." + method.getName() + ": invalid java bean, not single argument to method"); return; } if (Void.TYPE != method.getReturnType()) { - LOG.warn("Skipping Resource annotation on "+clazz.getName()+"."+method.getName()+": invalid java bean, not void"); + LOG.warn("Skipping Resource annotation on " + clazz.getName() + "." + method.getName() + ": invalid java bean, not void"); return; } - //default name is the javabean property name String name = method.getName().substring(3); - name = name.substring(0,1).toLowerCase(Locale.ENGLISH)+name.substring(1); - name = clazz.getCanonicalName()+"/"+name; + name = name.substring(0, 1).toLowerCase(Locale.ENGLISH) + name.substring(1); + name = clazz.getCanonicalName() + "/" + name; - name = (resource.name()!=null && !resource.name().trim().equals("")? resource.name(): name); - String mappedName = (resource.mappedName()!=null && !resource.mappedName().trim().equals("")?resource.mappedName():null); + name = (resource.name() != null && !resource.name().trim().equals("") ? resource.name() : name); + String mappedName = (resource.mappedName() != null && !resource.mappedName().trim().equals("") ? resource.mappedName() : null); Class paramType = method.getParameterTypes()[0]; Class resourceType = resource.type(); @@ -286,7 +287,7 @@ public class ResourceAnnotationHandler extends AbstractIntrospectableAnnotationH //If a descriptor has specified at least 1 injection target for this //resource, then it overrides this annotation MetaData metaData = _context.getMetaData(); - if (metaData.getOriginDescriptor("resource-ref."+name+".injection") != null) + if (metaData.getOriginDescriptor("resource-ref." + name + ".injection") != null) { //at least 1 injection was specified for this resource by a descriptor, so //it overrides this annotation @@ -324,8 +325,8 @@ public class ResourceAnnotationHandler extends AbstractIntrospectableAnnotationH try { InitialContext ic = new InitialContext(); - String nameInEnvironment = (mappedName!=null?mappedName:name); - ic.lookup("java:comp/env/"+nameInEnvironment); + String nameInEnvironment = (mappedName != null ? mappedName : name); + ic.lookup("java:comp/env/" + nameInEnvironment); bound = true; } catch (NameNotFoundException e) @@ -336,15 +337,15 @@ public class ResourceAnnotationHandler extends AbstractIntrospectableAnnotationH if (bound) { - LOG.debug("Bound "+(mappedName==null?name:mappedName) + " as "+ name); + LOG.debug("Bound " + (mappedName == null ? name : mappedName) + " as " + name); // Make the Injection for it injection = new Injection(); - injection.setTarget(clazz, method,paramType,resourceType); + injection.setTarget(clazz, method, paramType, resourceType); injection.setJndiName(name); injection.setMappingName(mappedName); injections.add(injection); //TODO - an @Resource is equivalent to a resource-ref, resource-env-ref, message-destination - metaData.setOrigin("resource-ref."+name+".injection",resource,clazz); + metaData.setOrigin("resource-ref." + name + ".injection", resource, clazz); } else if (!isEnvEntryType(paramType)) { @@ -352,7 +353,7 @@ public class ResourceAnnotationHandler extends AbstractIntrospectableAnnotationH //if this is an env-entry type resource and there is no value bound for it, it isn't //an error, it just means that perhaps the code will use a default value instead // JavaEE Spec. sec 5.4.1.3 - throw new IllegalStateException("No resource at "+(mappedName==null?name:mappedName)); + throw new IllegalStateException("No resource at " + (mappedName == null ? name : mappedName)); } } catch (NamingException e) @@ -364,42 +365,41 @@ public class ResourceAnnotationHandler extends AbstractIntrospectableAnnotationH throw new IllegalStateException(e); } } - } } - + /** * Check if the given Class is one that the specification allows to have a Resource annotation. - * + * * @param c the class * @return true if Resource annotation permitted, false otherwise */ - public boolean supportsResourceInjection (Class c) + public boolean supportsResourceInjection(Class c) { if (javax.servlet.Servlet.class.isAssignableFrom(c) || - javax.servlet.Filter.class.isAssignableFrom(c) || - javax.servlet.ServletContextListener.class.isAssignableFrom(c) || - javax.servlet.ServletContextAttributeListener.class.isAssignableFrom(c) || - javax.servlet.ServletRequestListener.class.isAssignableFrom(c) || - javax.servlet.ServletRequestAttributeListener.class.isAssignableFrom(c) || - javax.servlet.http.HttpSessionListener.class.isAssignableFrom(c) || - javax.servlet.http.HttpSessionAttributeListener.class.isAssignableFrom(c) || - javax.servlet.http.HttpSessionIdListener.class.isAssignableFrom(c) || - javax.servlet.AsyncListener.class.isAssignableFrom(c) || - javax.servlet.http.HttpUpgradeHandler.class.isAssignableFrom(c)) + javax.servlet.Filter.class.isAssignableFrom(c) || + javax.servlet.ServletContextListener.class.isAssignableFrom(c) || + javax.servlet.ServletContextAttributeListener.class.isAssignableFrom(c) || + javax.servlet.ServletRequestListener.class.isAssignableFrom(c) || + javax.servlet.ServletRequestAttributeListener.class.isAssignableFrom(c) || + javax.servlet.http.HttpSessionListener.class.isAssignableFrom(c) || + javax.servlet.http.HttpSessionAttributeListener.class.isAssignableFrom(c) || + javax.servlet.http.HttpSessionIdListener.class.isAssignableFrom(c) || + javax.servlet.AsyncListener.class.isAssignableFrom(c) || + javax.servlet.http.HttpUpgradeHandler.class.isAssignableFrom(c)) return true; - + return false; } - - + /** - * Check if the class is one of the basic java types permitted as + * Check if the class is one of the basic java types permitted as * env-entries. + * * @param clazz the class to check * @return true if class is permitted by the spec to be an env-entry value */ - public boolean isEnvEntryType (Class clazz) + public boolean isEnvEntryType(Class clazz) { return ENV_ENTRY_TYPES.contains(clazz); } diff --git a/jetty-annotations/src/main/java/org/eclipse/jetty/annotations/ResourcesAnnotationHandler.java b/jetty-annotations/src/main/java/org/eclipse/jetty/annotations/ResourcesAnnotationHandler.java index 7b8178aaf35..6428a7dded7 100644 --- a/jetty-annotations/src/main/java/org/eclipse/jetty/annotations/ResourcesAnnotationHandler.java +++ b/jetty-annotations/src/main/java/org/eclipse/jetty/annotations/ResourcesAnnotationHandler.java @@ -31,35 +31,34 @@ public class ResourcesAnnotationHandler extends AbstractIntrospectableAnnotation { private static final Logger LOG = Log.getLogger(ResourcesAnnotationHandler.class); - protected WebAppContext _wac; - public ResourcesAnnotationHandler (WebAppContext wac) + public ResourcesAnnotationHandler(WebAppContext wac) { super(true); _wac = wac; } - + @Override - public void doHandle (Class clazz) + public void doHandle(Class clazz) { Resources resources = (Resources)clazz.getAnnotation(Resources.class); if (resources != null) { Resource[] resArray = resources.value(); - if (resArray==null||resArray.length==0) + if (resArray == null || resArray.length == 0) { - LOG.warn ("Skipping empty or incorrect Resources annotation on "+clazz.getName()); + LOG.warn("Skipping empty or incorrect Resources annotation on " + clazz.getName()); return; } - for (int j=0;j servletMappings = getServletMappings(clazz.getCanonicalName()); - List constraintMappings = ((ConstraintAware)_context.getSecurityHandler()).getConstraintMappings(); + List servletMappings = getServletMappings(clazz.getCanonicalName()); + List constraintMappings = ((ConstraintAware)_context.getSecurityHandler()).getConstraintMappings(); - if (constraintsExist(servletMappings, constraintMappings)) - { - LOG.warn("Constraints already defined for "+clazz.getName()+", skipping ServletSecurity annotation"); - return; - } + if (constraintsExist(servletMappings, constraintMappings)) + { + LOG.warn("Constraints already defined for " + clazz.getName() + ", skipping ServletSecurity annotation"); + return; + } - //Make a fresh list - constraintMappings = new ArrayList(); + //Make a fresh list + constraintMappings = new ArrayList(); - ServletSecurityElement securityElement = new ServletSecurityElement(servletSecurity); - for (ServletMapping sm : servletMappings) - { - for (String url : sm.getPathSpecs()) - { - _context.getMetaData().setOrigin("constraint.url."+url,servletSecurity,clazz); - constraintMappings.addAll(ConstraintSecurityHandler.createConstraintsWithMappingsForPath(clazz.getName(), url, securityElement)); - } - } + ServletSecurityElement securityElement = new ServletSecurityElement(servletSecurity); + for (ServletMapping sm : servletMappings) + { + for (String url : sm.getPathSpecs()) + { + _context.getMetaData().setOrigin("constraint.url." + url, servletSecurity, clazz); + constraintMappings.addAll(ConstraintSecurityHandler.createConstraintsWithMappingsForPath(clazz.getName(), url, securityElement)); + } + } - //set up the security constraints produced by the annotation - ConstraintAware securityHandler = (ConstraintAware)_context.getSecurityHandler(); + //set up the security constraints produced by the annotation + ConstraintAware securityHandler = (ConstraintAware)_context.getSecurityHandler(); - for (ConstraintMapping m:constraintMappings) - securityHandler.addConstraintMapping(m); - - //Servlet Spec 3.1 requires paths with uncovered http methods to be reported - securityHandler.checkPathsWithUncoveredHttpMethods(); + for (ConstraintMapping m : constraintMappings) + { + securityHandler.addConstraintMapping(m); + } + + //Servlet Spec 3.1 requires paths with uncovered http methods to be reported + securityHandler.checkPathsWithUncoveredHttpMethods(); } - - /** * Make a jetty Constraint object, which represents the <auth-constraint> and * <user-data-constraint> elements, based on the security annotation. - * + * * @param servlet the servlet * @param rolesAllowed the roles allowed * @param permitOrDeny the role / permission semantic * @param transport the transport guarantee * @return the constraint */ - protected Constraint makeConstraint (Class servlet, String[] rolesAllowed, EmptyRoleSemantic permitOrDeny, TransportGuarantee transport) + protected Constraint makeConstraint(Class servlet, String[] rolesAllowed, EmptyRoleSemantic permitOrDeny, TransportGuarantee transport) { return ConstraintSecurityHandler.createConstraint(servlet.getName(), rolesAllowed, permitOrDeny, transport); } - - /** * Get the ServletMappings for the servlet's class. + * * @param className the class name * @return the servlet mappings for the class */ @@ -150,22 +148,20 @@ public class ServletSecurityAnnotationHandler extends AbstractIntrospectableAnno //Check the name of the servlet that this mapping applies to, and then find the ServletHolder for it to find it's class ServletHolder holder = _context.getServletHandler().getServlet(mapping.getServletName()); if (holder.getClassName() != null && holder.getClassName().equals(className)) - results.add(mapping); + results.add(mapping); } return results; } - - /** * Check if there are already <security-constraint> elements defined that match the url-patterns for * the servlet. - * + * * @param servletMappings the servlet mappings * @param constraintMappings the constraint mappings * @return true if constraint exists */ - protected boolean constraintsExist (List servletMappings, List constraintMappings) + protected boolean constraintsExist(List servletMappings, List constraintMappings) { boolean exists = false; @@ -181,20 +177,19 @@ public class ServletSecurityAnnotationHandler extends AbstractIntrospectableAnno //Check through the constraints to see if there are any whose pathSpecs (url mappings) //match the servlet. If so, then we already have constraints defined for this servlet, //and we will not be processing the annotation (ie web.xml or programmatic override). - for (int i=0; constraintMappings != null && i < constraintMappings.size() && !exists; i++) - { - for (int j=0; j < pathSpecs.length; j++) - { - //TODO decide if we need to check the origin - if (pathSpecs[j].equals(constraintMappings.get(i).getPathSpec())) - { - exists = true; - break; - } - } - } + for (int i = 0; constraintMappings != null && i < constraintMappings.size() && !exists; i++) + { + for (int j = 0; j < pathSpecs.length; j++) + { + //TODO decide if we need to check the origin + if (pathSpecs[j].equals(constraintMappings.get(i).getPathSpec())) + { + exists = true; + break; + } + } + } } return exists; } - } diff --git a/jetty-annotations/src/main/java/org/eclipse/jetty/annotations/WebFilterAnnotation.java b/jetty-annotations/src/main/java/org/eclipse/jetty/annotations/WebFilterAnnotation.java index 435c9f34280..2813a3aabfc 100644 --- a/jetty-annotations/src/main/java/org/eclipse/jetty/annotations/WebFilterAnnotation.java +++ b/jetty-annotations/src/main/java/org/eclipse/jetty/annotations/WebFilterAnnotation.java @@ -20,7 +20,6 @@ package org.eclipse.jetty.annotations; import java.util.ArrayList; import java.util.EnumSet; - import javax.servlet.DispatcherType; import javax.servlet.Filter; import javax.servlet.annotation.WebFilter; @@ -49,7 +48,7 @@ public class WebFilterAnnotation extends DiscoveredAnnotation { super(context, className); } - + public WebFilterAnnotation(WebAppContext context, String className, Resource resource) { super(context, className, resource); @@ -66,15 +65,14 @@ public class WebFilterAnnotation extends DiscoveredAnnotation Class clazz = getTargetClass(); if (clazz == null) { - LOG.warn(_className+" cannot be loaded"); + LOG.warn(_className + " cannot be loaded"); return; } - //Servlet Spec 8.1.2 if (!Filter.class.isAssignableFrom(clazz)) { - LOG.warn(clazz.getName()+" is not assignable from javax.servlet.Filter"); + LOG.warn(clazz.getName() + " is not assignable from javax.servlet.Filter"); return; } MetaData metaData = _context.getMetaData(); @@ -83,11 +81,11 @@ public class WebFilterAnnotation extends DiscoveredAnnotation if (filterAnnotation.value().length > 0 && filterAnnotation.urlPatterns().length > 0) { - LOG.warn(clazz.getName()+" defines both @WebFilter.value and @WebFilter.urlPatterns"); + LOG.warn(clazz.getName() + " defines both @WebFilter.value and @WebFilter.urlPatterns"); return; } - String name = (filterAnnotation.filterName().equals("")?clazz.getName():filterAnnotation.filterName()); + String name = (filterAnnotation.filterName().equals("") ? clazz.getName() : filterAnnotation.filterName()); String[] urlPatterns = filterAnnotation.value(); if (urlPatterns.length == 0) urlPatterns = filterAnnotation.urlPatterns(); @@ -96,19 +94,19 @@ public class WebFilterAnnotation extends DiscoveredAnnotation if (holder == null) { //Filter with this name does not already exist, so add it - holder = _context.getServletHandler().newFilterHolder(new Source (Source.Origin.ANNOTATION, clazz.getName())); + holder = _context.getServletHandler().newFilterHolder(new Source(Source.Origin.ANNOTATION, clazz.getName())); holder.setName(name); holder.setHeldClass(clazz); - metaData.setOrigin(name+".filter.filter-class",filterAnnotation,clazz); + metaData.setOrigin(name + ".filter.filter-class", filterAnnotation, clazz); holder.setDisplayName(filterAnnotation.displayName()); - metaData.setOrigin(name+".filter.display-name",filterAnnotation,clazz); + metaData.setOrigin(name + ".filter.display-name", filterAnnotation, clazz); - for (WebInitParam ip: filterAnnotation.initParams()) + for (WebInitParam ip : filterAnnotation.initParams()) { holder.setInitParameter(ip.name(), ip.value()); - metaData.setOrigin(name+".filter.init-param."+ip.name(),ip,clazz); + metaData.setOrigin(name + ".filter.init-param." + ip.name(), ip, clazz); } FilterMapping mapping = new FilterMapping(); @@ -117,7 +115,7 @@ public class WebFilterAnnotation extends DiscoveredAnnotation if (urlPatterns.length > 0) { ArrayList paths = new ArrayList(); - for (String s:urlPatterns) + for (String s : urlPatterns) { paths.add(ServletPathSpec.normalize(s)); } @@ -140,10 +138,10 @@ public class WebFilterAnnotation extends DiscoveredAnnotation dispatcherSet.add(d); } mapping.setDispatcherTypes(dispatcherSet); - metaData.setOrigin(name+".filter.mappings",filterAnnotation,clazz); + metaData.setOrigin(name + ".filter.mappings", filterAnnotation, clazz); holder.setAsyncSupported(filterAnnotation.asyncSupported()); - metaData.setOrigin(name+".filter.async-supported",filterAnnotation,clazz); + metaData.setOrigin(name + ".filter.async-supported", filterAnnotation, clazz); _context.getServletHandler().addFilter(holder); _context.getServletHandler().addFilterMapping(mapping); @@ -155,13 +153,13 @@ public class WebFilterAnnotation extends DiscoveredAnnotation //they override the annotation. If it already has DispatcherType set, that //also overrides the annotation. Init-params are additive, but web.xml overrides //init-params of the same name. - for (WebInitParam ip: filterAnnotation.initParams()) + for (WebInitParam ip : filterAnnotation.initParams()) { //if (holder.getInitParameter(ip.name()) == null) - if (metaData.getOrigin(name+".filter.init-param."+ip.name())==Origin.NotSet) + if (metaData.getOrigin(name + ".filter.init-param." + ip.name()) == Origin.NotSet) { holder.setInitParameter(ip.name(), ip.value()); - metaData.setOrigin(name+".filter.init-param."+ip.name(),ip,clazz); + metaData.setOrigin(name + ".filter.init-param." + ip.name(), ip, clazz); } } @@ -169,7 +167,7 @@ public class WebFilterAnnotation extends DiscoveredAnnotation boolean mappingExists = false; if (mappings != null) { - for (FilterMapping m:mappings) + for (FilterMapping m : mappings) { if (m.getFilterName().equals(name)) { @@ -188,7 +186,7 @@ public class WebFilterAnnotation extends DiscoveredAnnotation if (urlPatterns.length > 0) { ArrayList paths = new ArrayList(); - for (String s:urlPatterns) + for (String s : urlPatterns) { paths.add(ServletPathSpec.normalize(s)); } @@ -211,9 +209,8 @@ public class WebFilterAnnotation extends DiscoveredAnnotation } mapping.setDispatcherTypes(dispatcherSet); _context.getServletHandler().addFilterMapping(mapping); - metaData.setOrigin(name+".filter.mappings",filterAnnotation,clazz); + metaData.setOrigin(name + ".filter.mappings", filterAnnotation, clazz); } } } - } diff --git a/jetty-annotations/src/main/java/org/eclipse/jetty/annotations/WebFilterAnnotationHandler.java b/jetty-annotations/src/main/java/org/eclipse/jetty/annotations/WebFilterAnnotationHandler.java index 09ce8bc6fa8..c9b52069c87 100644 --- a/jetty-annotations/src/main/java/org/eclipse/jetty/annotations/WebFilterAnnotationHandler.java +++ b/jetty-annotations/src/main/java/org/eclipse/jetty/annotations/WebFilterAnnotationHandler.java @@ -27,42 +27,39 @@ import org.eclipse.jetty.webapp.WebAppContext; /** * WebFilterAnnotationHandler - * - * */ public class WebFilterAnnotationHandler extends AbstractDiscoverableAnnotationHandler { private static final Logger LOG = Log.getLogger(WebFilterAnnotationHandler.class); - public WebFilterAnnotationHandler (WebAppContext context) + public WebFilterAnnotationHandler(WebAppContext context) { super(context); } - - + @Override public void handle(ClassInfo info, String annotationName) { if (annotationName == null || !"javax.servlet.annotation.WebFilter".equals(annotationName)) return; - + WebFilterAnnotation wfAnnotation = new WebFilterAnnotation(_context, info.getClassName(), info.getContainingResource()); addAnnotation(wfAnnotation); } @Override public void handle(FieldInfo info, String annotationName) - { + { if (annotationName == null || !"javax.servlet.annotation.WebFilter".equals(annotationName)) return; - LOG.warn ("@WebFilter not applicable for fields: "+info.getClassInfo().getClassName()+"."+info.getFieldName()); + LOG.warn("@WebFilter not applicable for fields: " + info.getClassInfo().getClassName() + "." + info.getFieldName()); } @Override public void handle(MethodInfo info, String annotationName) - { + { if (annotationName == null || !"javax.servlet.annotation.WebFilter".equals(annotationName)) return; - LOG.warn ("@WebFilter not applicable for methods: "+info.getClassInfo().getClassName()+"."+info.getMethodName()+" "+info.getSignature()); + LOG.warn("@WebFilter not applicable for methods: " + info.getClassInfo().getClassName() + "." + info.getMethodName() + " " + info.getSignature()); } } diff --git a/jetty-annotations/src/main/java/org/eclipse/jetty/annotations/WebListenerAnnotation.java b/jetty-annotations/src/main/java/org/eclipse/jetty/annotations/WebListenerAnnotation.java index cb0dd23052a..f00341d0e1b 100644 --- a/jetty-annotations/src/main/java/org/eclipse/jetty/annotations/WebListenerAnnotation.java +++ b/jetty-annotations/src/main/java/org/eclipse/jetty/annotations/WebListenerAnnotation.java @@ -19,7 +19,6 @@ package org.eclipse.jetty.annotations; import java.util.EventListener; - import javax.servlet.ServletContextAttributeListener; import javax.servlet.ServletContextListener; import javax.servlet.ServletRequestAttributeListener; @@ -49,7 +48,7 @@ public class WebListenerAnnotation extends DiscoveredAnnotation { super(context, className); } - + public WebListenerAnnotation(WebAppContext context, String className, Resource resource) { super(context, className, resource); @@ -65,30 +64,30 @@ public class WebListenerAnnotation extends DiscoveredAnnotation if (clazz == null) { - LOG.warn(_className+" cannot be loaded"); + LOG.warn(_className + " cannot be loaded"); return; } try { if (ServletContextListener.class.isAssignableFrom(clazz) || - ServletContextAttributeListener.class.isAssignableFrom(clazz) || - ServletRequestListener.class.isAssignableFrom(clazz) || - ServletRequestAttributeListener.class.isAssignableFrom(clazz) || - HttpSessionListener.class.isAssignableFrom(clazz) || - HttpSessionAttributeListener.class.isAssignableFrom(clazz) || - HttpSessionIdListener.class.isAssignableFrom(clazz)) + ServletContextAttributeListener.class.isAssignableFrom(clazz) || + ServletRequestListener.class.isAssignableFrom(clazz) || + ServletRequestAttributeListener.class.isAssignableFrom(clazz) || + HttpSessionListener.class.isAssignableFrom(clazz) || + HttpSessionAttributeListener.class.isAssignableFrom(clazz) || + HttpSessionIdListener.class.isAssignableFrom(clazz)) { - MetaData metaData = _context.getMetaData(); - if (metaData.getOrigin(clazz.getName()+".listener") == Origin.NotSet) - { + MetaData metaData = _context.getMetaData(); + if (metaData.getOrigin(clazz.getName() + ".listener") == Origin.NotSet) + { ListenerHolder h = _context.getServletHandler().newListenerHolder(new Source(Source.Origin.ANNOTATION, clazz.getName())); h.setHeldClass(clazz); _context.getServletHandler().addListener(h); } } else - LOG.warn(clazz.getName()+" does not implement one of the servlet listener interfaces"); + LOG.warn(clazz.getName() + " does not implement one of the servlet listener interfaces"); } catch (Exception e) { diff --git a/jetty-annotations/src/main/java/org/eclipse/jetty/annotations/WebListenerAnnotationHandler.java b/jetty-annotations/src/main/java/org/eclipse/jetty/annotations/WebListenerAnnotationHandler.java index d3b0aa18653..b091ef70fb7 100644 --- a/jetty-annotations/src/main/java/org/eclipse/jetty/annotations/WebListenerAnnotationHandler.java +++ b/jetty-annotations/src/main/java/org/eclipse/jetty/annotations/WebListenerAnnotationHandler.java @@ -29,17 +29,17 @@ public class WebListenerAnnotationHandler extends AbstractDiscoverableAnnotation { private static final Logger LOG = Log.getLogger(WebListenerAnnotationHandler.class); - public WebListenerAnnotationHandler (WebAppContext context) + public WebListenerAnnotationHandler(WebAppContext context) { - super(context); + super(context); } - + @Override public void handle(ClassInfo info, String annotationName) { if (annotationName == null || !"javax.servlet.annotation.WebListener".equals(annotationName)) return; - + WebListenerAnnotation wlAnnotation = new WebListenerAnnotation(_context, info.getClassName(), info.getContainingResource()); addAnnotation(wlAnnotation); } @@ -49,7 +49,7 @@ public class WebListenerAnnotationHandler extends AbstractDiscoverableAnnotation { if (annotationName == null || !"javax.servlet.annotation.WebListener".equals(annotationName)) return; - LOG.warn ("@WebListener is not applicable to fields: "+info.getClassInfo().getClassName()+"."+info.getFieldName()); + LOG.warn("@WebListener is not applicable to fields: " + info.getClassInfo().getClassName() + "." + info.getFieldName()); } @Override @@ -57,6 +57,6 @@ public class WebListenerAnnotationHandler extends AbstractDiscoverableAnnotation { if (annotationName == null || !"javax.servlet.annotation.WebListener".equals(annotationName)) return; - LOG.warn ("@WebListener is not applicable to methods: "+info.getClassInfo().getClassName()+"."+info.getMethodName()+" "+info.getSignature()); + LOG.warn("@WebListener is not applicable to methods: " + info.getClassInfo().getClassName() + "." + info.getMethodName() + " " + info.getSignature()); } } diff --git a/jetty-annotations/src/main/java/org/eclipse/jetty/annotations/WebServletAnnotation.java b/jetty-annotations/src/main/java/org/eclipse/jetty/annotations/WebServletAnnotation.java index d7eaa3bc8fb..5af95057f1f 100644 --- a/jetty-annotations/src/main/java/org/eclipse/jetty/annotations/WebServletAnnotation.java +++ b/jetty-annotations/src/main/java/org/eclipse/jetty/annotations/WebServletAnnotation.java @@ -21,14 +21,12 @@ package org.eclipse.jetty.annotations; import java.util.ArrayList; import java.util.Collections; import java.util.List; - import javax.servlet.Servlet; import javax.servlet.annotation.WebInitParam; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import org.eclipse.jetty.http.pathmap.ServletPathSpec; -import org.eclipse.jetty.servlet.Holder; import org.eclipse.jetty.servlet.ServletHolder; import org.eclipse.jetty.servlet.ServletMapping; import org.eclipse.jetty.servlet.Source; @@ -44,20 +42,17 @@ import org.eclipse.jetty.webapp.WebAppContext; /** * WebServletAnnotation - * - * */ public class WebServletAnnotation extends DiscoveredAnnotation { private static final Logger LOG = Log.getLogger(WebServletAnnotation.class); - public WebServletAnnotation (WebAppContext context, String className) + public WebServletAnnotation(WebAppContext context, String className) { super(context, className); } - - public WebServletAnnotation (WebAppContext context, String className, Resource resource) + public WebServletAnnotation(WebAppContext context, String className, Resource resource) { super(context, className, resource); } @@ -73,14 +68,14 @@ public class WebServletAnnotation extends DiscoveredAnnotation if (clazz == null) { - LOG.warn(_className+" cannot be loaded"); + LOG.warn(_className + " cannot be loaded"); return; } //Servlet Spec 8.1.1 if (!HttpServlet.class.isAssignableFrom(clazz)) { - LOG.warn(clazz.getName()+" is not assignable from javax.servlet.http.HttpServlet"); + LOG.warn(clazz.getName() + " is not assignable from javax.servlet.http.HttpServlet"); return; } @@ -88,7 +83,7 @@ public class WebServletAnnotation extends DiscoveredAnnotation if (annotation.urlPatterns().length > 0 && annotation.value().length > 0) { - LOG.warn(clazz.getName()+ " defines both @WebServlet.value and @WebServlet.urlPatterns"); + LOG.warn(clazz.getName() + " defines both @WebServlet.value and @WebServlet.urlPatterns"); return; } @@ -98,16 +93,18 @@ public class WebServletAnnotation extends DiscoveredAnnotation if (urlPatterns.length == 0) { - LOG.warn(clazz.getName()+ " defines neither @WebServlet.value nor @WebServlet.urlPatterns"); + LOG.warn(clazz.getName() + " defines neither @WebServlet.value nor @WebServlet.urlPatterns"); return; } //canonicalize the patterns ArrayList urlPatternList = new ArrayList(); for (String p : urlPatterns) + { urlPatternList.add(ServletPathSpec.normalize(p)); + } - String servletName = (annotation.name().equals("")?clazz.getName():annotation.name()); + String servletName = (annotation.name().equals("") ? clazz.getName() : annotation.name()); MetaData metaData = _context.getMetaData(); ServletMapping mapping = null; //the new mapping @@ -134,33 +131,32 @@ public class WebServletAnnotation extends DiscoveredAnnotation //No servlet of this name has already been defined, either by a descriptor //or another annotation (which would be impossible). Source source = new Source(Source.Origin.ANNOTATION, clazz.getName()); - + holder = _context.getServletHandler().newServletHolder(source); holder.setHeldClass(clazz); - metaData.setOrigin(servletName+".servlet.servlet-class",annotation,clazz); + metaData.setOrigin(servletName + ".servlet.servlet-class", annotation, clazz); holder.setName(servletName); holder.setDisplayName(annotation.displayName()); - metaData.setOrigin(servletName+".servlet.display-name",annotation,clazz); + metaData.setOrigin(servletName + ".servlet.display-name", annotation, clazz); holder.setInitOrder(annotation.loadOnStartup()); - metaData.setOrigin(servletName+".servlet.load-on-startup",annotation,clazz); + metaData.setOrigin(servletName + ".servlet.load-on-startup", annotation, clazz); holder.setAsyncSupported(annotation.asyncSupported()); - metaData.setOrigin(servletName+".servlet.async-supported",annotation,clazz); + metaData.setOrigin(servletName + ".servlet.async-supported", annotation, clazz); - for (WebInitParam ip:annotation.initParams()) + for (WebInitParam ip : annotation.initParams()) { holder.setInitParameter(ip.name(), ip.value()); - metaData.setOrigin(servletName+".servlet.init-param."+ip.name(),ip,clazz); + metaData.setOrigin(servletName + ".servlet.init-param." + ip.name(), ip, clazz); } _context.getServletHandler().addServlet(holder); - mapping = new ServletMapping(source); mapping.setServletName(holder.getName()); - mapping.setPathSpecs( LazyList.toStringArray(urlPatternList)); + mapping.setPathSpecs(LazyList.toStringArray(urlPatternList)); } else { @@ -175,16 +171,15 @@ public class WebServletAnnotation extends DiscoveredAnnotation //check if the existing servlet has each init-param from the annotation //if not, add it - for (WebInitParam ip:annotation.initParams()) + for (WebInitParam ip : annotation.initParams()) { - if (metaData.getOrigin(servletName+".servlet.init-param."+ip.name())==Origin.NotSet) + if (metaData.getOrigin(servletName + ".servlet.init-param." + ip.name()) == Origin.NotSet) { holder.setInitParameter(ip.name(), ip.value()); - metaData.setOrigin(servletName+".servlet.init-param."+ip.name(),ip,clazz); + metaData.setOrigin(servletName + ".servlet.init-param." + ip.name(), ip, clazz); } } - //check the url-patterns //ServletSpec 3.0 p81 If a servlet already has url mappings from a //webxml or fragment descriptor the annotation is ignored. @@ -201,7 +196,6 @@ public class WebServletAnnotation extends DiscoveredAnnotation } } - //We also want to be able to replace mappings that were defined in webdefault.xml //that were for a different servlet eg a mapping in webdefault.xml for / to the jetty //default servlet should be able to be replaced by an annotation for / to a different @@ -217,7 +211,7 @@ public class WebServletAnnotation extends DiscoveredAnnotation //for each of the urls in the annotation, check if a mapping to same/different servlet exists // if mapping exists and is from a default descriptor, it can be replaced. NOTE: we do not // guard against duplicate path mapping here: that is the job of the ServletHandler - for (String p:urlPatternList) + for (String p : urlPatternList) { ServletMapping existingMapping = _context.getServletHandler().getServletMapping(p); if (existingMapping != null && existingMapping.isDefault()) @@ -227,36 +221,34 @@ public class WebServletAnnotation extends DiscoveredAnnotation if (updatedPaths == null || updatedPaths.length == 0) { boolean success = allMappings.remove(existingMapping); - if (LOG.isDebugEnabled()) LOG.debug("Removed empty mapping {} from defaults descriptor success:{}",existingMapping, success); + if (LOG.isDebugEnabled()) + LOG.debug("Removed empty mapping {} from defaults descriptor success:{}", existingMapping, success); } else { existingMapping.setPathSpecs(updatedPaths); - if (LOG.isDebugEnabled()) LOG.debug("Removed path {} from mapping {} from defaults descriptor ", p,existingMapping); + if (LOG.isDebugEnabled()) + LOG.debug("Removed path {} from mapping {} from defaults descriptor ", p, existingMapping); } } - _context.getMetaData().setOrigin(servletName+".servlet.mapping."+p, annotation, clazz); + _context.getMetaData().setOrigin(servletName + ".servlet.mapping." + p, annotation, clazz); } allMappings.add(mapping); _context.getServletHandler().setServletMappings(allMappings.toArray(new ServletMapping[allMappings.size()])); } } - - - /** - * @param name - * @return + * */ - private List getServletMappingsForServlet (String name) + private List getServletMappingsForServlet(String name) { ServletMapping[] allMappings = _context.getServletHandler().getServletMappings(); if (allMappings == null) return Collections.emptyList(); List mappings = new ArrayList(); - for (ServletMapping m:allMappings) + for (ServletMapping m : allMappings) { if (m.getServletName() != null && name.equals(m.getServletName())) { @@ -266,16 +258,14 @@ public class WebServletAnnotation extends DiscoveredAnnotation return mappings; } - /** - * @param mappings - * @return + * */ - private boolean containsNonDefaultMappings (List mappings) + private boolean containsNonDefaultMappings(List mappings) { if (mappings == null) return false; - for (ServletMapping m:mappings) + for (ServletMapping m : mappings) { if (!m.isDefault()) return true; diff --git a/jetty-annotations/src/main/java/org/eclipse/jetty/annotations/WebServletAnnotationHandler.java b/jetty-annotations/src/main/java/org/eclipse/jetty/annotations/WebServletAnnotationHandler.java index a42dee3a861..fa8cfc046cc 100644 --- a/jetty-annotations/src/main/java/org/eclipse/jetty/annotations/WebServletAnnotationHandler.java +++ b/jetty-annotations/src/main/java/org/eclipse/jetty/annotations/WebServletAnnotationHandler.java @@ -34,12 +34,11 @@ public class WebServletAnnotationHandler extends AbstractDiscoverableAnnotationH { private static final Logger LOG = Log.getLogger(WebServletAnnotationHandler.class); - public WebServletAnnotationHandler (WebAppContext context) + public WebServletAnnotationHandler(WebAppContext context) { super(context); } - /** * Handle discovering a WebServlet annotation. */ @@ -48,8 +47,8 @@ public class WebServletAnnotationHandler extends AbstractDiscoverableAnnotationH { if (annotationName == null || !"javax.servlet.annotation.WebServlet".equals(annotationName)) return; - - WebServletAnnotation annotation = new WebServletAnnotation (_context, info.getClassName(), info.getContainingResource()); + + WebServletAnnotation annotation = new WebServletAnnotation(_context, info.getClassName(), info.getContainingResource()); addAnnotation(annotation); } @@ -58,8 +57,8 @@ public class WebServletAnnotationHandler extends AbstractDiscoverableAnnotationH { if (annotationName == null || !"javax.servlet.annotation.WebServlet".equals(annotationName)) return; - - LOG.warn ("@WebServlet annotation not supported for fields"); + + LOG.warn("@WebServlet annotation not supported for fields"); } @Override @@ -67,7 +66,7 @@ public class WebServletAnnotationHandler extends AbstractDiscoverableAnnotationH { if (annotationName == null || !"javax.servlet.annotation.WebServlet".equals(annotationName)) return; - - LOG.warn ("@WebServlet annotation not supported for methods"); + + LOG.warn("@WebServlet annotation not supported for methods"); } } diff --git a/jetty-annotations/src/test/java/org/acme/ClassOne.java b/jetty-annotations/src/test/java/org/acme/ClassOne.java index 0f643f12de4..2addfb38f76 100644 --- a/jetty-annotations/src/test/java/org/acme/ClassOne.java +++ b/jetty-annotations/src/test/java/org/acme/ClassOne.java @@ -17,13 +17,8 @@ package org.acme; // ======================================================================== // - - - /** * ClassOne - * - * */ public class ClassOne { @@ -31,5 +26,4 @@ public class ClassOne public void one() { } - } diff --git a/jetty-annotations/src/test/java/org/eclipse/jetty/annotations/ClassA.java b/jetty-annotations/src/test/java/org/eclipse/jetty/annotations/ClassA.java index 5af8762c98f..26691a57395 100644 --- a/jetty-annotations/src/test/java/org/eclipse/jetty/annotations/ClassA.java +++ b/jetty-annotations/src/test/java/org/eclipse/jetty/annotations/ClassA.java @@ -18,11 +18,8 @@ package org.eclipse.jetty.annotations; - /** * ClassA - * - * */ @Sample(1) public class ClassA @@ -34,27 +31,26 @@ public class ClassA private Integer j; private Integer k; - public static class Foo { - + } - + @Sample(7) private Integer m; - + @Sample(2) - public void a (Integer[] x) + public void a(Integer[] x) { System.err.println("ClassA.public"); } - + @Sample(3) protected void b(Foo[] f) { System.err.println("ClassA.protected"); } - + @Sample(4) void c(int[] x) { @@ -66,7 +62,7 @@ public class ClassA { System.err.println("ClassA.private"); } - + @Sample(6) protected void l() { @@ -77,22 +73,22 @@ public class ClassA { return this.e; } - + public Integer getF() { return this.f; } - + public Integer getG() { return this.g; } - + public Integer getJ() { return this.j; } - + public void x() { System.err.println("ClassA.x"); diff --git a/jetty-annotations/src/test/java/org/eclipse/jetty/annotations/ClassB.java b/jetty-annotations/src/test/java/org/eclipse/jetty/annotations/ClassB.java index b4c6885e376..3e8b6947bee 100644 --- a/jetty-annotations/src/test/java/org/eclipse/jetty/annotations/ClassB.java +++ b/jetty-annotations/src/test/java/org/eclipse/jetty/annotations/ClassB.java @@ -18,44 +18,38 @@ package org.eclipse.jetty.annotations; - - /** * ClassB - * - * */ -@Sample(value=50) +@Sample(value = 50) @Multi({"do", "re", "mi"}) public class ClassB extends ClassA implements InterfaceD { //test override of public scope method - @Sample(value=51) + @Sample(value = 51) @Multi({"fa", "so", "la"}) public void a() { - System.err.println("ClassB.public"); + System.err.println("ClassB.public"); } - + //test override of package scope method - @Sample(value=52) + @Sample(value = 52) void c() { System.err.println("ClassB.package"); } - + @Override public void l() { System.err.println("Overridden method l has no annotation"); } - - + //test no annotation public void z() { System.err.println("ClassB.z"); } - } diff --git a/jetty-annotations/src/test/java/org/eclipse/jetty/annotations/FilterC.java b/jetty-annotations/src/test/java/org/eclipse/jetty/annotations/FilterC.java index 1556ca8b283..3bf14f2d794 100644 --- a/jetty-annotations/src/test/java/org/eclipse/jetty/annotations/FilterC.java +++ b/jetty-annotations/src/test/java/org/eclipse/jetty/annotations/FilterC.java @@ -19,7 +19,6 @@ package org.eclipse.jetty.annotations; import java.io.IOException; - import javax.annotation.PostConstruct; import javax.annotation.PreDestroy; import javax.annotation.Resource; @@ -37,15 +36,17 @@ import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; -@WebFilter(filterName="CFilter", dispatcherTypes={DispatcherType.REQUEST}, urlPatterns = {"/*"}, initParams={@WebInitParam(name="a", value="99")}, asyncSupported=false) +@WebFilter(filterName = "CFilter", dispatcherTypes = {DispatcherType.REQUEST}, urlPatterns = {"/*"}, initParams = { + @WebInitParam(name = "a", value = "99") +}, asyncSupported = false) @RunAs("admin") public class FilterC implements Filter { - @Resource (mappedName="foo") + @Resource(mappedName = "foo") private Double foo; @PreDestroy - public void pre () + public void pre() { } @@ -56,16 +57,15 @@ public class FilterC implements Filter } - @Override public void doFilter(ServletRequest arg0, ServletResponse arg1, FilterChain arg2) - throws IOException, ServletException + throws IOException, ServletException { HttpServletRequest request = (HttpServletRequest)arg0; HttpServletResponse response = (HttpServletResponse)arg1; HttpSession session = request.getSession(true); String val = request.getParameter("action"); - if (val!=null) + if (val != null) session.setAttribute("action", val); arg2.doFilter(request, response); } diff --git a/jetty-annotations/src/test/java/org/eclipse/jetty/annotations/InterfaceD.java b/jetty-annotations/src/test/java/org/eclipse/jetty/annotations/InterfaceD.java index 0443e951733..5ad229843a1 100644 --- a/jetty-annotations/src/test/java/org/eclipse/jetty/annotations/InterfaceD.java +++ b/jetty-annotations/src/test/java/org/eclipse/jetty/annotations/InterfaceD.java @@ -20,8 +20,6 @@ package org.eclipse.jetty.annotations; /** * InterfaceD - * - * */ public interface InterfaceD { diff --git a/jetty-annotations/src/test/java/org/eclipse/jetty/annotations/ListenerC.java b/jetty-annotations/src/test/java/org/eclipse/jetty/annotations/ListenerC.java index cfd899055e5..b2c426f7988 100644 --- a/jetty-annotations/src/test/java/org/eclipse/jetty/annotations/ListenerC.java +++ b/jetty-annotations/src/test/java/org/eclipse/jetty/annotations/ListenerC.java @@ -29,13 +29,12 @@ public class ListenerC implements ServletContextListener @Override public void contextDestroyed(ServletContextEvent arg0) { - + } @Override public void contextInitialized(ServletContextEvent arg0) { - - } + } } diff --git a/jetty-annotations/src/test/java/org/eclipse/jetty/annotations/Multi.java b/jetty-annotations/src/test/java/org/eclipse/jetty/annotations/Multi.java index 134df024184..fa29523f4e2 100644 --- a/jetty-annotations/src/test/java/org/eclipse/jetty/annotations/Multi.java +++ b/jetty-annotations/src/test/java/org/eclipse/jetty/annotations/Multi.java @@ -25,7 +25,7 @@ import java.lang.annotation.Target; @Retention(RetentionPolicy.RUNTIME) @Target({ElementType.TYPE, ElementType.METHOD, ElementType.FIELD}) -public @interface Multi +public @interface Multi { String[] value(); } diff --git a/jetty-annotations/src/test/java/org/eclipse/jetty/annotations/Sample.java b/jetty-annotations/src/test/java/org/eclipse/jetty/annotations/Sample.java index 8ae1cbc51d8..9635ea95671 100644 --- a/jetty-annotations/src/test/java/org/eclipse/jetty/annotations/Sample.java +++ b/jetty-annotations/src/test/java/org/eclipse/jetty/annotations/Sample.java @@ -25,7 +25,7 @@ import java.lang.annotation.Target; @Retention(RetentionPolicy.RUNTIME) @Target({ElementType.TYPE, ElementType.METHOD, ElementType.FIELD}) -public @interface Sample +public @interface Sample { int value(); } diff --git a/jetty-annotations/src/test/java/org/eclipse/jetty/annotations/ServletC.java b/jetty-annotations/src/test/java/org/eclipse/jetty/annotations/ServletC.java index f95b7867829..02a292adef2 100644 --- a/jetty-annotations/src/test/java/org/eclipse/jetty/annotations/ServletC.java +++ b/jetty-annotations/src/test/java/org/eclipse/jetty/annotations/ServletC.java @@ -19,7 +19,6 @@ package org.eclipse.jetty.annotations; import java.io.IOException; - import javax.annotation.PostConstruct; import javax.annotation.PreDestroy; import javax.annotation.Resource; @@ -37,17 +36,21 @@ import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; @DeclareRoles({"alice"}) -@WebServlet(urlPatterns = { "/foo/*", "/bah/*" }, name="CServlet", initParams={@WebInitParam(name="x", value="y")}, loadOnStartup=2, asyncSupported=false) -@MultipartConfig(fileSizeThreshold=1000, maxFileSize=2000, maxRequestSize=3000) +@WebServlet(urlPatterns = {"/foo/*", "/bah/*"}, name = "CServlet", initParams = { + @WebInitParam(name = "x", value = "y") +}, loadOnStartup = 2, asyncSupported = false) +@MultipartConfig(fileSizeThreshold = 1000, maxFileSize = 2000, maxRequestSize = 3000) @RunAs("admin") -@ServletSecurity(value=@HttpConstraint(rolesAllowed={"fred", "bill", "dorothy"}), httpMethodConstraints={@HttpMethodConstraint(value="GET", rolesAllowed={"bob", "carol", "ted"})}) +@ServletSecurity(value = @HttpConstraint(rolesAllowed = {"fred", "bill", "dorothy"}), httpMethodConstraints = { + @HttpMethodConstraint(value = "GET", rolesAllowed = {"bob", "carol", "ted"}) +}) public class ServletC extends HttpServlet { - @Resource (mappedName="foo", type=Double.class) + @Resource(mappedName = "foo", type = Double.class) private Double foo; @PreDestroy - public void pre () + public void pre() { } diff --git a/jetty-annotations/src/test/java/org/eclipse/jetty/annotations/ServletD.java b/jetty-annotations/src/test/java/org/eclipse/jetty/annotations/ServletD.java index 6a00d5f808d..436a8ca10e9 100644 --- a/jetty-annotations/src/test/java/org/eclipse/jetty/annotations/ServletD.java +++ b/jetty-annotations/src/test/java/org/eclipse/jetty/annotations/ServletD.java @@ -22,9 +22,9 @@ import javax.servlet.annotation.WebInitParam; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; - - -@WebServlet(urlPatterns = { "/", "/bah/*" }, name="DServlet", initParams={@WebInitParam(name="x", value="y")}, loadOnStartup=1, asyncSupported=false) +@WebServlet(urlPatterns = {"/", "/bah/*"}, name = "DServlet", initParams = { + @WebInitParam(name = "x", value = "y") +}, loadOnStartup = 1, asyncSupported = false) public class ServletD extends HttpServlet { diff --git a/jetty-annotations/src/test/java/org/eclipse/jetty/annotations/TestAnnotationConfiguration.java b/jetty-annotations/src/test/java/org/eclipse/jetty/annotations/TestAnnotationConfiguration.java index e9deb4dc928..e362019e55b 100644 --- a/jetty-annotations/src/test/java/org/eclipse/jetty/annotations/TestAnnotationConfiguration.java +++ b/jetty-annotations/src/test/java/org/eclipse/jetty/annotations/TestAnnotationConfiguration.java @@ -45,7 +45,7 @@ public class TestAnnotationConfiguration { public class TestableAnnotationConfiguration extends AnnotationConfiguration { - public void assertAnnotationDiscovery (boolean b) + public void assertAnnotationDiscovery(boolean b) { if (!b) assertTrue(_discoverableAnnotationHandlers.isEmpty()); @@ -102,14 +102,18 @@ public class TestAnnotationConfiguration JAR.unpack(testWebInfClassesJar, unpacked); webInfClasses = Resource.newResource(unpacked); - containerLoader = new URLClassLoader(new URL[] { testContainerSciJar.toURI().toURL() }, Thread.currentThread().getContextClassLoader()); + containerLoader = new URLClassLoader(new URL[]{ + testContainerSciJar.toURI().toURL() + }, Thread.currentThread().getContextClassLoader()); targetClasses = Resource.newResource(MavenTestingUtils.getTargetDir().toURI()).addPath("/test-classes"); - classes = Arrays.asList(new Resource[] { webInfClasses, targetClasses }); + classes = Arrays.asList(new Resource[]{webInfClasses, targetClasses}); - webAppLoader = new URLClassLoader(new URL[] { testSciJar.toURI().toURL(), targetClasses.getURI().toURL(), webInfClasses.getURI().toURL() }, - containerLoader); + webAppLoader = new URLClassLoader(new URL[]{ + testSciJar.toURI().toURL(), targetClasses.getURI().toURL(), webInfClasses.getURI().toURL() + }, + containerLoader); } @Test @@ -126,7 +130,7 @@ public class TestAnnotationConfiguration context25.getServletContext().setEffectiveMinorVersion(5); config25.configure(context25); config25.assertAnnotationDiscovery(false); - + //check that a 2.5 webapp with configurationDiscovered will discover annotations TestableAnnotationConfiguration config25b = new TestableAnnotationConfiguration(); WebAppContext context25b = new WebAppContext(); @@ -139,7 +143,7 @@ public class TestAnnotationConfiguration context25b.getServletContext().setEffectiveMinorVersion(5); config25b.configure(context25b); config25b.assertAnnotationDiscovery(true); - + //check that a 3.x webapp with metadata true won't discover annotations TestableAnnotationConfiguration config31 = new TestableAnnotationConfiguration(); WebAppContext context31 = new WebAppContext(); @@ -151,7 +155,7 @@ public class TestAnnotationConfiguration context31.getServletContext().setEffectiveMinorVersion(1); config31.configure(context31); config31.assertAnnotationDiscovery(false); - + //check that a 3.x webapp with metadata false will discover annotations TestableAnnotationConfiguration config31b = new TestableAnnotationConfiguration(); WebAppContext context31b = new WebAppContext(); @@ -220,12 +224,12 @@ public class TestAnnotationConfiguration assertNotNull(scis); assertEquals(3, scis.size()); assertEquals("com.acme.ServerServletContainerInitializer", scis.get(0).getClass().getName()); // container - // path + // path assertEquals("com.acme.webinf.WebInfClassServletContainerInitializer", scis.get(1).getClass().getName()); // web-inf assertEquals("com.acme.initializer.FooInitializer", scis.get(2).getClass().getName()); // web-inf - // jar - // no - // web-fragment + // jar + // no + // web-fragment } finally { @@ -243,9 +247,11 @@ public class TestAnnotationConfiguration File orderedFragmentJar = new File(jarDir, "test-sci-with-ordering.jar"); assertTrue(orderedFragmentJar.exists()); - URLClassLoader orderedLoader = new URLClassLoader(new URL[] { orderedFragmentJar.toURI().toURL(), testSciJar.toURI().toURL(), - targetClasses.getURI().toURL(), webInfClasses.getURI().toURL() }, - containerLoader); + URLClassLoader orderedLoader = new URLClassLoader(new URL[]{ + orderedFragmentJar.toURI().toURL(), testSciJar.toURI().toURL(), + targetClasses.getURI().toURL(), webInfClasses.getURI().toURL() + }, + containerLoader); Thread.currentThread().setContextClassLoader(orderedLoader); try @@ -270,7 +276,6 @@ public class TestAnnotationConfiguration assertEquals("com.acme.webinf.WebInfClassServletContainerInitializer", scis.get(1).getClass().getName()); // web-inf assertEquals("com.acme.ordering.AcmeServletContainerInitializer", scis.get(2).getClass().getName()); // first assertEquals("com.acme.initializer.FooInitializer", scis.get(3).getClass().getName()); //other in ordering - } finally { @@ -297,7 +302,7 @@ public class TestAnnotationConfiguration context.getServletContext().setEffectiveMinorVersion(5); scis = config.getNonExcludedInitializers(context); assertNotNull(scis); - for (ServletContainerInitializer s:scis) + for (ServletContainerInitializer s : scis) { //should not have any of the web-inf lib scis in here assertFalse(s.getClass().getName().equals("com.acme.ordering.AcmeServletContainerInitializer")); @@ -338,7 +343,6 @@ public class TestAnnotationConfiguration assertEquals("com.acme.ServerServletContainerInitializer", scis.get(0).getClass().getName()); //container path assertEquals("com.acme.webinf.WebInfClassServletContainerInitializer", scis.get(1).getClass().getName()); // web-inf assertEquals("com.acme.initializer.FooInitializer", scis.get(2).getClass().getName()); //web-inf jar no web-fragment - } finally { @@ -346,24 +350,22 @@ public class TestAnnotationConfiguration } } - - @Test public void testGetFragmentFromJar() throws Exception { String dir = MavenTestingUtils.getTargetTestingDir("getFragmentFromJar").getAbsolutePath(); File file = new File(dir); - file=new File(file.getCanonicalPath()); - URL url=file.toURI().toURL(); + file = new File(file.getCanonicalPath()); + URL url = file.toURI().toURL(); - Resource jar1 = Resource.newResource(url+"file.jar"); + Resource jar1 = Resource.newResource(url + "file.jar"); AnnotationConfiguration config = new AnnotationConfiguration(); WebAppContext wac = new WebAppContext(); List frags = new ArrayList(); - frags.add(new FragmentDescriptor(Resource.newResource("jar:"+url+"file.jar!/fooa.props"))); - frags.add(new FragmentDescriptor(Resource.newResource("jar:"+url+"file2.jar!/foob.props"))); + frags.add(new FragmentDescriptor(Resource.newResource("jar:" + url + "file.jar!/fooa.props"))); + frags.add(new FragmentDescriptor(Resource.newResource("jar:" + url + "file2.jar!/foob.props"))); assertNotNull(config.getFragmentFromJar(jar1, frags)); } diff --git a/jetty-annotations/src/test/java/org/eclipse/jetty/annotations/TestAnnotationInheritance.java b/jetty-annotations/src/test/java/org/eclipse/jetty/annotations/TestAnnotationInheritance.java index c3a22e1b631..ac5f8551f0f 100644 --- a/jetty-annotations/src/test/java/org/eclipse/jetty/annotations/TestAnnotationInheritance.java +++ b/jetty-annotations/src/test/java/org/eclipse/jetty/annotations/TestAnnotationInheritance.java @@ -18,22 +18,12 @@ package org.eclipse.jetty.annotations; -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.contains; -import static org.hamcrest.Matchers.containsInAnyOrder; -import static org.hamcrest.Matchers.hasKey; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertFalse; -import static org.junit.jupiter.api.Assertions.assertNotNull; -import static org.junit.jupiter.api.Assertions.assertTrue; - import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; - import javax.naming.Context; import javax.naming.InitialContext; @@ -44,14 +34,22 @@ import org.eclipse.jetty.annotations.AnnotationParser.MethodInfo; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.Test; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.contains; +import static org.hamcrest.Matchers.containsInAnyOrder; +import static org.hamcrest.Matchers.hasKey; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertTrue; + /** * */ public class TestAnnotationInheritance { List classNames = new ArrayList(); - - + class SampleHandler extends AbstractHandler { public final List annotatedClassNames = new ArrayList(); @@ -63,16 +61,16 @@ public class TestAnnotationInheritance { if (annotation == null || !"org.eclipse.jetty.annotations.Sample".equals(annotation)) return; - + annotatedClassNames.add(info.getClassName()); } @Override public void handle(FieldInfo info, String annotation) - { + { if (annotation == null || !"org.eclipse.jetty.annotations.Sample".equals(annotation)) return; - annotatedFields.add(info.getClassInfo().getClassName()+"."+info.getFieldName()); + annotatedFields.add(info.getClassInfo().getClassName() + "." + info.getFieldName()); } @Override @@ -80,13 +78,13 @@ public class TestAnnotationInheritance { if (annotation == null || !"org.eclipse.jetty.annotations.Sample".equals(annotation)) return; - annotatedMethods.add(info.getClassInfo().getClassName()+"."+info.getMethodName()); + annotatedMethods.add(info.getClassInfo().getClassName() + "." + info.getMethodName()); } - + @Override public String toString() { - return annotatedClassNames.toString()+annotatedMethods+annotatedFields; + return annotatedClassNames.toString() + annotatedMethods + annotatedFields; } } @@ -113,14 +111,14 @@ public class TestAnnotationInheritance assertEquals(2, handler.annotatedClassNames.size()); //check we got all annotated methods on each class - assertEquals (7, handler.annotatedMethods.size()); - assertTrue (handler.annotatedMethods.contains("org.eclipse.jetty.annotations.ClassA.a")); - assertTrue (handler.annotatedMethods.contains("org.eclipse.jetty.annotations.ClassA.b")); - assertTrue (handler.annotatedMethods.contains("org.eclipse.jetty.annotations.ClassA.c")); - assertTrue (handler.annotatedMethods.contains("org.eclipse.jetty.annotations.ClassA.d")); - assertTrue (handler.annotatedMethods.contains("org.eclipse.jetty.annotations.ClassA.l")); - assertTrue (handler.annotatedMethods.contains("org.eclipse.jetty.annotations.ClassB.a")); - assertTrue (handler.annotatedMethods.contains("org.eclipse.jetty.annotations.ClassB.c")); + assertEquals(7, handler.annotatedMethods.size()); + assertTrue(handler.annotatedMethods.contains("org.eclipse.jetty.annotations.ClassA.a")); + assertTrue(handler.annotatedMethods.contains("org.eclipse.jetty.annotations.ClassA.b")); + assertTrue(handler.annotatedMethods.contains("org.eclipse.jetty.annotations.ClassA.c")); + assertTrue(handler.annotatedMethods.contains("org.eclipse.jetty.annotations.ClassA.d")); + assertTrue(handler.annotatedMethods.contains("org.eclipse.jetty.annotations.ClassA.l")); + assertTrue(handler.annotatedMethods.contains("org.eclipse.jetty.annotations.ClassB.a")); + assertTrue(handler.annotatedMethods.contains("org.eclipse.jetty.annotations.ClassB.c")); //check we got all annotated fields on each class assertEquals(1, handler.annotatedFields.size()); @@ -138,14 +136,14 @@ public class TestAnnotationInheritance assertEquals(2, handler.annotatedClassNames.size()); //check we got all annotated methods on each class - assertEquals (7, handler.annotatedMethods.size()); - assertTrue (handler.annotatedMethods.contains("org.eclipse.jetty.annotations.ClassA.a")); - assertTrue (handler.annotatedMethods.contains("org.eclipse.jetty.annotations.ClassA.b")); - assertTrue (handler.annotatedMethods.contains("org.eclipse.jetty.annotations.ClassA.c")); - assertTrue (handler.annotatedMethods.contains("org.eclipse.jetty.annotations.ClassA.d")); - assertTrue (handler.annotatedMethods.contains("org.eclipse.jetty.annotations.ClassA.l")); - assertTrue (handler.annotatedMethods.contains("org.eclipse.jetty.annotations.ClassB.a")); - assertTrue (handler.annotatedMethods.contains("org.eclipse.jetty.annotations.ClassB.c")); + assertEquals(7, handler.annotatedMethods.size()); + assertTrue(handler.annotatedMethods.contains("org.eclipse.jetty.annotations.ClassA.a")); + assertTrue(handler.annotatedMethods.contains("org.eclipse.jetty.annotations.ClassA.b")); + assertTrue(handler.annotatedMethods.contains("org.eclipse.jetty.annotations.ClassA.c")); + assertTrue(handler.annotatedMethods.contains("org.eclipse.jetty.annotations.ClassA.d")); + assertTrue(handler.annotatedMethods.contains("org.eclipse.jetty.annotations.ClassA.l")); + assertTrue(handler.annotatedMethods.contains("org.eclipse.jetty.annotations.ClassB.a")); + assertTrue(handler.annotatedMethods.contains("org.eclipse.jetty.annotations.ClassB.c")); //check we got all annotated fields on each class assertEquals(1, handler.annotatedFields.size()); @@ -156,7 +154,7 @@ public class TestAnnotationInheritance public void testTypeInheritanceHandling() throws Exception { Map> map = new ConcurrentHashMap<>(); - + AnnotationParser parser = new AnnotationParser(); ClassInheritanceHandler handler = new ClassInheritanceHandler(map); @@ -183,6 +181,6 @@ public class TestAnnotationInheritance classes = map.get("org.eclipse.jetty.annotations.InterfaceD"); assertThat(classes, containsInAnyOrder("org.eclipse.jetty.annotations.ClassB", - Foo.class.getName())); + Foo.class.getName())); } } diff --git a/jetty-annotations/src/test/java/org/eclipse/jetty/annotations/TestAnnotationParser.java b/jetty-annotations/src/test/java/org/eclipse/jetty/annotations/TestAnnotationParser.java index 05e54e8823c..281d8bd17d0 100644 --- a/jetty-annotations/src/test/java/org/eclipse/jetty/annotations/TestAnnotationParser.java +++ b/jetty-annotations/src/test/java/org/eclipse/jetty/annotations/TestAnnotationParser.java @@ -80,8 +80,7 @@ public class TestAnnotationParser foundClasses.add(info.getClassName()); } } - - + public static class DuplicateClassScanHandler extends AnnotationParser.AbstractHandler { private Map> _classMap = new ConcurrentHashMap(); @@ -91,21 +90,19 @@ public class TestAnnotationParser { List list = new CopyOnWriteArrayList<>(); Resource r = info.getContainingResource(); - list.add((r==null?"":r.toString())); - + list.add((r == null ? "" : r.toString())); + List existing = _classMap.putIfAbsent(info.getClassName(), list); if (existing != null) { existing.addAll(list); } } - - + public List getParsedList(String classname) { return _classMap.get(classname); } - } public WorkDir testdir; @@ -114,12 +111,12 @@ public class TestAnnotationParser public void testSampleAnnotation() throws Exception { String[] classNames = new String[] - { "org.eclipse.jetty.annotations.ClassA" }; + {"org.eclipse.jetty.annotations.ClassA"}; AnnotationParser parser = new AnnotationParser(); class SampleAnnotationHandler extends AnnotationParser.AbstractHandler { - private List methods = Arrays.asList("a","b","c","d","l"); + private List methods = Arrays.asList("a", "b", "c", "d", "l"); @Override public void handle(ClassInfo info, String annotation) @@ -127,26 +124,26 @@ public class TestAnnotationParser if (annotation == null || !"org.eclipse.jetty.annotations.Sample".equals(annotation)) return; - assertEquals("org.eclipse.jetty.annotations.ClassA",info.getClassName()); + assertEquals("org.eclipse.jetty.annotations.ClassA", info.getClassName()); } @Override public void handle(FieldInfo info, String annotation) - { + { if (annotation == null || !"org.eclipse.jetty.annotations.Sample".equals(annotation)) return; - assertEquals("m",info.getFieldName()); - assertEquals(org.objectweb.asm.Type.OBJECT,org.objectweb.asm.Type.getType(info.getFieldType()).getSort()); + assertEquals("m", info.getFieldName()); + assertEquals(org.objectweb.asm.Type.OBJECT, org.objectweb.asm.Type.getType(info.getFieldType()).getSort()); } @Override public void handle(MethodInfo info, String annotation) - { + { if (annotation == null || !"org.eclipse.jetty.annotations.Sample".equals(annotation)) return; - assertEquals("org.eclipse.jetty.annotations.ClassA",info.getClassInfo().getClassName()); + assertEquals("org.eclipse.jetty.annotations.ClassA", info.getClassInfo().getClassName()); assertThat(info.getMethodName(), is(in(methods))); - assertEquals("org.eclipse.jetty.annotations.Sample",annotation); + assertEquals("org.eclipse.jetty.annotations.Sample", annotation); } } @@ -161,7 +158,7 @@ public class TestAnnotationParser public void testMultiAnnotation() throws Exception { String[] classNames = new String[] - { "org.eclipse.jetty.annotations.ClassB" }; + {"org.eclipse.jetty.annotations.ClassB"}; AnnotationParser parser = new AnnotationParser(); class MultiAnnotationHandler extends AnnotationParser.AbstractHandler @@ -169,7 +166,7 @@ public class TestAnnotationParser @Override public void handle(ClassInfo info, String annotation) { - if (annotation == null || ! "org.eclipse.jetty.annotations.Multi".equals(annotation)) + if (annotation == null || !"org.eclipse.jetty.annotations.Multi".equals(annotation)) return; assertTrue("org.eclipse.jetty.annotations.ClassB".equals(info.getClassName())); } @@ -177,14 +174,14 @@ public class TestAnnotationParser @Override public void handle(FieldInfo info, String annotation) { - assertTrue(annotation == null || ! "org.eclipse.jetty.annotations.Multi".equals(annotation), - "There should not be any"); + assertTrue(annotation == null || !"org.eclipse.jetty.annotations.Multi".equals(annotation), + "There should not be any"); } @Override public void handle(MethodInfo info, String annotation) - { - if (annotation == null || ! "org.eclipse.jetty.annotations.Multi".equals(annotation)) + { + if (annotation == null || !"org.eclipse.jetty.annotations.Multi".equals(annotation)) return; assertTrue("org.eclipse.jetty.annotations.ClassB".equals(info.getClassInfo().getClassName())); assertTrue("a".equals(info.getMethodName())); @@ -247,22 +244,21 @@ public class TestAnnotationParser FS.ensureEmpty(basedir); // Copy in class that is known to have annotations. - copyClass(ClassA.class,basedir); + copyClass(ClassA.class, basedir); // Setup Tracker TrackingAnnotationHandler tracker = new TrackingAnnotationHandler(Sample.class.getName()); // Setup annotation scanning AnnotationParser parser = new AnnotationParser(); - + // Parse parser.parse(Collections.singleton(tracker), basedir.toURI()); - + // Validate assertThat("Found Class", tracker.foundClasses, contains(ClassA.class.getName())); } - - + @Test public void testScanDuplicateClassesInJars() throws Exception { @@ -272,14 +268,13 @@ public class TestAnnotationParser DuplicateClassScanHandler handler = new DuplicateClassScanHandler(); Set handlers = Collections.singleton(handler); parser.parse(handlers, testJar); - parser.parse(handlers, testJar2); + parser.parse(handlers, testJar2); List locations = handler.getParsedList("org.acme.ClassOne"); assertNotNull(locations); assertEquals(2, locations.size()); assertTrue(!(locations.get(0).equals(locations.get(1)))); } - - + @Test public void testScanDuplicateClasses() throws Exception { @@ -289,14 +284,12 @@ public class TestAnnotationParser DuplicateClassScanHandler handler = new DuplicateClassScanHandler(); Set handlers = Collections.singleton(handler); parser.parse(handlers, testJar); - parser.parse(handlers, Resource.newResource(testClasses)); - Listlocations = handler.getParsedList("org.acme.ClassOne"); + parser.parse(handlers, Resource.newResource(testClasses)); + List locations = handler.getParsedList("org.acme.ClassOne"); assertNotNull(locations); assertEquals(2, locations.size()); assertTrue(!(locations.get(0).equals(locations.get(1)))); } - - private void copyClass(Class clazz, File basedir) throws IOException { diff --git a/jetty-annotations/src/test/java/org/eclipse/jetty/annotations/TestSecurityAnnotationConversions.java b/jetty-annotations/src/test/java/org/eclipse/jetty/annotations/TestSecurityAnnotationConversions.java index 111e91c70b7..c5aec612b5f 100644 --- a/jetty-annotations/src/test/java/org/eclipse/jetty/annotations/TestSecurityAnnotationConversions.java +++ b/jetty-annotations/src/test/java/org/eclipse/jetty/annotations/TestSecurityAnnotationConversions.java @@ -18,15 +18,8 @@ package org.eclipse.jetty.annotations; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertNotNull; -import static org.junit.jupiter.api.Assertions.assertNull; -import static org.junit.jupiter.api.Assertions.assertTrue; -import static org.junit.jupiter.api.Assertions.fail; - import java.util.Arrays; import java.util.List; - import javax.servlet.annotation.HttpConstraint; import javax.servlet.annotation.HttpMethodConstraint; import javax.servlet.annotation.ServletSecurity; @@ -43,9 +36,15 @@ import org.eclipse.jetty.util.security.Constraint; import org.eclipse.jetty.webapp.WebAppContext; import org.junit.jupiter.api.Test; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.fail; + public class TestSecurityAnnotationConversions { - @ServletSecurity(value=@HttpConstraint(value=EmptyRoleSemantic.DENY)) + @ServletSecurity(value = @HttpConstraint(value = EmptyRoleSemantic.DENY)) public static class DenyServlet extends HttpServlet {} @@ -53,21 +52,26 @@ public class TestSecurityAnnotationConversions public static class PermitServlet extends HttpServlet {} - @ServletSecurity(value=@HttpConstraint(value=EmptyRoleSemantic.PERMIT, transportGuarantee=TransportGuarantee.CONFIDENTIAL, rolesAllowed={"tom", "dick", "harry"})) + @ServletSecurity(value = @HttpConstraint(value = EmptyRoleSemantic.PERMIT, transportGuarantee = TransportGuarantee.CONFIDENTIAL, rolesAllowed = { + "tom", "dick", "harry" + })) public static class RolesServlet extends HttpServlet {} - @ServletSecurity(value=@HttpConstraint(value=EmptyRoleSemantic.PERMIT, transportGuarantee=TransportGuarantee.CONFIDENTIAL, rolesAllowed={"tom", "dick", "harry"}), - httpMethodConstraints={@HttpMethodConstraint(value="GET")}) + @ServletSecurity(value = @HttpConstraint(value = EmptyRoleSemantic.PERMIT, transportGuarantee = TransportGuarantee.CONFIDENTIAL, rolesAllowed = { + "tom", "dick", "harry" + }), + httpMethodConstraints = {@HttpMethodConstraint(value = "GET")}) public static class Method1Servlet extends HttpServlet {} - @ServletSecurity(value=@HttpConstraint(value=EmptyRoleSemantic.PERMIT, transportGuarantee=TransportGuarantee.CONFIDENTIAL, rolesAllowed={"tom", "dick", "harry"}), - httpMethodConstraints={@HttpMethodConstraint(value="GET", transportGuarantee=TransportGuarantee.CONFIDENTIAL)}) + @ServletSecurity(value = @HttpConstraint(value = EmptyRoleSemantic.PERMIT, transportGuarantee = TransportGuarantee.CONFIDENTIAL, rolesAllowed = { + "tom", "dick", "harry" + }), + httpMethodConstraints = {@HttpMethodConstraint(value = "GET", transportGuarantee = TransportGuarantee.CONFIDENTIAL)}) public static class Method2Servlet extends HttpServlet {} - public void setUp() { } @@ -76,7 +80,9 @@ public class TestSecurityAnnotationConversions public void testDenyAllOnClass() throws Exception { - WebAppContext wac = makeWebAppContext(DenyServlet.class.getCanonicalName(), "denyServlet", new String[]{"/foo/*", "*.foo"}); + WebAppContext wac = makeWebAppContext(DenyServlet.class.getCanonicalName(), "denyServlet", new String[]{ + "/foo/*", "*.foo" + }); //Assume we found 1 servlet with a @HttpConstraint with value=EmptyRoleSemantic.DENY security annotation ServletSecurityAnnotationHandler annotationHandler = new ServletSecurityAnnotationHandler(wac); @@ -108,22 +114,22 @@ public class TestSecurityAnnotationConversions public void testPermitAll() throws Exception { //Assume we found 1 servlet with a @ServletSecurity security annotation - WebAppContext wac = makeWebAppContext(PermitServlet.class.getCanonicalName(), "permitServlet", new String[]{"/foo/*", "*.foo"}); + WebAppContext wac = makeWebAppContext(PermitServlet.class.getCanonicalName(), "permitServlet", new String[]{ + "/foo/*", "*.foo" + }); ServletSecurityAnnotationHandler annotationHandler = new ServletSecurityAnnotationHandler(wac); AnnotationIntrospector introspector = new AnnotationIntrospector(); introspector.registerHandler(annotationHandler); - //set up the expected outcomes - no constraints at all as per Servlet Spec 3.1 pg 129 //1 ConstraintMapping per ServletMapping pathSpec - ConstraintMapping[] expectedMappings = new ConstraintMapping[]{}; - + introspector.introspect(PermitServlet.class); - compareResults (expectedMappings, ((ConstraintAware)wac.getSecurityHandler()).getConstraintMappings()); + compareResults(expectedMappings, ((ConstraintAware)wac.getSecurityHandler()).getConstraintMappings()); } @Test @@ -132,7 +138,9 @@ public class TestSecurityAnnotationConversions //Assume we found 1 servlet with annotation with roles defined and //and a TransportGuarantee - WebAppContext wac = makeWebAppContext(RolesServlet.class.getCanonicalName(), "rolesServlet", new String[]{"/foo/*", "*.foo"}); + WebAppContext wac = makeWebAppContext(RolesServlet.class.getCanonicalName(), "rolesServlet", new String[]{ + "/foo/*", "*.foo" + }); ServletSecurityAnnotationHandler annotationHandler = new ServletSecurityAnnotationHandler(wac); AnnotationIntrospector introspector = new AnnotationIntrospector(); @@ -155,7 +163,7 @@ public class TestSecurityAnnotationConversions expectedMappings[1].setPathSpec("*.foo"); introspector.introspect(RolesServlet.class); - compareResults (expectedMappings, ((ConstraintAware)wac.getSecurityHandler()).getConstraintMappings()); + compareResults(expectedMappings, ((ConstraintAware)wac.getSecurityHandler()).getConstraintMappings()); } @Test @@ -164,7 +172,9 @@ public class TestSecurityAnnotationConversions //ServletSecurity annotation with HttpConstraint of TransportGuarantee.CONFIDENTIAL, and a list of rolesAllowed, and //a HttpMethodConstraint for GET method that permits all and has TransportGuarantee.NONE (ie is default) - WebAppContext wac = makeWebAppContext(Method1Servlet.class.getCanonicalName(), "method1Servlet", new String[]{"/foo/*", "*.foo"}); + WebAppContext wac = makeWebAppContext(Method1Servlet.class.getCanonicalName(), "method1Servlet", new String[]{ + "/foo/*", "*.foo" + }); //set up the expected outcomes: - a Constraint for the RolesAllowed on the class //with userdata constraint of DC_CONFIDENTIAL @@ -202,7 +212,7 @@ public class TestSecurityAnnotationConversions ServletSecurityAnnotationHandler annotationHandler = new ServletSecurityAnnotationHandler(wac); introspector.registerHandler(annotationHandler); introspector.introspect(Method1Servlet.class); - compareResults (expectedMappings, ((ConstraintAware)wac.getSecurityHandler()).getConstraintMappings()); + compareResults(expectedMappings, ((ConstraintAware)wac.getSecurityHandler()).getConstraintMappings()); } @Test @@ -210,7 +220,9 @@ public class TestSecurityAnnotationConversions { //A ServletSecurity annotation that has HttpConstraint of CONFIDENTIAL with defined roles, but a //HttpMethodConstraint for GET that permits all, but also requires CONFIDENTIAL - WebAppContext wac = makeWebAppContext(Method2Servlet.class.getCanonicalName(), "method2Servlet", new String[]{"/foo/*", "*.foo"}); + WebAppContext wac = makeWebAppContext(Method2Servlet.class.getCanonicalName(), "method2Servlet", new String[]{ + "/foo/*", "*.foo" + }); AnnotationIntrospector introspector = new AnnotationIntrospector(); ServletSecurityAnnotationHandler annotationHandler = new ServletSecurityAnnotationHandler(wac); @@ -249,25 +261,25 @@ public class TestSecurityAnnotationConversions expectedMappings[3].setMethod("GET"); introspector.introspect(Method2Servlet.class); - compareResults (expectedMappings, ((ConstraintAware)wac.getSecurityHandler()).getConstraintMappings()); + compareResults(expectedMappings, ((ConstraintAware)wac.getSecurityHandler()).getConstraintMappings()); } - private void compareResults (ConstraintMapping[] expectedMappings, List actualMappings) + private void compareResults(ConstraintMapping[] expectedMappings, List actualMappings) { assertNotNull(actualMappings); assertEquals(expectedMappings.length, actualMappings.size()); - for (int k=0; k < actualMappings.size(); k++) + for (int k = 0; k < actualMappings.size(); k++) { ConstraintMapping am = actualMappings.get(k); - boolean matched = false; + boolean matched = false; - for (int i=0; i< expectedMappings.length && !matched; i++) + for (int i = 0; i < expectedMappings.length && !matched; i++) { ConstraintMapping em = expectedMappings[i]; if (em.getPathSpec().equals(am.getPathSpec())) { - if ((em.getMethod()==null && am.getMethod() == null) || em.getMethod() != null && em.getMethod().equals(am.getMethod())) + if ((em.getMethod() == null && am.getMethod() == null) || em.getMethod() != null && em.getMethod().equals(am.getMethod())) { matched = true; @@ -295,12 +307,11 @@ public class TestSecurityAnnotationConversions } if (!matched) - fail("No expected ConstraintMapping matching method:"+am.getMethod()+" pathSpec: "+am.getPathSpec()); + fail("No expected ConstraintMapping matching method:" + am.getMethod() + " pathSpec: " + am.getPathSpec()); } } - - private WebAppContext makeWebAppContext (String className, String servletName, String[] paths) + private WebAppContext makeWebAppContext(String className, String servletName, String[] paths) { WebAppContext wac = new WebAppContext(); diff --git a/jetty-annotations/src/test/java/org/eclipse/jetty/annotations/TestServletAnnotations.java b/jetty-annotations/src/test/java/org/eclipse/jetty/annotations/TestServletAnnotations.java index 6d851888704..c8032f14b80 100644 --- a/jetty-annotations/src/test/java/org/eclipse/jetty/annotations/TestServletAnnotations.java +++ b/jetty-annotations/src/test/java/org/eclipse/jetty/annotations/TestServletAnnotations.java @@ -18,15 +18,6 @@ package org.eclipse.jetty.annotations; -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.anyOf; -import static org.hamcrest.Matchers.containsInAnyOrder; -import static org.hamcrest.Matchers.is; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertNotNull; -import static org.junit.jupiter.api.Assertions.assertTrue; -import static org.junit.jupiter.api.Assertions.fail; - import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; @@ -40,6 +31,15 @@ import org.eclipse.jetty.webapp.DiscoveredAnnotation; import org.eclipse.jetty.webapp.WebAppContext; import org.junit.jupiter.api.Test; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.anyOf; +import static org.hamcrest.Matchers.containsInAnyOrder; +import static org.hamcrest.Matchers.is; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.fail; + /** * TestServletAnnotations */ @@ -77,7 +77,6 @@ public class TestServletAnnotations parser.parse(Collections.singleton(handler), classes); - assertEquals(1, results.size()); assertTrue(results.get(0) instanceof WebServletAnnotation); @@ -103,9 +102,8 @@ public class TestServletAnnotations assertEquals(2, paths.length); } - @Test - public void testWebServletAnnotationOverrideDefault () throws Exception + public void testWebServletAnnotationOverrideDefault() throws Exception { //if the existing servlet mapping TO A DIFFERENT SERVLET IS from a default descriptor we //DO allow the annotation to replace the mapping. @@ -132,16 +130,14 @@ public class TestServletAnnotations assertEquals(1, resultMappings.length); assertEquals(2, resultMappings[0].getPathSpecs().length); resultMappings[0].getServletName().equals("DServlet"); - for (String s:resultMappings[0].getPathSpecs()) + for (String s : resultMappings[0].getPathSpecs()) { assertThat(s, anyOf(is("/"), is("/bah/*"))); } } - - @Test - public void testWebServletAnnotationReplaceDefault () throws Exception + public void testWebServletAnnotationReplaceDefault() throws Exception { //if the existing servlet mapping TO A DIFFERENT SERVLET IS from a default descriptor we //DO allow the annotation to replace the mapping. @@ -170,31 +166,29 @@ public class TestServletAnnotations ServletMapping[] resultMappings = wac.getServletHandler().getServletMappings(); assertNotNull(resultMappings); assertEquals(2, resultMappings.length); - for (ServletMapping r:resultMappings) + for (ServletMapping r : resultMappings) { - if (r.getServletName().equals("default")) - { - assertEquals(1,r.getPathSpecs().length); - assertEquals("/other", r.getPathSpecs()[0]); - } - else if (r.getServletName().equals("DServlet")) - { - assertEquals(2,r.getPathSpecs().length); - for (String p:r.getPathSpecs()) - { - if (!p.equals("/") && !p.equals("/bah/*")) - fail("Unexpected path"); - } - } - else - fail("Unexpected servlet mapping: " + r); + if (r.getServletName().equals("default")) + { + assertEquals(1, r.getPathSpecs().length); + assertEquals("/other", r.getPathSpecs()[0]); + } + else if (r.getServletName().equals("DServlet")) + { + assertEquals(2, r.getPathSpecs().length); + for (String p : r.getPathSpecs()) + { + if (!p.equals("/") && !p.equals("/bah/*")) + fail("Unexpected path"); + } + } + else + fail("Unexpected servlet mapping: " + r); } - } - @Test - public void testWebServletAnnotationNotOverride () throws Exception + public void testWebServletAnnotationNotOverride() throws Exception { //if the existing servlet mapping TO A DIFFERENT SERVLET IS NOT from a default descriptor we //DO NOT allow the annotation to replace the mapping @@ -213,7 +207,7 @@ public class TestServletAnnotations ServletMapping[] resultMappings = wac.getServletHandler().getServletMappings(); assertEquals(2, resultMappings.length); - for (ServletMapping r:resultMappings) + for (ServletMapping r : resultMappings) { if (r.getServletName().equals("DServlet")) { @@ -229,7 +223,7 @@ public class TestServletAnnotations } @Test - public void testWebServletAnnotationIgnore () throws Exception + public void testWebServletAnnotationIgnore() throws Exception { //an existing servlet OF THE SAME NAME has even 1 non-default mapping we can't use //any of the url mappings in the annotation @@ -256,17 +250,16 @@ public class TestServletAnnotations ServletMapping[] resultMappings = wac.getServletHandler().getServletMappings(); assertEquals(2, resultMappings.length); - for (ServletMapping r:resultMappings) + for (ServletMapping r : resultMappings) { assertEquals(1, r.getPathSpecs().length); if (!r.getPathSpecs()[0].equals("/default") && !r.getPathSpecs()[0].equals("/other")) fail("Unexpected path in mapping: " + r); } - } @Test - public void testWebServletAnnotationNoMappings () throws Exception + public void testWebServletAnnotationNoMappings() throws Exception { //an existing servlet OF THE SAME NAME has no mappings, therefore all mappings in the annotation //should be accepted @@ -275,24 +268,21 @@ public class TestServletAnnotations servlet.setName("foo"); wac.getServletHandler().addServlet(servlet); - WebServletAnnotation annotation = new WebServletAnnotation(wac, "org.eclipse.jetty.annotations.ServletD", null); annotation.apply(); ServletMapping[] resultMappings = wac.getServletHandler().getServletMappings(); assertEquals(1, resultMappings.length); assertEquals(2, resultMappings[0].getPathSpecs().length); - for (String s:resultMappings[0].getPathSpecs()) + for (String s : resultMappings[0].getPathSpecs()) { assertThat(s, anyOf(is("/"), is("/bah/*"))); } } - - @Test - public void testDeclareRoles () - throws Exception + public void testDeclareRoles() + throws Exception { WebAppContext wac = new WebAppContext(); ConstraintSecurityHandler sh = new ConstraintSecurityHandler(); diff --git a/jetty-annotations/src/test/java/org/eclipse/jetty/annotations/resources/ResourceA.java b/jetty-annotations/src/test/java/org/eclipse/jetty/annotations/resources/ResourceA.java index 26e44909f86..e5b91f72ce8 100644 --- a/jetty-annotations/src/test/java/org/eclipse/jetty/annotations/resources/ResourceA.java +++ b/jetty-annotations/src/test/java/org/eclipse/jetty/annotations/resources/ResourceA.java @@ -19,7 +19,6 @@ package org.eclipse.jetty.annotations.resources; import java.io.IOException; - import javax.annotation.Resource; import javax.servlet.ServletConfig; import javax.servlet.ServletException; @@ -28,8 +27,6 @@ import javax.servlet.ServletResponse; /** * ResourceA - * - * */ public class ResourceA implements javax.servlet.Servlet { @@ -37,25 +34,24 @@ public class ResourceA implements javax.servlet.Servlet private Integer h; private Integer k; - - @Resource(name="myf", mappedName="resB") //test giving both a name and mapped name from the environment + @Resource(name = "myf", mappedName = "resB") //test giving both a name and mapped name from the environment private Integer f;//test a non inherited field that needs injection - @Resource(mappedName="resA") //test the default naming scheme but using a mapped name from the environment + @Resource(mappedName = "resA") //test the default naming scheme but using a mapped name from the environment private Integer g; - @Resource(name="resA") //test using the given name as the name from the environment + @Resource(name = "resA") //test using the given name as the name from the environment private Integer j; - @Resource(mappedName="resB") //test using the default name on an inherited field + @Resource(mappedName = "resB") //test using the default name on an inherited field protected Integer n; //TODO - if it's inherited, is it supposed to use the classname of the class it is inherited by? - - @Resource(name="mye", mappedName="resA", type=Integer.class) + @Resource(name = "mye", mappedName = "resA", type = Integer.class) public void setE(Integer e) { - this.e=e; + this.e = e; } + public Integer getE() { return this.e; @@ -76,42 +72,48 @@ public class ResourceA implements javax.servlet.Servlet return this.j; } - @Resource(mappedName="resA") + @Resource(mappedName = "resA") public void setH(Integer h) { - this.h=h; + this.h = h; } - @Resource(name="resA") + @Resource(name = "resA") public void setK(Integer k) { - this.k=k; + this.k = k; } + public void x() { System.err.println("ResourceA.x"); } + @Override public void destroy() { } + @Override public ServletConfig getServletConfig() { return null; } + @Override public String getServletInfo() { return null; } + @Override public void init(ServletConfig arg0) throws ServletException { } + @Override public void service(ServletRequest arg0, ServletResponse arg1) - throws ServletException, IOException + throws ServletException, IOException { } } diff --git a/jetty-annotations/src/test/java/org/eclipse/jetty/annotations/resources/ResourceB.java b/jetty-annotations/src/test/java/org/eclipse/jetty/annotations/resources/ResourceB.java index 4dbdefee5ca..d8fc21ff2e9 100644 --- a/jetty-annotations/src/test/java/org/eclipse/jetty/annotations/resources/ResourceB.java +++ b/jetty-annotations/src/test/java/org/eclipse/jetty/annotations/resources/ResourceB.java @@ -17,26 +17,25 @@ // package org.eclipse.jetty.annotations.resources; + import javax.annotation.Resource; import javax.annotation.Resources; /** * ResourceB - * - * */ @Resources({ - @Resource(name="peach", mappedName="resA"), - @Resource(name="pear", mappedName="resB") + @Resource(name = "peach", mappedName = "resA"), + @Resource(name = "pear", mappedName = "resB") }) public class ResourceB extends ResourceA { - @Resource(mappedName="resB") + @Resource(mappedName = "resB") private Integer f;//test no inheritance of private fields - + @Resource private Integer p = 8; //test no injection because no value - + //test no annotation public void z() { diff --git a/jetty-annotations/src/test/java/org/eclipse/jetty/annotations/resources/TestResourceAnnotations.java b/jetty-annotations/src/test/java/org/eclipse/jetty/annotations/resources/TestResourceAnnotations.java index e832b2a6227..1ea4ab22824 100644 --- a/jetty-annotations/src/test/java/org/eclipse/jetty/annotations/resources/TestResourceAnnotations.java +++ b/jetty-annotations/src/test/java/org/eclipse/jetty/annotations/resources/TestResourceAnnotations.java @@ -18,12 +18,8 @@ package org.eclipse.jetty.annotations.resources; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertNotNull; - import java.lang.reflect.Field; import java.util.List; - import javax.naming.Context; import javax.naming.InitialContext; @@ -38,6 +34,9 @@ import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; + public class TestResourceAnnotations { private Server server; @@ -68,8 +67,8 @@ public class TestResourceAnnotations } @Test - public void testResourceAnnotations () - throws Exception + public void testResourceAnnotations() + throws Exception { new org.eclipse.jetty.plus.jndi.EnvEntry(server, "resA", objA, false); new org.eclipse.jetty.plus.jndi.EnvEntry(server, "resB", objB, false); @@ -106,7 +105,7 @@ public class TestResourceAnnotations //only 1 field injection because the other has no Resource mapping assertEquals(1, resBInjections.size()); Injection fi = resBInjections.get(0); - assertEquals ("f", fi.getTarget().getName()); + assertEquals("f", fi.getTarget().getName()); //3 method injections on class ResourceA, 4 field injections List resAInjections = injections.getInjections(ResourceA.class.getCanonicalName()); @@ -129,9 +128,9 @@ public class TestResourceAnnotations injections.inject(binst); //check injected values - Field f = ResourceB.class.getDeclaredField ("f"); + Field f = ResourceB.class.getDeclaredField("f"); f.setAccessible(true); - assertEquals(objB , f.get(binst)); + assertEquals(objB, f.get(binst)); //@Resource(mappedName="resA") //test the default naming scheme but using a mapped name from the environment f = ResourceA.class.getDeclaredField("g"); @@ -150,8 +149,8 @@ public class TestResourceAnnotations } @Test - public void testResourcesAnnotation () - throws Exception + public void testResourcesAnnotation() + throws Exception { new org.eclipse.jetty.plus.jndi.EnvEntry(server, "resA", objA, false); new org.eclipse.jetty.plus.jndi.EnvEntry(server, "resB", objB, false); diff --git a/jetty-ant/pom.xml b/jetty-ant/pom.xml index 3c2dcf9b050..b66fb07eaeb 100644 --- a/jetty-ant/pom.xml +++ b/jetty-ant/pom.xml @@ -8,7 +8,7 @@ jetty-ant jar Jetty :: Ant Plugin - + ${project.groupId}.ant diff --git a/jetty-ant/src/main/java/org/eclipse/jetty/ant/AntMetaInfConfiguration.java b/jetty-ant/src/main/java/org/eclipse/jetty/ant/AntMetaInfConfiguration.java index 0010cfa55f7..0a45505d434 100644 --- a/jetty-ant/src/main/java/org/eclipse/jetty/ant/AntMetaInfConfiguration.java +++ b/jetty-ant/src/main/java/org/eclipse/jetty/ant/AntMetaInfConfiguration.java @@ -25,17 +25,11 @@ import java.net.URL; import java.net.URLClassLoader; import java.util.ArrayList; import java.util.List; -import java.util.regex.Pattern; import org.apache.tools.ant.AntClassLoader; -import org.eclipse.jetty.util.PatternMatcher; -import org.eclipse.jetty.util.resource.Resource; import org.eclipse.jetty.webapp.Configuration; import org.eclipse.jetty.webapp.MetaInfConfiguration; -import org.eclipse.jetty.webapp.WebAppClassLoader; import org.eclipse.jetty.webapp.WebAppContext; -import org.eclipse.jetty.webapp.WebInfConfiguration; -import org.eclipse.jetty.webapp.WebXmlConfiguration; public class AntMetaInfConfiguration extends MetaInfConfiguration { @@ -45,8 +39,6 @@ public class AntMetaInfConfiguration extends MetaInfConfiguration { return MetaInfConfiguration.class; } - - @Override public void findAndFilterContainerPaths(WebAppContext context) throws Exception @@ -55,11 +47,8 @@ public class AntMetaInfConfiguration extends MetaInfConfiguration super.findAndFilterContainerPaths(context); } - - - /* ------------------------------------------------------------------------------- */ @Override - protected List getAllContainerJars(final WebAppContext context) throws URISyntaxException + protected List getAllContainerJars(final WebAppContext context) throws URISyntaxException { List uris = new ArrayList<>(); if (context.getClassLoader() != null) @@ -71,16 +60,18 @@ public class AntMetaInfConfiguration extends MetaInfConfiguration { URL[] urls = ((URLClassLoader)loader).getURLs(); if (urls != null) - for(URL url:urls) - uris.add(new URI(url.toString().replaceAll(" ","%20"))); + for (URL url : urls) + { + uris.add(new URI(url.toString().replaceAll(" ", "%20"))); + } } else if (loader instanceof AntClassLoader) { - AntClassLoader antLoader = (AntClassLoader)loader; + AntClassLoader antLoader = (AntClassLoader)loader; String[] paths = antLoader.getClasspath().split(new String(new char[]{File.pathSeparatorChar})); if (paths != null) { - for (String p:paths) + for (String p : paths) { File f = new File(p); uris.add(f.toURI()); diff --git a/jetty-ant/src/main/java/org/eclipse/jetty/ant/AntWebAppContext.java b/jetty-ant/src/main/java/org/eclipse/jetty/ant/AntWebAppContext.java index 34e740e6eac..911f6cd2f69 100644 --- a/jetty-ant/src/main/java/org/eclipse/jetty/ant/AntWebAppContext.java +++ b/jetty-ant/src/main/java/org/eclipse/jetty/ant/AntWebAppContext.java @@ -65,36 +65,45 @@ import org.eclipse.jetty.xml.XmlConfiguration; public class AntWebAppContext extends WebAppContext { private static final Logger LOG = Log.getLogger(WebAppContext.class); - - public final static String DEFAULT_CONTAINER_INCLUDE_JAR_PATTERN = - ".*/.*jsp-api-[^/]*\\.jar$|.*/.*jsp-[^/]*\\.jar$|.*/.*taglibs[^/]*\\.jar$|.*/.*jstl[^/]*\\.jar$|.*/.*jsf-impl-[^/]*\\.jar$|.*/.*javax.faces-[^/]*\\.jar$|.*/.*myfaces-impl-[^/]*\\.jar$"; + public static final String DEFAULT_CONTAINER_INCLUDE_JAR_PATTERN = + ".*/.*jsp-api-[^/]*\\.jar$|.*/.*jsp-[^/]*\\.jar$|.*/.*taglibs[^/]*\\.jar$|.*/.*jstl[^/]*\\.jar$|.*/.*jsf-impl-[^/]*\\.jar$|.*/.*javax.faces-[^/]*\\.jar$|.*/.*myfaces-impl-[^/]*\\.jar$"; - /** Location of jetty-env.xml file. */ + /** + * Location of jetty-env.xml file. + */ private File jettyEnvXml; - - /** List of web application libraries. */ + + /** + * List of web application libraries. + */ private List libraries = new ArrayList<>(); - /** List of web application class directories. */ + /** + * List of web application class directories. + */ private List classes = new ArrayList<>(); - - /** context xml file to apply to the webapp */ + + /** + * context xml file to apply to the webapp + */ private File contextXml; - - /** List of extra scan targets for this web application. */ + + /** + * List of extra scan targets for this web application. + */ private FileSet scanTargets; - - /** context attributes to set **/ + + /** + * context attributes to set + **/ private Attributes attributes; - + private Project project; - + private List scanFiles; - private FileMatchingConfiguration librariesConfiguration; - public static void dump(ClassLoader loader) { @@ -106,15 +115,16 @@ public class AntWebAppContext extends WebAppContext URL[] urls = ((URLClassLoader)loader).getURLs(); if (urls != null) { - for (URL u:urls) - System.err.println("\t"+u+"\n"); + for (URL u : urls) + { + System.err.println("\t" + u + "\n"); + } } } loader = loader.getParent(); } } - /** * AntURLClassLoader * @@ -124,11 +134,11 @@ public class AntWebAppContext extends WebAppContext public static class AntURLClassLoader extends URLClassLoader { private AntClassLoader antLoader; - + public AntURLClassLoader(AntClassLoader antLoader) { - super(new URL[] {}, antLoader); - this.antLoader = antLoader; + super(new URL[]{}, antLoader); + this.antLoader = antLoader; } @Override @@ -153,17 +163,17 @@ public class AntWebAppContext extends WebAppContext public URL[] getURLs() { Set urls = new HashSet(); - + //convert urls from antLoader String[] paths = antLoader.getClasspath().split(new String(new char[]{File.pathSeparatorChar})); if (paths != null) { - for (String p:paths) + for (String p : paths) { File f = new File(p); try { - urls.add(f.toURI().toURL()); + urls.add(f.toURI().toURL()); } catch (Exception e) { @@ -171,15 +181,17 @@ public class AntWebAppContext extends WebAppContext } } } - + //add in any that may have been added to us as a URL directly URL[] ourURLS = super.getURLs(); if (ourURLS != null) { - for (URL u:ourURLS) + for (URL u : ourURLS) + { urls.add(u); + } } - + return urls.toArray(new URL[urls.size()]); } @@ -286,12 +298,9 @@ public class AntWebAppContext extends WebAppContext super.clearAssertionStatus(); } } - - + /** * AntServletHolder - * - * */ public static class AntServletHolder extends ServletHolder { @@ -301,33 +310,29 @@ public class AntWebAppContext extends WebAppContext super(); } - public AntServletHolder(Class servlet) { super(servlet); } - public AntServletHolder(Servlet servlet) { super(servlet); } - public AntServletHolder(String name, Class servlet) { super(name, servlet); } - public AntServletHolder(String name, Servlet servlet) { super(name, servlet); } - protected String getSystemClassPath (ClassLoader loader) throws Exception + protected String getSystemClassPath(ClassLoader loader) throws Exception { - StringBuilder classpath=new StringBuilder(); + StringBuilder classpath = new StringBuilder(); while (loader != null) { if (loader instanceof URLClassLoader) @@ -335,13 +340,13 @@ public class AntWebAppContext extends WebAppContext URL[] urls = ((URLClassLoader)loader).getURLs(); if (urls != null) { - for (int i=0;i0) + if (classpath.length() > 0) classpath.append(File.pathSeparatorChar); classpath.append(file.getAbsolutePath()); } @@ -358,15 +363,10 @@ public class AntWebAppContext extends WebAppContext return classpath.toString(); } - } - - /** * AntServletHandler - * - * */ public static class AntServletHandler extends ServletHandler { @@ -376,11 +376,8 @@ public class AntWebAppContext extends WebAppContext { return new AntServletHolder(); } - } - - /** * Default constructor. Takes project as an argument * @@ -393,12 +390,12 @@ public class AntWebAppContext extends WebAppContext this.project = project; setAttribute(MetaInfConfiguration.CONTAINER_JAR_PATTERN, DEFAULT_CONTAINER_INCLUDE_JAR_PATTERN); setParentLoaderPriority(true); - addConfiguration(new AntWebInfConfiguration(),new AntWebXmlConfiguration(),new AntMetaInfConfiguration()); + addConfiguration(new AntWebInfConfiguration(), new AntWebXmlConfiguration(), new AntMetaInfConfiguration()); } - /** * Adds a new Ant's attributes tag object if it have not been created yet. + * * @param atts the attributes */ public void addAttributes(Attributes atts) @@ -411,19 +408,15 @@ public class AntWebAppContext extends WebAppContext this.attributes = atts; } - public void addLib(FileSet lib) { libraries.add(lib); } - public void addClasses(FileSet classes) { this.classes.add(classes); } - - @Override protected ServletHandler newServletHandler() @@ -431,27 +424,22 @@ public class AntWebAppContext extends WebAppContext return new AntServletHandler(); } - public void setJettyEnvXml(File jettyEnvXml) { this.jettyEnvXml = jettyEnvXml; TaskLog.log("jetty-env.xml file: = " + (jettyEnvXml == null ? null : jettyEnvXml.getAbsolutePath())); } - public File getJettyEnvXml () + public File getJettyEnvXml() { return this.jettyEnvXml; } - - - public List getLibraries() { return librariesConfiguration.getBaseDirectories(); } - public void addScanTargets(FileSet scanTargets) { if (this.scanTargets != null) @@ -461,39 +449,36 @@ public class AntWebAppContext extends WebAppContext this.scanTargets = scanTargets; } - - public List getScanTargetFiles () + + public List getScanTargetFiles() { if (this.scanTargets == null) return null; - - + FileMatchingConfiguration configuration = new FileMatchingConfiguration(); configuration.addDirectoryScanner(scanTargets.getDirectoryScanner(project)); return configuration.getBaseDirectories(); } - + public List getScanFiles() { if (scanFiles == null) scanFiles = initScanFiles(); return scanFiles; } - - - public boolean isScanned (File file) + + public boolean isScanned(File file) { - List files = getScanFiles(); - if (files == null || files.isEmpty()) - return false; - return files.contains(file); + List files = getScanFiles(); + if (files == null || files.isEmpty()) + return false; + return files.contains(file); } - - - public List initScanFiles () + + public List initScanFiles() { List scanList = new ArrayList(); - + if (getDescriptor() != null) { try (Resource r = Resource.newResource(getDescriptor());) @@ -523,7 +508,7 @@ public class AntWebAppContext extends WebAppContext try (Resource r = Resource.newResource(getDefaultsDescriptor());) { if (!WebAppContext.WEB_DEFAULTS_XML.equals(getDefaultsDescriptor())) - { + { scanList.add(r.getFile()); } } @@ -550,17 +535,15 @@ public class AntWebAppContext extends WebAppContext List cpFiles = getClassPathFiles(); if (cpFiles != null) scanList.addAll(cpFiles); - + //any extra scan targets List scanFiles = (List)getScanTargetFiles(); if (scanFiles != null) scanList.addAll(scanFiles); - + return scanList; } - - - + @Override public void setWar(String path) { @@ -581,20 +564,19 @@ public class AntWebAppContext extends WebAppContext } } - /** - * + * */ @Override public void doStart() { try { - TaskLog.logWithTimestamp("Starting web application "+this.getDescriptor()); - + TaskLog.logWithTimestamp("Starting web application " + this.getDescriptor()); + if (jettyEnvXml != null && jettyEnvXml.exists()) getConfiguration(EnvConfiguration.class).setJettyEnvResource(new PathResource(jettyEnvXml)); - + ClassLoader parentLoader = this.getClass().getClassLoader(); if (parentLoader instanceof AntClassLoader) parentLoader = new AntURLClassLoader((AntClassLoader)parentLoader); @@ -602,18 +584,20 @@ public class AntWebAppContext extends WebAppContext setClassLoader(new WebAppClassLoader(parentLoader, this)); if (attributes != null && attributes.getAttributes() != null) { - for (Attribute a:attributes.getAttributes()) + for (Attribute a : attributes.getAttributes()) + { setAttribute(a.getName(), a.getValue()); + } } - + //apply a context xml file if one was supplied if (contextXml != null) { XmlConfiguration xmlConfiguration = new XmlConfiguration(new PathResource(contextXml)); - TaskLog.log("Applying context xml file "+contextXml); - xmlConfiguration.configure(this); + TaskLog.log("Applying context xml file " + contextXml); + xmlConfiguration.configure(this); } - + super.doStart(); } catch (Exception e) @@ -628,7 +612,7 @@ public class AntWebAppContext extends WebAppContext try { scanFiles = null; - TaskLog.logWithTimestamp("Stopping web application "+this); + TaskLog.logWithTimestamp("Stopping web application " + this); Thread.currentThread().sleep(500L); super.doStop(); //remove all filters, servlets and listeners. They will be recreated @@ -649,8 +633,6 @@ public class AntWebAppContext extends WebAppContext } } - - /** * @return a list of classpath files (libraries and class directories). */ @@ -677,15 +659,13 @@ public class AntWebAppContext extends WebAppContext } } - return classPathFiles; } - /** * @return a FileMatchingConfiguration object describing the - * configuration of all libraries added to this particular web app - * (both classes and libraries). + * configuration of all libraries added to this particular web app + * (both classes and libraries). */ public FileMatchingConfiguration getLibrariesConfiguration() { @@ -708,16 +688,13 @@ public class AntWebAppContext extends WebAppContext return config; } - public File getContextXml() { return contextXml; } - public void setContextXml(File contextXml) { this.contextXml = contextXml; } - } diff --git a/jetty-ant/src/main/java/org/eclipse/jetty/ant/AntWebInfConfiguration.java b/jetty-ant/src/main/java/org/eclipse/jetty/ant/AntWebInfConfiguration.java index 890a119e3e6..c1c224d3a95 100644 --- a/jetty-ant/src/main/java/org/eclipse/jetty/ant/AntWebInfConfiguration.java +++ b/jetty-ant/src/main/java/org/eclipse/jetty/ant/AntWebInfConfiguration.java @@ -50,11 +50,11 @@ public class AntWebInfConfiguration extends WebInfConfiguration List classPathFiles = ((AntWebAppContext)context).getClassPathFiles(); if (classPathFiles != null) { - for (File cpFile:classPathFiles) + for (File cpFile : classPathFiles) { if (cpFile.exists()) { - ((WebAppClassLoader) context.getClassLoader()).addClassPath(cpFile.getCanonicalPath()); + ((WebAppClassLoader)context.getClassLoader()).addClassPath(cpFile.getCanonicalPath()); } } } diff --git a/jetty-ant/src/main/java/org/eclipse/jetty/ant/AntWebXmlConfiguration.java b/jetty-ant/src/main/java/org/eclipse/jetty/ant/AntWebXmlConfiguration.java index d553957e64b..a097c78282d 100644 --- a/jetty-ant/src/main/java/org/eclipse/jetty/ant/AntWebXmlConfiguration.java +++ b/jetty-ant/src/main/java/org/eclipse/jetty/ant/AntWebXmlConfiguration.java @@ -24,10 +24,8 @@ import java.util.List; import org.eclipse.jetty.util.log.Log; import org.eclipse.jetty.util.log.Logger; import org.eclipse.jetty.webapp.Configuration; -import org.eclipse.jetty.webapp.WebInfConfiguration; import org.eclipse.jetty.webapp.WebXmlConfiguration; - /** * This configuration object provides additional way to inject application * properties into the configured web application. The list of classpath files, @@ -38,13 +36,16 @@ public class AntWebXmlConfiguration extends WebXmlConfiguration { private static final Logger LOG = Log.getLogger(WebXmlConfiguration.class); - /** List of classpath files. */ + /** + * List of classpath files. + */ private List classPathFiles; - /** Web application root directory. */ + /** + * Web application root directory. + */ private File webAppBaseDir; - public AntWebXmlConfiguration() { super(); @@ -55,7 +56,7 @@ public class AntWebXmlConfiguration extends WebXmlConfiguration { return WebXmlConfiguration.class; } - + public void setClassPathFiles(List classPathFiles) { this.classPathFiles = classPathFiles; @@ -65,7 +66,4 @@ public class AntWebXmlConfiguration extends WebXmlConfiguration { this.webAppBaseDir = webAppBaseDir; } - - - } diff --git a/jetty-ant/src/main/java/org/eclipse/jetty/ant/JettyRunTask.java b/jetty-ant/src/main/java/org/eclipse/jetty/ant/JettyRunTask.java index 5da5e947f50..6b7355f5b0b 100644 --- a/jetty-ant/src/main/java/org/eclipse/jetty/ant/JettyRunTask.java +++ b/jetty-ant/src/main/java/org/eclipse/jetty/ant/JettyRunTask.java @@ -41,42 +41,59 @@ import org.eclipse.jetty.webapp.WebAppContext; */ public class JettyRunTask extends Task { - private int scanIntervalSeconds; - - /** Temporary files directory. */ + private int scanIntervalSeconds; + + /** + * Temporary files directory. + */ private File tempDirectory; - /** List of web applications to be deployed. */ + /** + * List of web applications to be deployed. + */ private List webapps = new ArrayList<>(); - /** Location of jetty.xml file. */ + /** + * Location of jetty.xml file. + */ private File jettyXml; - /** List of server connectors. */ + /** + * List of server connectors. + */ private Connectors connectors = null; - /** Server request logger object. */ + /** + * Server request logger object. + */ private RequestLog requestLog; - /** List of login services. */ + /** + * List of login services. + */ private LoginServices loginServices; - /** List of system properties to be set. */ + /** + * List of system properties to be set. + */ private SystemProperties systemProperties; - - /** List of other contexts to deploy */ + + /** + * List of other contexts to deploy + */ private ContextHandlers contextHandlers; - - /** Port Jetty will use for the default connector */ + /** + * Port Jetty will use for the default connector + */ private int jettyPort = 8080; - + private int stopPort; - + private String stopKey; private boolean daemon; - + public JettyRunTask() { TaskLog.setTask(this); @@ -84,16 +101,18 @@ public class JettyRunTask extends Task /** * Creates a new WebApp Ant object. - * @param webapp the webapp context + * + * @param webapp the webapp context */ public void addWebApp(AntWebAppContext webapp) { - webapps.add(webapp); + webapps.add(webapp); } /** * Adds a new Ant's connector tag object if it have not been created yet. - * @param connectors the connectors + * + * @param connectors the connectors */ public void addConnectors(Connectors connectors) { @@ -103,10 +122,10 @@ public class JettyRunTask extends Task } public void addLoginServices(LoginServices services) - { - if (this.loginServices != null ) - throw new BuildException("Only one tag is allowed!"); - this.loginServices = services; + { + if (this.loginServices != null) + throw new BuildException("Only one tag is allowed!"); + this.loginServices = services; } public void addSystemProperties(SystemProperties systemProperties) @@ -115,8 +134,8 @@ public class JettyRunTask extends Task throw new BuildException("Only one tag is allowed!"); this.systemProperties = systemProperties; } - - public void addContextHandlers (ContextHandlers handlers) + + public void addContextHandlers(ContextHandlers handlers) { if (this.contextHandlers != null) throw new BuildException("Only one tag is allowed!"); @@ -147,7 +166,7 @@ public class JettyRunTask extends Task { try { - this.requestLog = (RequestLog) Class.forName(className).getDeclaredConstructor().newInstance(); + this.requestLog = (RequestLog)Class.forName(className).getDeclaredConstructor().newInstance(); } catch (ClassNotFoundException e) { @@ -157,7 +176,6 @@ public class JettyRunTask extends Task { throw new BuildException("Request logger instantiation exception: " + e); } - } public String getRequestLog() @@ -172,7 +190,7 @@ public class JettyRunTask extends Task /** * Sets the port Jetty uses for the default connector. - * + * * @param jettyPort The port Jetty will use for the default connector */ public void setJettyPort(final int jettyPort) @@ -191,7 +209,7 @@ public class JettyRunTask extends Task { TaskLog.log("Configuring Jetty for project: " + getProject().getName()); - + setSystemProperties(); List connectorsList = null; @@ -199,9 +217,9 @@ public class JettyRunTask extends Task if (connectors != null) connectorsList = connectors.getConnectors(); else - connectorsList = new Connectors(jettyPort,30000).getDefaultConnectors(); + connectorsList = new Connectors(jettyPort, 30000).getDefaultConnectors(); - List loginServicesList = (loginServices != null?loginServices.getLoginServices():new ArrayList()); + List loginServicesList = (loginServices != null ? loginServices.getLoginServices() : new ArrayList()); ServerProxyImpl server = new ServerProxyImpl(); server.setConnectors(connectorsList); server.setLoginServices(loginServicesList); @@ -216,7 +234,7 @@ public class JettyRunTask extends Task try { - for (WebAppContext webapp: webapps) + for (WebAppContext webapp : webapps) { server.addWebApplication((AntWebAppContext)webapp); } @@ -237,7 +255,7 @@ public class JettyRunTask extends Task public void setStopPort(int stopPort) { this.stopPort = stopPort; - TaskLog.log("stopPort="+stopPort); + TaskLog.log("stopPort=" + stopPort); } public String getStopKey() @@ -248,7 +266,7 @@ public class JettyRunTask extends Task public void setStopKey(String stopKey) { this.stopKey = stopKey; - TaskLog.log("stopKey="+stopKey); + TaskLog.log("stopKey=" + stopKey); } /** @@ -265,7 +283,7 @@ public class JettyRunTask extends Task public void setDaemon(boolean daemon) { this.daemon = daemon; - TaskLog.log("Daemon="+daemon); + TaskLog.log("Daemon=" + daemon); } public int getScanIntervalSeconds() @@ -276,9 +294,9 @@ public class JettyRunTask extends Task public void setScanIntervalSeconds(int secs) { scanIntervalSeconds = secs; - TaskLog.log("scanIntervalSecs="+secs); + TaskLog.log("scanIntervalSecs=" + secs); } - + /** * Sets the system properties. */ @@ -289,10 +307,9 @@ public class JettyRunTask extends Task Iterator propertiesIterator = systemProperties.getSystemProperties().iterator(); while (propertiesIterator.hasNext()) { - Property property = ((Property) propertiesIterator.next()); + Property property = ((Property)propertiesIterator.next()); SystemProperties.setIfNotSetAlready(property); } } } - } diff --git a/jetty-ant/src/main/java/org/eclipse/jetty/ant/JettyStopTask.java b/jetty-ant/src/main/java/org/eclipse/jetty/ant/JettyStopTask.java index fd30fd9339e..9478bf8c9a8 100644 --- a/jetty-ant/src/main/java/org/eclipse/jetty/ant/JettyStopTask.java +++ b/jetty-ant/src/main/java/org/eclipse/jetty/ant/JettyStopTask.java @@ -31,39 +31,35 @@ import org.eclipse.jetty.ant.utils.TaskLog; /** * JettyStopTask - * - * */ public class JettyStopTask extends Task { private int stopPort; - + private String stopKey; - + private int stopWait; - - - + /** - * + * */ public JettyStopTask() { TaskLog.setTask(this); } - /** + /** * @see org.apache.tools.ant.Task#execute() */ @Override public void execute() throws BuildException { try - { - Socket s = new Socket(InetAddress.getByName("127.0.0.1"),stopPort); + { + Socket s = new Socket(InetAddress.getByName("127.0.0.1"), stopPort); if (stopWait > 0) - s.setSoTimeout(stopWait*1000); + s.setSoTimeout(stopWait * 1000); try { OutputStream out = s.getOutputStream(); @@ -72,9 +68,9 @@ public class JettyStopTask extends Task if (stopWait > 0) { - TaskLog.log("Waiting"+(stopWait > 0 ? (" "+stopWait+"sec") : "")+" for jetty to stop"); + TaskLog.log("Waiting" + (stopWait > 0 ? (" " + stopWait + "sec") : "") + " for jetty to stop"); LineNumberReader lin = new LineNumberReader(new InputStreamReader(s.getInputStream())); - String response=lin.readLine(); + String response = lin.readLine(); if ("Stopped".equals(response)) System.err.println("Stopped"); } @@ -82,7 +78,7 @@ public class JettyStopTask extends Task finally { s.close(); - } + } } catch (ConnectException e) { @@ -94,22 +90,22 @@ public class JettyStopTask extends Task } } - public int getStopPort() + public int getStopPort() { return stopPort; } - public void setStopPort(int stopPort) + public void setStopPort(int stopPort) { this.stopPort = stopPort; } - public String getStopKey() + public String getStopKey() { return stopKey; } - public void setStopKey(String stopKey) + public void setStopKey(String stopKey) { this.stopKey = stopKey; } @@ -123,6 +119,4 @@ public class JettyStopTask extends Task { this.stopWait = stopWait; } - - } diff --git a/jetty-ant/src/main/java/org/eclipse/jetty/ant/ServerProxyImpl.java b/jetty-ant/src/main/java/org/eclipse/jetty/ant/ServerProxyImpl.java index 9cc5b05c36c..30ca0d9adb4 100644 --- a/jetty-ant/src/main/java/org/eclipse/jetty/ant/ServerProxyImpl.java +++ b/jetty-ant/src/main/java/org/eclipse/jetty/ant/ServerProxyImpl.java @@ -16,7 +16,6 @@ // ======================================================================== // - package org.eclipse.jetty.ant; import java.io.File; @@ -46,8 +45,6 @@ import org.eclipse.jetty.util.resource.Resource; import org.eclipse.jetty.xml.XmlConfiguration; import org.xml.sax.SAXException; - - /** * A proxy class for interaction with Jetty server object. Used to have some * level of abstraction over standard Jetty classes. @@ -55,62 +52,84 @@ import org.xml.sax.SAXException; public class ServerProxyImpl implements ServerProxy { - /** Proxied Jetty server object. */ + /** + * Proxied Jetty server object. + */ private Server server; - - /** Temporary files directory. */ + + /** + * Temporary files directory. + */ private File tempDirectory; - - /** Collection of context handlers (web application contexts). */ + + /** + * Collection of context handlers (web application contexts). + */ private ContextHandlerCollection contexts; - /** Location of jetty.xml file. */ + /** + * Location of jetty.xml file. + */ private File jettyXml; - /** List of connectors. */ + /** + * List of connectors. + */ private List connectors; - /** Request logger. */ + /** + * Request logger. + */ private RequestLog requestLog; - /** User realms. */ + /** + * User realms. + */ private List loginServices; - /** List of added web applications. */ + /** + * List of added web applications. + */ private List webApplications = new ArrayList(); - /** other contexts to deploy */ + /** + * other contexts to deploy + */ private ContextHandlers contextHandlers; - /** scan interval for changed files */ + /** + * scan interval for changed files + */ private int scanIntervalSecs; - /** port to listen for stop command */ + /** + * port to listen for stop command + */ private int stopPort; - /** security key for stop command */ + /** + * security key for stop command + */ private String stopKey; - /** wait for all jetty threads to exit or continue */ + /** + * wait for all jetty threads to exit or continue + */ private boolean daemon; - private boolean configured = false; - - /** * WebAppScannerListener * * Handle notifications that files we are interested in have changed * during execution. - * */ public static class WebAppScannerListener implements Scanner.BulkListener - { + { AntWebAppContext awc; - public WebAppScannerListener (AntWebAppContext awc) + public WebAppScannerListener(AntWebAppContext awc) { this.awc = awc; } @@ -137,25 +156,22 @@ public class ServerProxyImpl implements ServerProxy TaskLog.log(e.getMessage()); } } - } - /** * Default constructor. Creates a new Jetty server with a standard connector * listening on a given port. */ - public ServerProxyImpl () + public ServerProxyImpl() { server = new Server(); server.setStopAtShutdown(true); } - @Override public void addWebApplication(AntWebAppContext webApp) { - webApplications.add(webApp); + webApplications.add(webApp); } public int getStopPort() @@ -228,19 +244,16 @@ public class ServerProxyImpl implements ServerProxy this.webApplications = webApplications; } - public File getTempDirectory() { return tempDirectory; } - public void setTempDirectory(File tempDirectory) { this.tempDirectory = tempDirectory; } - /** * @see org.eclipse.jetty.ant.utils.ServerProxy#start() */ @@ -250,15 +263,15 @@ public class ServerProxyImpl implements ServerProxy try { configure(); - + configureWebApps(); - + server.start(); - - System.setProperty("jetty.ant.server.port","" + ((ServerConnector)server.getConnectors()[0]).getLocalPort()); - + + System.setProperty("jetty.ant.server.port", "" + ((ServerConnector)server.getConnectors()[0]).getLocalPort()); + String host = ((ServerConnector)server.getConnectors()[0]).getHost(); - + if (host == null) { System.setProperty("jetty.ant.server.host", "localhost"); @@ -267,9 +280,9 @@ public class ServerProxyImpl implements ServerProxy { System.setProperty("jetty.ant.server.host", host); } - + startScanners(); - + TaskLog.log("Jetty AntTask Started"); if (!daemon) @@ -286,9 +299,6 @@ public class ServerProxyImpl implements ServerProxy } } - - - /** * @see org.eclipse.jetty.ant.utils.ServerProxy#getProxiedObject() */ @@ -298,7 +308,6 @@ public class ServerProxyImpl implements ServerProxy return server; } - /** * @return the daemon */ @@ -307,16 +316,14 @@ public class ServerProxyImpl implements ServerProxy return daemon; } - /** * @param daemon the daemon to set */ public void setDaemon(boolean daemon) - { + { this.daemon = daemon; } - /** * @return the contextHandlers */ @@ -325,27 +332,23 @@ public class ServerProxyImpl implements ServerProxy return contextHandlers; } - /** * @param contextHandlers the contextHandlers to set */ - public void setContextHandlers (ContextHandlers contextHandlers) + public void setContextHandlers(ContextHandlers contextHandlers) { this.contextHandlers = contextHandlers; } - public int getScanIntervalSecs() { return scanIntervalSecs; } - public void setScanIntervalSecs(int scanIntervalSecs) { this.scanIntervalSecs = scanIntervalSecs; } - /** * Configures Jetty server before adding any web applications to it. @@ -354,27 +357,27 @@ public class ServerProxyImpl implements ServerProxy { if (configured) return; - + configured = true; - if(stopPort>0 && stopKey!=null) + if (stopPort > 0 && stopKey != null) { ShutdownMonitor monitor = ShutdownMonitor.getInstance(); monitor.setPort(stopPort); monitor.setKey(stopKey); monitor.setExitVm(false); } - + if (tempDirectory != null && !tempDirectory.exists()) tempDirectory.mkdirs(); - + // Applies external configuration via jetty.xml applyJettyXml(); // Configures connectors for this server instance. if (connectors != null) { - for (Connector c:connectors) + for (Connector c : connectors) { ServerConnector jc = new ServerConnector(server); @@ -388,7 +391,7 @@ public class ServerProxyImpl implements ServerProxy // Configures login services if (loginServices != null) { - for (LoginService ls:loginServices) + for (LoginService ls : loginServices) { server.addBean(ls); } @@ -400,46 +403,44 @@ public class ServerProxyImpl implements ServerProxy // Set default server handlers configureHandlers(); } - - + /** - * + * */ private void configureHandlers() { if (requestLog != null) server.setRequestLog(requestLog); - contexts = (ContextHandlerCollection) server - .getChildHandlerByClass(ContextHandlerCollection.class); + contexts = (ContextHandlerCollection)server + .getChildHandlerByClass(ContextHandlerCollection.class); if (contexts == null) { contexts = new ContextHandlerCollection(); - HandlerCollection handlers = (HandlerCollection) server - .getChildHandlerByClass(HandlerCollection.class); + HandlerCollection handlers = (HandlerCollection)server + .getChildHandlerByClass(HandlerCollection.class); if (handlers == null) { handlers = new HandlerCollection(); server.setHandler(handlers); - handlers.setHandlers(new Handler[] { contexts, new DefaultHandler() }); + handlers.setHandlers(new Handler[]{contexts, new DefaultHandler()}); } else { handlers.addHandler(contexts); } } - + //if there are any extra contexts to deploy if (contextHandlers != null && contextHandlers.getContextHandlers() != null) { - for (ContextHandler c:contextHandlers.getContextHandlers()) + for (ContextHandler c : contextHandlers.getContextHandlers()) + { contexts.addHandler(c); + } } } - - - /** * Applies jetty.xml configuration to the Jetty server instance. */ @@ -447,8 +448,7 @@ public class ServerProxyImpl implements ServerProxy { if (jettyXml != null && jettyXml.exists()) { - TaskLog.log("Configuring jetty from xml configuration file = " - + jettyXml.getAbsolutePath()); + TaskLog.log("Configuring jetty from xml configuration file = " + jettyXml.getAbsolutePath()); XmlConfiguration configuration; try { @@ -474,21 +474,19 @@ public class ServerProxyImpl implements ServerProxy } } - /** * Starts web applications' scanners. */ private void startScanners() throws Exception { - for (AntWebAppContext awc:webApplications) + for (AntWebAppContext awc : webApplications) { if (scanIntervalSecs <= 0) return; List scanList = awc.getScanFiles(); - - TaskLog.log("Web application '" + awc + "': starting scanner at interval of " - + scanIntervalSecs + " seconds."); + + TaskLog.log("Web application '" + awc + "': starting scanner at interval of " + scanIntervalSecs + " seconds."); Scanner.Listener changeListener = new WebAppScannerListener(awc); Scanner scanner = new Scanner(); scanner.setScanInterval(scanIntervalSecs); @@ -496,21 +494,19 @@ public class ServerProxyImpl implements ServerProxy scanner.setScanDirs(scanList); scanner.setReportExistingFilesOnStartup(false); scanner.start(); - } + } } - - + /** - * + * */ private void configureWebApps() { - for (AntWebAppContext awc:webApplications) + for (AntWebAppContext awc : webApplications) { awc.setAttribute(AntWebAppContext.BASETEMPDIR, tempDirectory); if (contexts != null) contexts.addHandler(awc); } } - } diff --git a/jetty-ant/src/main/java/org/eclipse/jetty/ant/types/Attribute.java b/jetty-ant/src/main/java/org/eclipse/jetty/ant/types/Attribute.java index 96633989b58..2bec15d8ebe 100644 --- a/jetty-ant/src/main/java/org/eclipse/jetty/ant/types/Attribute.java +++ b/jetty-ant/src/main/java/org/eclipse/jetty/ant/types/Attribute.java @@ -22,24 +22,24 @@ public class Attribute { String name; - + String value; - + public void setName(String name) { this.name = name; } - + public void setValue(String value) { this.value = value; } - + public String getName() { return name; } - + public String getValue() { return value; diff --git a/jetty-ant/src/main/java/org/eclipse/jetty/ant/types/Attributes.java b/jetty-ant/src/main/java/org/eclipse/jetty/ant/types/Attributes.java index db3de2fb456..516ed1109df 100644 --- a/jetty-ant/src/main/java/org/eclipse/jetty/ant/types/Attributes.java +++ b/jetty-ant/src/main/java/org/eclipse/jetty/ant/types/Attributes.java @@ -25,12 +25,12 @@ public class Attributes { List _attributes = new ArrayList(); - - public void addAttribute(Attribute attr ) + + public void addAttribute(Attribute attr) { _attributes.add(attr); } - + public List getAttributes() { return _attributes; diff --git a/jetty-ant/src/main/java/org/eclipse/jetty/ant/types/Connector.java b/jetty-ant/src/main/java/org/eclipse/jetty/ant/types/Connector.java index eddb1c39457..47ce2c2fd18 100644 --- a/jetty-ant/src/main/java/org/eclipse/jetty/ant/types/Connector.java +++ b/jetty-ant/src/main/java/org/eclipse/jetty/ant/types/Connector.java @@ -20,8 +20,6 @@ package org.eclipse.jetty.ant.types; /** * Connector - * - * */ public class Connector { @@ -58,5 +56,4 @@ public class Connector { this.maxIdleTime = maxIdleTime; } - } diff --git a/jetty-ant/src/main/java/org/eclipse/jetty/ant/types/Connectors.java b/jetty-ant/src/main/java/org/eclipse/jetty/ant/types/Connectors.java index 6b25db15f4e..68f2a6e48ba 100644 --- a/jetty-ant/src/main/java/org/eclipse/jetty/ant/types/Connectors.java +++ b/jetty-ant/src/main/java/org/eclipse/jetty/ant/types/Connectors.java @@ -16,7 +16,6 @@ // ======================================================================== // - package org.eclipse.jetty.ant.types; import java.util.ArrayList; @@ -33,7 +32,8 @@ public class Connectors /** * Default constructor. */ - public Connectors() { + public Connectors() + { this(8080, 30000); } @@ -78,5 +78,4 @@ public class Connectors { return defaultConnectors; } - } diff --git a/jetty-ant/src/main/java/org/eclipse/jetty/ant/types/ContextHandlers.java b/jetty-ant/src/main/java/org/eclipse/jetty/ant/types/ContextHandlers.java index 0c250583d2a..7930ab10284 100644 --- a/jetty-ant/src/main/java/org/eclipse/jetty/ant/types/ContextHandlers.java +++ b/jetty-ant/src/main/java/org/eclipse/jetty/ant/types/ContextHandlers.java @@ -16,7 +16,6 @@ // ======================================================================== // - package org.eclipse.jetty.ant.types; import java.util.ArrayList; diff --git a/jetty-ant/src/main/java/org/eclipse/jetty/ant/types/FileMatchingConfiguration.java b/jetty-ant/src/main/java/org/eclipse/jetty/ant/types/FileMatchingConfiguration.java index 3d08c68e9fb..8c03ec85be5 100644 --- a/jetty-ant/src/main/java/org/eclipse/jetty/ant/types/FileMatchingConfiguration.java +++ b/jetty-ant/src/main/java/org/eclipse/jetty/ant/types/FileMatchingConfiguration.java @@ -16,7 +16,6 @@ // ======================================================================== // - package org.eclipse.jetty.ant.types; import java.io.File; @@ -43,7 +42,7 @@ public class FileMatchingConfiguration /** * @param directoryScanner new directory scanner retrieved from the - * <fileset/> element. + * <fileset/> element. */ public void addDirectoryScanner(DirectoryScanner directoryScanner) { @@ -52,7 +51,7 @@ public class FileMatchingConfiguration /** * @return a list of base directories denoted by a list of directory - * scanners. + * scanners. */ public List getBaseDirectories() { @@ -60,7 +59,7 @@ public class FileMatchingConfiguration Iterator scanners = directoryScanners.iterator(); while (scanners.hasNext()) { - DirectoryScanner scanner = (DirectoryScanner) scanners.next(); + DirectoryScanner scanner = (DirectoryScanner)scanners.next(); baseDirs.add(scanner.getBasedir()); } @@ -69,7 +68,7 @@ public class FileMatchingConfiguration /** * Checks if passed file is scanned by any of the directory scanners. - * + * * @param pathToFile a fully qualified path to tested file. * @return true if so, false otherwise. */ @@ -78,7 +77,7 @@ public class FileMatchingConfiguration Iterator scanners = directoryScanners.iterator(); while (scanners.hasNext()) { - DirectoryScanner scanner = (DirectoryScanner) scanners.next(); + DirectoryScanner scanner = (DirectoryScanner)scanners.next(); scanner.scan(); String[] includedFiles = scanner.getIncludedFiles(); diff --git a/jetty-ant/src/main/java/org/eclipse/jetty/ant/types/LoginServices.java b/jetty-ant/src/main/java/org/eclipse/jetty/ant/types/LoginServices.java index 867f99bca32..33735a8a3e1 100644 --- a/jetty-ant/src/main/java/org/eclipse/jetty/ant/types/LoginServices.java +++ b/jetty-ant/src/main/java/org/eclipse/jetty/ant/types/LoginServices.java @@ -16,7 +16,6 @@ // ======================================================================== // - package org.eclipse.jetty.ant.types; import java.util.ArrayList; diff --git a/jetty-ant/src/main/java/org/eclipse/jetty/ant/types/SystemProperties.java b/jetty-ant/src/main/java/org/eclipse/jetty/ant/types/SystemProperties.java index 3e2b38bbdc9..d5d860fd4ed 100644 --- a/jetty-ant/src/main/java/org/eclipse/jetty/ant/types/SystemProperties.java +++ b/jetty-ant/src/main/java/org/eclipse/jetty/ant/types/SystemProperties.java @@ -16,7 +16,6 @@ // ======================================================================== // - package org.eclipse.jetty.ant.types; import java.util.ArrayList; @@ -27,7 +26,7 @@ import org.eclipse.jetty.ant.utils.TaskLog; /** * SystemProperties - *

    + *

    * Ant <systemProperties/> tag definition. */ public class SystemProperties @@ -47,17 +46,16 @@ public class SystemProperties /** * Set a System.property with this value if it is not already set. - * @param property the property to test + * + * @param property the property to test * @return true if property has been set */ public static boolean setIfNotSetAlready(Property property) { if (System.getProperty(property.getName()) == null) { - System.setProperty(property.getName(), (property.getValue() == null ? "" : property - .getValue())); - TaskLog.log("Setting property '" + property.getName() + "' to value '" - + property.getValue() + "'"); + System.setProperty(property.getName(), (property.getValue() == null ? "" : property.getValue())); + TaskLog.log("Setting property '" + property.getName() + "' to value '" + property.getValue() + "'"); return true; } diff --git a/jetty-ant/src/main/java/org/eclipse/jetty/ant/utils/ServerProxy.java b/jetty-ant/src/main/java/org/eclipse/jetty/ant/utils/ServerProxy.java index 432778e7148..51b02b9309c 100644 --- a/jetty-ant/src/main/java/org/eclipse/jetty/ant/utils/ServerProxy.java +++ b/jetty-ant/src/main/java/org/eclipse/jetty/ant/utils/ServerProxy.java @@ -16,7 +16,6 @@ // ======================================================================== // - package org.eclipse.jetty.ant.utils; import org.eclipse.jetty.ant.AntWebAppContext; @@ -26,7 +25,7 @@ public interface ServerProxy /** * Adds a new web application to this server. - * + * * @param awc a AntWebAppContext object. */ public void addWebApplication(AntWebAppContext awc); @@ -35,8 +34,6 @@ public interface ServerProxy * Starts this server. */ public void start(); - - - public Object getProxiedObject(); + public Object getProxiedObject(); } diff --git a/jetty-ant/src/main/java/org/eclipse/jetty/ant/utils/TaskLog.java b/jetty-ant/src/main/java/org/eclipse/jetty/ant/utils/TaskLog.java index e9aad1d017d..ba0618fda75 100644 --- a/jetty-ant/src/main/java/org/eclipse/jetty/ant/utils/TaskLog.java +++ b/jetty-ant/src/main/java/org/eclipse/jetty/ant/utils/TaskLog.java @@ -26,7 +26,6 @@ import org.apache.tools.ant.Task; /** * Provides logging functionality for classes without access to the Ant project * variable. - * */ public class TaskLog { @@ -34,7 +33,7 @@ public class TaskLog private static Task task; private static final SimpleDateFormat format = new SimpleDateFormat( - "yyyy-MM-dd HH:mm:ss.SSS"); + "yyyy-MM-dd HH:mm:ss.SSS"); public static void setTask(Task task) { diff --git a/jetty-ant/src/test/java/org/eclipse/jetty/ant/AntBuild.java b/jetty-ant/src/test/java/org/eclipse/jetty/ant/AntBuild.java index 9e4db36eed5..a0f20d40c01 100644 --- a/jetty-ant/src/test/java/org/eclipse/jetty/ant/AntBuild.java +++ b/jetty-ant/src/test/java/org/eclipse/jetty/ant/AntBuild.java @@ -46,7 +46,7 @@ public class AntBuild private int _port; private String _host; - + public AntBuild(String ant) { _ant = ant; @@ -55,22 +55,22 @@ public class AntBuild private class AntBuildProcess implements Runnable { List connList; - + @Override public void run() { File buildFile = new File(_ant); - + Project antProject = new Project(); try { antProject.setBaseDir(MavenTestingUtils.getBaseDir()); - antProject.setUserProperty("ant.file",buildFile.getAbsolutePath()); + antProject.setUserProperty("ant.file", buildFile.getAbsolutePath()); DefaultLogger logger = new DefaultLogger(); ConsoleParser parser = new ConsoleParser(); //connList = parser.newPattern(".*([0-9]+\\.[0-9]*\\.[0-9]*\\.[0-9]*):([0-9]*)",1); - connList = parser.newPattern("Jetty AntTask Started",1); + connList = parser.newPattern("Jetty AntTask Started", 1); PipedOutputStream pos = new PipedOutputStream(); PipedInputStream pis = new PipedInputStream(pos); @@ -78,9 +78,9 @@ public class AntBuild PipedOutputStream pose = new PipedOutputStream(); PipedInputStream pise = new PipedInputStream(pose); - startPump("STDOUT",parser,pis); - startPump("STDERR",parser,pise); - + startPump("STDOUT", parser, pis); + startPump("STDERR", parser, pise); + logger.setErrorPrintStream(new PrintStream(pos)); logger.setOutputPrintStream(new PrintStream(pose)); logger.setMessageOutputLevel(Project.MSG_VERBOSE); @@ -91,21 +91,20 @@ public class AntBuild ProjectHelper helper = ProjectHelper.getProjectHelper(); - antProject.addReference("ant.projectHelper",helper); + antProject.addReference("ant.projectHelper", helper); - helper.parse(antProject,buildFile); + helper.parse(antProject, buildFile); antProject.executeTarget("jetty.run"); - - parser.waitForDone(10000,TimeUnit.MILLISECONDS); + + parser.waitForDone(10000, TimeUnit.MILLISECONDS); } catch (Exception e) { antProject.fireBuildFinished(e); } } - - + public void waitForStarted() throws Exception { while (connList == null || connList.isEmpty()) @@ -122,26 +121,25 @@ public class AntBuild _process = new Thread(abp); _process.start(); - + abp.waitForStarted(); - + // once this has returned we should have the connection info we need //_host = abp.getConnectionList().get(0)[0]; //_port = Integer.parseInt(abp.getConnectionList().get(0)[1]); - + } - + public int getJettyPort() { return Integer.parseInt(System.getProperty("jetty.ant.server.port")); } - + public String getJettyHost() { return System.getProperty("jetty.ant.server.host"); } - - + /** * Stop the jetty server */ @@ -159,7 +157,7 @@ public class AntBuild public List newPattern(String exp, int cnt) { - ConsolePattern pat = new ConsolePattern(exp,cnt); + ConsolePattern pat = new ConsolePattern(exp, cnt); patterns.add(pat); count += cnt; @@ -191,7 +189,7 @@ public class AntBuild public void waitForDone(long timeout, TimeUnit unit) throws InterruptedException { - getLatch().await(timeout,unit); + getLatch().await(timeout, unit); } private CountDownLatch getLatch() @@ -239,9 +237,9 @@ public class AntBuild private void startPump(String mode, ConsoleParser parser, InputStream inputStream) { - ConsoleStreamer pump = new ConsoleStreamer(mode,inputStream); + ConsoleStreamer pump = new ConsoleStreamer(mode, inputStream); pump.setParser(parser); - Thread thread = new Thread(pump,"ConsoleStreamer/" + mode); + Thread thread = new Thread(pump, "ConsoleStreamer/" + mode); thread.start(); } diff --git a/jetty-ant/src/test/java/org/eclipse/jetty/ant/JettyAntTaskTest.java b/jetty-ant/src/test/java/org/eclipse/jetty/ant/JettyAntTaskTest.java index ca2ef880874..2d6124cfa6c 100644 --- a/jetty-ant/src/test/java/org/eclipse/jetty/ant/JettyAntTaskTest.java +++ b/jetty-ant/src/test/java/org/eclipse/jetty/ant/JettyAntTaskTest.java @@ -18,29 +18,29 @@ package org.eclipse.jetty.ant; -import static org.hamcrest.Matchers.is; -import static org.hamcrest.MatcherAssert.assertThat; - import java.net.HttpURLConnection; import java.net.URI; import org.eclipse.jetty.toolchain.test.MavenTestingUtils; import org.junit.jupiter.api.Test; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.is; + public class JettyAntTaskTest { - + @Test public void testConnectorTask() throws Exception { AntBuild build = new AntBuild(MavenTestingUtils.getTestResourceFile("connector-test.xml").getAbsolutePath()); - + build.start(); - + URI uri = new URI("http://" + build.getJettyHost() + ":" + build.getJettyPort()); - + HttpURLConnection connection = (HttpURLConnection)uri.toURL().openConnection(); - + connection.connect(); assertThat("response code is 404", connection.getResponseCode(), is(404)); @@ -48,9 +48,8 @@ public class JettyAntTaskTest build.stop(); } - @Test - public void testWebApp () throws Exception + public void testWebApp() throws Exception { AntBuild build = new AntBuild(MavenTestingUtils.getTestResourceFile("webapp-test.xml").getAbsolutePath()); @@ -67,6 +66,4 @@ public class JettyAntTaskTest System.err.println("Stop build!"); build.stop(); } - - } diff --git a/jetty-client/pom.xml b/jetty-client/pom.xml index 2ce321e6e30..67c8d231d5a 100644 --- a/jetty-client/pom.xml +++ b/jetty-client/pom.xml @@ -19,12 +19,7 @@ maven-surefire-plugin - @{argLine} ${jetty.surefire.argLine} - --add-reads org.eclipse.jetty.client=jetty.servlet.api - --add-modules java.security.jgss - --add-modules jetty.servlet.api - --add-modules org.eclipse.jetty.jmx - --add-modules org.slf4j + @{argLine} ${jetty.surefire.argLine} --add-reads org.eclipse.jetty.client=jetty.servlet.api --add-modules java.security.jgss --add-modules jetty.servlet.api --add-modules org.eclipse.jetty.jmx --add-modules org.slf4j diff --git a/jetty-client/src/main/java/org/eclipse/jetty/client/AbstractConnectionPool.java b/jetty-client/src/main/java/org/eclipse/jetty/client/AbstractConnectionPool.java index 55dff0d7c89..1d4ebaec7e7 100644 --- a/jetty-client/src/main/java/org/eclipse/jetty/client/AbstractConnectionPool.java +++ b/jetty-client/src/main/java/org/eclipse/jetty/client/AbstractConnectionPool.java @@ -38,7 +38,7 @@ public abstract class AbstractConnectionPool implements ConnectionPool, Dumpable private static final Logger LOG = Log.getLogger(AbstractConnectionPool.class); private final AtomicBoolean closed = new AtomicBoolean(); - + /** * The connectionCount encodes both the total connections plus the pending connection counts, so both can be atomically changed. * The bottom 32 bits represent the total connections and the top 32 bits represent the pending connections. @@ -106,18 +106,18 @@ public abstract class AbstractConnectionPool implements ConnectionPool, Dumpable int total = AtomicBiInteger.getLo(encoded); if (LOG.isDebugEnabled()) - LOG.debug("tryCreate {}/{} connections {}/{} pending",total,maxConnections,pending,maxPending); - + LOG.debug("tryCreate {}/{} connections {}/{} pending", total, maxConnections, pending, maxPending); + if (total >= maxConnections) return; - if (maxPending>=0 && pending>=maxPending) + if (maxPending >= 0 && pending >= maxPending) return; - - if (connections.compareAndSet(encoded,pending+1,total+1)) + + if (connections.compareAndSet(encoded, pending + 1, total + 1)) { if (LOG.isDebugEnabled()) - LOG.debug("newConnection {}/{} connections {}/{} pending", total+1, maxConnections, pending+1, maxPending); + LOG.debug("newConnection {}/{} connections {}/{} pending", total + 1, maxConnections, pending + 1, maxPending); destination.newConnection(new Promise<>() { @@ -199,7 +199,7 @@ public abstract class AbstractConnectionPool implements ConnectionPool, Dumpable { if (closed.compareAndSet(false, true)) { - connections.set(0,0); + connections.set(0, 0); } } diff --git a/jetty-client/src/main/java/org/eclipse/jetty/client/AuthenticationProtocolHandler.java b/jetty-client/src/main/java/org/eclipse/jetty/client/AuthenticationProtocolHandler.java index a51aea42b9b..4f3d3a48fa7 100644 --- a/jetty-client/src/main/java/org/eclipse/jetty/client/AuthenticationProtocolHandler.java +++ b/jetty-client/src/main/java/org/eclipse/jetty/client/AuthenticationProtocolHandler.java @@ -45,7 +45,7 @@ import org.eclipse.jetty.util.log.Logger; public abstract class AuthenticationProtocolHandler implements ProtocolHandler { - public static final int DEFAULT_MAX_CONTENT_LENGTH = 16*1024; + public static final int DEFAULT_MAX_CONTENT_LENGTH = 16 * 1024; public static final Logger LOG = Log.getLogger(AuthenticationProtocolHandler.class); private final HttpClient client; private final int maxContentLength; @@ -80,18 +80,17 @@ public abstract class AuthenticationProtocolHandler implements ProtocolHandler return new AuthenticationListener(); } - protected List getHeaderInfo(String header) throws IllegalArgumentException { List headerInfos = new ArrayList<>(); Matcher m; - for(String value : new QuotedCSV(true, header)) + for (String value : new QuotedCSV(true, header)) { m = CHALLENGE_PATTERN.matcher(value); if (m.matches()) { - if(m.group("schemeOnly") != null) + if (m.group("schemeOnly") != null) { headerInfos.add(new HeaderInfo(getAuthorizationHeader(), m.group(1), new HashMap<>())); continue; @@ -291,7 +290,7 @@ public abstract class AuthenticationProtocolHandler implements ProtocolHandler { result.addAll(getHeaderInfo(value)); } - catch(IllegalArgumentException e) + catch (IllegalArgumentException e) { if (LOG.isDebugEnabled()) LOG.debug("Failed to parse authentication header", e); diff --git a/jetty-client/src/main/java/org/eclipse/jetty/client/ContentDecoder.java b/jetty-client/src/main/java/org/eclipse/jetty/client/ContentDecoder.java index c4449b703f8..eb69c1d5734 100644 --- a/jetty-client/src/main/java/org/eclipse/jetty/client/ContentDecoder.java +++ b/jetty-client/src/main/java/org/eclipse/jetty/client/ContentDecoder.java @@ -53,7 +53,7 @@ public interface ContentDecoder * {@link Factory} instances are configured in {@link HttpClient} via * {@link HttpClient#getContentDecoderFactories()}. */ - public static abstract class Factory + public abstract static class Factory { private final String encoding; @@ -73,8 +73,10 @@ public interface ContentDecoder @Override public boolean equals(Object obj) { - if (this == obj) return true; - if (!(obj instanceof Factory)) return false; + if (this == obj) + return true; + if (!(obj instanceof Factory)) + return false; Factory that = (Factory)obj; return encoding.equals(that.encoding); } diff --git a/jetty-client/src/main/java/org/eclipse/jetty/client/DuplexConnectionPool.java b/jetty-client/src/main/java/org/eclipse/jetty/client/DuplexConnectionPool.java index 6f51a4a6d8e..bfccf42c6b3 100644 --- a/jetty-client/src/main/java/org/eclipse/jetty/client/DuplexConnectionPool.java +++ b/jetty-client/src/main/java/org/eclipse/jetty/client/DuplexConnectionPool.java @@ -245,8 +245,8 @@ public class DuplexConnectionPool extends AbstractConnectionPool implements Swee lock(); try { - active = new DumpableCollection("active",new ArrayList<>(activeConnections)); - idle = new DumpableCollection("idle",new ArrayList<>(idleConnections)); + active = new DumpableCollection("active", new ArrayList<>(activeConnections)); + idle = new DumpableCollection("idle", new ArrayList<>(idleConnections)); } finally { @@ -268,8 +268,8 @@ public class DuplexConnectionPool extends AbstractConnectionPool implements Swee try { toSweep = activeConnections.stream() - .filter(connection -> connection instanceof Sweeper.Sweepable) - .collect(Collectors.toList()); + .filter(connection -> connection instanceof Sweeper.Sweepable) + .collect(Collectors.toList()); } finally { @@ -282,11 +282,11 @@ public class DuplexConnectionPool extends AbstractConnectionPool implements Swee { boolean removed = remove(connection, true); LOG.warn("Connection swept: {}{}{} from active connections{}{}", - connection, - System.lineSeparator(), - removed ? "Removed" : "Not removed", - System.lineSeparator(), - dump()); + connection, + System.lineSeparator(), + removed ? "Removed" : "Not removed", + System.lineSeparator(), + dump()); } } @@ -310,11 +310,11 @@ public class DuplexConnectionPool extends AbstractConnectionPool implements Swee } return String.format("%s@%x[c=%d/%d,a=%d,i=%d]", - getClass().getSimpleName(), - hashCode(), - getConnectionCount(), - getMaxConnectionCount(), - activeSize, - idleSize); + getClass().getSimpleName(), + hashCode(), + getConnectionCount(), + getMaxConnectionCount(), + activeSize, + idleSize); } } diff --git a/jetty-client/src/main/java/org/eclipse/jetty/client/GZIPContentDecoder.java b/jetty-client/src/main/java/org/eclipse/jetty/client/GZIPContentDecoder.java index 7a02c1b4f04..7699a98dad8 100644 --- a/jetty-client/src/main/java/org/eclipse/jetty/client/GZIPContentDecoder.java +++ b/jetty-client/src/main/java/org/eclipse/jetty/client/GZIPContentDecoder.java @@ -36,7 +36,7 @@ public class GZIPContentDecoder extends org.eclipse.jetty.http.GZIPContentDecode public GZIPContentDecoder(int bufferSize) { - this(null,bufferSize); + this(null, bufferSize); } public GZIPContentDecoder(ByteBufferPool byteBufferPool, int bufferSize) diff --git a/jetty-client/src/main/java/org/eclipse/jetty/client/HttpChannel.java b/jetty-client/src/main/java/org/eclipse/jetty/client/HttpChannel.java index 3351e46f6bb..a8699fba543 100644 --- a/jetty-client/src/main/java/org/eclipse/jetty/client/HttpChannel.java +++ b/jetty-client/src/main/java/org/eclipse/jetty/client/HttpChannel.java @@ -40,7 +40,7 @@ public abstract class HttpChannel { _totalTimeout.destroy(); } - + public HttpDestination getHttpDestination() { return _destination; diff --git a/jetty-client/src/main/java/org/eclipse/jetty/client/HttpClient.java b/jetty-client/src/main/java/org/eclipse/jetty/client/HttpClient.java index 4b82e97e490..c53e8e66710 100644 --- a/jetty-client/src/main/java/org/eclipse/jetty/client/HttpClient.java +++ b/jetty-client/src/main/java/org/eclipse/jetty/client/HttpClient.java @@ -200,9 +200,9 @@ public class HttpClient extends ContainerLifeCycle ByteBufferPool byteBufferPool = getByteBufferPool(); if (byteBufferPool == null) setByteBufferPool(new MappedByteBufferPool(2048, - executor instanceof ThreadPool.SizedThreadPool - ? ((ThreadPool.SizedThreadPool)executor).getMaxThreads() / 2 - : ProcessorUtils.availableProcessors() * 2)); + executor instanceof ThreadPool.SizedThreadPool + ? ((ThreadPool.SizedThreadPool)executor).getMaxThreads() / 2 + : ProcessorUtils.availableProcessors() * 2)); Scheduler scheduler = getScheduler(); if (scheduler == null) setScheduler(new ScheduledExecutorScheduler(name + "-scheduler", false)); @@ -236,7 +236,9 @@ public class HttpClient extends ContainerLifeCycle handlers.clear(); for (HttpDestination destination : destinations.values()) + { destination.close(); + } destinations.clear(); requestListeners.clear(); @@ -316,6 +318,8 @@ public class HttpClient extends ContainerLifeCycle return decoderFactories; } + // @checkstyle-disable-check : MethodNameCheck + /** * Performs a GET request to the specified URI. * @@ -399,6 +403,8 @@ public class HttpClient extends ContainerLifeCycle return newRequest(uri).method(HttpMethod.POST); } + // @checkstyle-enable-check : MethodNameCheck + /** * Creates a new request with the "http" scheme and the specified host and port * @@ -437,11 +443,11 @@ public class HttpClient extends ContainerLifeCycle { Request newRequest = newHttpRequest(oldRequest.getConversation(), newURI); newRequest.method(oldRequest.getMethod()) - .version(oldRequest.getVersion()) - .content(oldRequest.getContent()) - .idleTimeout(oldRequest.getIdleTimeout(), TimeUnit.MILLISECONDS) - .timeout(oldRequest.getTimeout(), TimeUnit.MILLISECONDS) - .followRedirects(oldRequest.isFollowRedirects()); + .version(oldRequest.getVersion()) + .content(oldRequest.getContent()) + .idleTimeout(oldRequest.getIdleTimeout(), TimeUnit.MILLISECONDS) + .timeout(oldRequest.getTimeout(), TimeUnit.MILLISECONDS) + .followRedirects(oldRequest.isFollowRedirects()); for (HttpField field : oldRequest.getHeaders()) { HttpHeader header = field.getHeader(); @@ -459,7 +465,7 @@ public class HttpClient extends ContainerLifeCycle // Remove authorization headers. if (HttpHeader.AUTHORIZATION == header || - HttpHeader.PROXY_AUTHORIZATION == header) + HttpHeader.PROXY_AUTHORIZATION == header) continue; String name = field.getName(); @@ -513,7 +519,7 @@ public class HttpClient extends ContainerLifeCycle private Origin createOrigin(String scheme, String host, int port) { if (!HttpScheme.HTTP.is(scheme) && !HttpScheme.HTTPS.is(scheme) && - !HttpScheme.WS.is(scheme) && !HttpScheme.WSS.is(scheme)) + !HttpScheme.WS.is(scheme) && !HttpScheme.WSS.is(scheme)) throw new IllegalArgumentException("Invalid protocol " + scheme); scheme = scheme.toLowerCase(Locale.ENGLISH); @@ -967,6 +973,7 @@ public class HttpClient extends ContainerLifeCycle /** * Sets the http compliance mode for parsing http responses. * This affect how weak the {@link HttpParser} parses http responses and which http protocol level is supported + * * @param httpCompliance The compliance level which is used to actually parse http responses */ public void setHttpCompliance(HttpCompliance httpCompliance) @@ -1254,7 +1261,7 @@ public class HttpClient extends ContainerLifeCycle else { StringBuilder value = new StringBuilder(); - for (Iterator iterator = set.iterator(); iterator.hasNext();) + for (Iterator iterator = set.iterator(); iterator.hasNext(); ) { ContentDecoder.Factory decoderFactory = iterator.next(); value.append(decoderFactory.getEncoding()); diff --git a/jetty-client/src/main/java/org/eclipse/jetty/client/HttpConnection.java b/jetty-client/src/main/java/org/eclipse/jetty/client/HttpConnection.java index a4a264e8342..f2642ced9eb 100644 --- a/jetty-client/src/main/java/org/eclipse/jetty/client/HttpConnection.java +++ b/jetty-client/src/main/java/org/eclipse/jetty/client/HttpConnection.java @@ -67,7 +67,7 @@ public abstract class HttpConnection implements IConnection HttpRequest httpRequest = (HttpRequest)request; ArrayList listeners = new ArrayList<>(httpRequest.getResponseListeners()); - + httpRequest.sent(); if (listener != null) listeners.add(listener); diff --git a/jetty-client/src/main/java/org/eclipse/jetty/client/HttpContent.java b/jetty-client/src/main/java/org/eclipse/jetty/client/HttpContent.java index faa26d21021..efb5e983e4d 100644 --- a/jetty-client/src/main/java/org/eclipse/jetty/client/HttpContent.java +++ b/jetty-client/src/main/java/org/eclipse/jetty/client/HttpContent.java @@ -82,7 +82,6 @@ public class HttpContent implements Callback, Closeable } /** - * @param buffer * @return true if the buffer is the sentinel instance {@link CLOSE} */ private static boolean isTheCloseBuffer(ByteBuffer buffer) @@ -91,7 +90,7 @@ public class HttpContent implements Callback, Closeable boolean isTheCloseBuffer = (buffer == CLOSE); return isTheCloseBuffer; } - + /** * @return whether there is any content at all */ @@ -234,11 +233,11 @@ public class HttpContent implements Callback, Closeable public String toString() { return String.format("%s@%x - has=%b,last=%b,consumed=%b,buffer=%s", - getClass().getSimpleName(), - hashCode(), - hasContent(), - isLast(), - isConsumed(), - BufferUtil.toDetailString(getContent())); + getClass().getSimpleName(), + hashCode(), + hasContent(), + isLast(), + isConsumed(), + BufferUtil.toDetailString(getContent())); } } diff --git a/jetty-client/src/main/java/org/eclipse/jetty/client/HttpContentResponse.java b/jetty-client/src/main/java/org/eclipse/jetty/client/HttpContentResponse.java index cfe7ba23346..2a1aec0cc4b 100644 --- a/jetty-client/src/main/java/org/eclipse/jetty/client/HttpContentResponse.java +++ b/jetty-client/src/main/java/org/eclipse/jetty/client/HttpContentResponse.java @@ -129,10 +129,10 @@ public class HttpContentResponse implements ContentResponse public String toString() { return String.format("%s[%s %d %s - %d bytes]", - HttpContentResponse.class.getSimpleName(), - getVersion(), - getStatus(), - getReason(), - getContent().length); + HttpContentResponse.class.getSimpleName(), + getVersion(), + getStatus(), + getReason(), + getContent().length); } } diff --git a/jetty-client/src/main/java/org/eclipse/jetty/client/HttpConversation.java b/jetty-client/src/main/java/org/eclipse/jetty/client/HttpConversation.java index 3f57de2b9fc..d1151d27b63 100644 --- a/jetty-client/src/main/java/org/eclipse/jetty/client/HttpConversation.java +++ b/jetty-client/src/main/java/org/eclipse/jetty/client/HttpConversation.java @@ -45,46 +45,46 @@ public class HttpConversation extends AttributesMap * This list changes as the conversation proceeds, as follows: *

      *
    1. - * request R1 send => conversation.updateResponseListeners(null) - *
        - *
      • exchanges in conversation: E1
      • - *
      • listeners to be notified: E1.listeners
      • - *
      + * request R1 send => conversation.updateResponseListeners(null) + *
        + *
      • exchanges in conversation: E1
      • + *
      • listeners to be notified: E1.listeners
      • + *
      *
    2. *
    3. - * response R1 arrived, 401 => conversation.updateResponseListeners(AuthenticationProtocolHandler.listener) - *
        - *
      • exchanges in conversation: E1
      • - *
      • listeners to be notified: AuthenticationProtocolHandler.listener
      • - *
      + * response R1 arrived, 401 => conversation.updateResponseListeners(AuthenticationProtocolHandler.listener) + *
        + *
      • exchanges in conversation: E1
      • + *
      • listeners to be notified: AuthenticationProtocolHandler.listener
      • + *
      *
    4. *
    5. - * request R2 send => conversation.updateResponseListeners(null) - *
        - *
      • exchanges in conversation: E1 + E2
      • - *
      • listeners to be notified: E2.listeners + E1.listeners
      • - *
      + * request R2 send => conversation.updateResponseListeners(null) + *
        + *
      • exchanges in conversation: E1 + E2
      • + *
      • listeners to be notified: E2.listeners + E1.listeners
      • + *
      *
    6. *
    7. - * response R2 arrived, 302 => conversation.updateResponseListeners(RedirectProtocolHandler.listener) - *
        - *
      • exchanges in conversation: E1 + E2
      • - *
      • listeners to be notified: E2.listeners + RedirectProtocolHandler.listener
      • - *
      + * response R2 arrived, 302 => conversation.updateResponseListeners(RedirectProtocolHandler.listener) + *
        + *
      • exchanges in conversation: E1 + E2
      • + *
      • listeners to be notified: E2.listeners + RedirectProtocolHandler.listener
      • + *
      *
    8. *
    9. - * request R3 send => conversation.updateResponseListeners(null) - *
        - *
      • exchanges in conversation: E1 + E2 + E3
      • - *
      • listeners to be notified: E3.listeners + E1.listeners
      • - *
      + * request R3 send => conversation.updateResponseListeners(null) + *
        + *
      • exchanges in conversation: E1 + E2 + E3
      • + *
      • listeners to be notified: E3.listeners + E1.listeners
      • + *
      *
    10. *
    11. - * response R3 arrived, 200 => conversation.updateResponseListeners(null) - *
        - *
      • exchanges in conversation: E1 + E2 + E3
      • - *
      • listeners to be notified: E3.listeners + E1.listeners
      • - *
      + * response R3 arrived, 200 => conversation.updateResponseListeners(null) + *
        + *
      • exchanges in conversation: E1 + E2 + E3
      • + *
      • listeners to be notified: E3.listeners + E1.listeners
      • + *
      *
    12. *
    * Basically the override conversation listener replaces the first exchange response listener, diff --git a/jetty-client/src/main/java/org/eclipse/jetty/client/HttpDestination.java b/jetty-client/src/main/java/org/eclipse/jetty/client/HttpDestination.java index 14022463f73..847d5f45ee5 100644 --- a/jetty-client/src/main/java/org/eclipse/jetty/client/HttpDestination.java +++ b/jetty-client/src/main/java/org/eclipse/jetty/client/HttpDestination.java @@ -469,7 +469,9 @@ public class HttpDestination extends ContainerLifeCycle implements Destination, // and we don't want to fail it immediately as if it was queued before the failure. // The call to Request.abort() will remove the exchange from the exchanges queue. for (HttpExchange exchange : new ArrayList<>(exchanges)) + { exchange.getRequest().abort(cause); + } if (exchanges.isEmpty()) tryRemoveIdleDestination(); } @@ -503,12 +505,12 @@ public class HttpDestination extends ContainerLifeCycle implements Destination, public String toString() { return String.format("%s[%s]@%x%s,queue=%d,pool=%s", - HttpDestination.class.getSimpleName(), - asString(), - hashCode(), - proxy == null ? "" : "(via " + proxy + ")", - exchanges.size(), - connectionPool); + HttpDestination.class.getSimpleName(), + asString(), + hashCode(), + proxy == null ? "" : "(via " + proxy + ")", + exchanges.size(), + connectionPool); } @FunctionalInterface @@ -541,7 +543,7 @@ public class HttpDestination extends ContainerLifeCycle implements Destination, /** * Creates a Key with the given origin and protocol and a {@code null} kind. * - * @param origin the origin + * @param origin the origin * @param protocol the protocol */ public Key(Origin origin, Protocol protocol) @@ -552,9 +554,9 @@ public class HttpDestination extends ContainerLifeCycle implements Destination, /** * Creates a Key with the given origin and protocol and kind. * - * @param origin the origin + * @param origin the origin * @param protocol the protocol - * @param kind the opaque kind + * @param kind the opaque kind */ public Key(Origin origin, Protocol protocol, String kind) { @@ -587,8 +589,8 @@ public class HttpDestination extends ContainerLifeCycle implements Destination, return false; Key that = (Key)obj; return origin.equals(that.origin) && - Objects.equals(protocol, that.protocol) && - Objects.equals(kind, that.kind); + Objects.equals(protocol, that.protocol) && + Objects.equals(kind, that.kind); } @Override @@ -600,9 +602,9 @@ public class HttpDestination extends ContainerLifeCycle implements Destination, public String asString() { return String.format("%s|%s,kind=%s", - origin.asString(), - protocol == null ? "null" : protocol.asString(), - kind); + origin.asString(), + protocol == null ? "null" : protocol.asString(), + kind); } @Override diff --git a/jetty-client/src/main/java/org/eclipse/jetty/client/HttpExchange.java b/jetty-client/src/main/java/org/eclipse/jetty/client/HttpExchange.java index d694bc950e3..74d66ffd797 100644 --- a/jetty-client/src/main/java/org/eclipse/jetty/client/HttpExchange.java +++ b/jetty-client/src/main/java/org/eclipse/jetty/client/HttpExchange.java @@ -291,10 +291,10 @@ public class HttpExchange synchronized (this) { return String.format("%s@%x req=%s/%s@%h res=%s/%s@%h", - HttpExchange.class.getSimpleName(), - hashCode(), - requestState, requestFailure, requestFailure, - responseState, responseFailure, responseFailure); + HttpExchange.class.getSimpleName(), + hashCode(), + requestState, requestFailure, requestFailure, + responseState, responseFailure, responseFailure); } } diff --git a/jetty-client/src/main/java/org/eclipse/jetty/client/HttpProxy.java b/jetty-client/src/main/java/org/eclipse/jetty/client/HttpProxy.java index 42789788b53..07511ff3c5b 100644 --- a/jetty-client/src/main/java/org/eclipse/jetty/client/HttpProxy.java +++ b/jetty-client/src/main/java/org/eclipse/jetty/client/HttpProxy.java @@ -105,7 +105,7 @@ public class HttpProxy extends ProxyConfiguration.Proxy else { throw new IOException("Cannot tunnel request, missing " + - SslContextFactory.class.getName() + " in " + HttpClient.class.getName()); + SslContextFactory.class.getName() + " in " + HttpClient.class.getName()); } } else @@ -156,11 +156,11 @@ public class HttpProxy extends ProxyConfiguration.Proxy HttpClient httpClient = destination.getHttpClient(); long connectTimeout = httpClient.getConnectTimeout(); Request connect = httpClient.newRequest(proxyAddress.getHost(), proxyAddress.getPort()) - .method(HttpMethod.CONNECT) - .path(target) - .header(HttpHeader.HOST, target) - .idleTimeout(2 * connectTimeout, TimeUnit.MILLISECONDS) - .timeout(connectTimeout, TimeUnit.MILLISECONDS); + .method(HttpMethod.CONNECT) + .path(target) + .header(HttpHeader.HOST, target) + .idleTimeout(2 * connectTimeout, TimeUnit.MILLISECONDS) + .timeout(connectTimeout, TimeUnit.MILLISECONDS); ProxyConfiguration.Proxy proxy = destination.getProxy(); if (proxy != null && proxy.isSecure()) connect.scheme(HttpScheme.HTTPS.asString()); @@ -184,7 +184,7 @@ public class HttpProxy extends ProxyConfiguration.Proxy else { HttpResponseException failure = new HttpResponseException("Unexpected " + response + - " for " + result.getRequest(), response); + " for " + result.getRequest(), response); tunnelFailed(endPoint, failure); } } diff --git a/jetty-client/src/main/java/org/eclipse/jetty/client/HttpReceiver.java b/jetty-client/src/main/java/org/eclipse/jetty/client/HttpReceiver.java index 4e28877e6c2..fbf558977fe 100644 --- a/jetty-client/src/main/java/org/eclipse/jetty/client/HttpReceiver.java +++ b/jetty-client/src/main/java/org/eclipse/jetty/client/HttpReceiver.java @@ -22,7 +22,6 @@ import java.io.IOException; import java.net.URI; import java.nio.ByteBuffer; import java.util.Collections; -import java.util.Enumeration; import java.util.HashMap; import java.util.List; import java.util.Map; @@ -158,7 +157,8 @@ public abstract class HttpReceiver */ protected boolean responseHeader(HttpExchange exchange, HttpField field) { - out: while (true) + out: + while (true) { ResponseState current = responseState.get(); switch (current) @@ -240,7 +240,8 @@ public abstract class HttpReceiver */ protected boolean responseHeaders(HttpExchange exchange) { - out: while (true) + out: + while (true) { ResponseState current = responseState.get(); switch (current) @@ -266,16 +267,16 @@ public abstract class HttpReceiver List responseListeners = exchange.getConversation().getResponseListeners(); notifier.notifyHeaders(responseListeners, response); contentListeners = responseListeners.stream() - .filter(Response.AsyncContentListener.class::isInstance) - .map(Response.AsyncContentListener.class::cast) - .collect(Collectors.toList()); + .filter(Response.AsyncContentListener.class::isInstance) + .map(Response.AsyncContentListener.class::cast) + .collect(Collectors.toList()); List contentEncodings = response.getHeaders().getCSV(HttpHeader.CONTENT_ENCODING.asString(), false); if (contentEncodings != null && !contentEncodings.isEmpty()) { for (ContentDecoder.Factory factory : getHttpDestination().getHttpClient().getContentDecoderFactories()) { - for (String encoding: contentEncodings) + for (String encoding : contentEncodings) { if (factory.getEncoding().equalsIgnoreCase(encoding)) { @@ -305,7 +306,8 @@ public abstract class HttpReceiver */ protected boolean responseContent(HttpExchange exchange, ByteBuffer buffer, Callback callback) { - out: while (true) + out: + while (true) { ResponseState current = responseState.get(); switch (current) @@ -483,7 +485,8 @@ public abstract class HttpReceiver { // Update the state to avoid more response processing. boolean terminate; - out: while (true) + out: + while (true) { ResponseState current = responseState.get(); switch (current) @@ -546,10 +549,10 @@ public abstract class HttpReceiver public String toString() { return String.format("%s@%x(rsp=%s,failure=%s)", - getClass().getSimpleName(), - hashCode(), - responseState, - failure); + getClass().getSimpleName(), + hashCode(), + responseState, + failure); } /** diff --git a/jetty-client/src/main/java/org/eclipse/jetty/client/HttpRedirector.java b/jetty-client/src/main/java/org/eclipse/jetty/client/HttpRedirector.java index 47292818600..4e6a6a0799c 100644 --- a/jetty-client/src/main/java/org/eclipse/jetty/client/HttpRedirector.java +++ b/jetty-client/src/main/java/org/eclipse/jetty/client/HttpRedirector.java @@ -102,11 +102,11 @@ public class HttpRedirector /** * Redirects the given {@code response}, blocking until the redirect is complete. * - * @param request the original request that triggered the redirect + * @param request the original request that triggered the redirect * @param response the response to the original request * @return a {@link Result} object containing the request to the redirected location and its response * @throws InterruptedException if the thread is interrupted while waiting for the redirect to complete - * @throws ExecutionException if the redirect failed + * @throws ExecutionException if the redirect failed * @see #redirect(Request, Response, Response.CompleteListener) */ public Result redirect(Request request, Response response) throws InterruptedException, ExecutionException @@ -119,9 +119,9 @@ public class HttpRedirector public void onComplete(Result result) { resultRef.set(new Result(result.getRequest(), - result.getRequestFailure(), - new HttpContentResponse(result.getResponse(), getContent(), getMediaType(), getEncoding()), - result.getResponseFailure())); + result.getRequestFailure(), + new HttpContentResponse(result.getResponse(), getContent(), getMediaType(), getEncoding()), + result.getResponseFailure())); latch.countDown(); } }); @@ -145,7 +145,7 @@ public class HttpRedirector /** * Redirects the given {@code response} asynchronously. * - * @param request the original request that triggered the redirect + * @param request the original request that triggered the redirect * @param response the response to the original request * @param listener the listener that receives response events * @return the request to the redirected location @@ -218,7 +218,7 @@ public class HttpRedirector { return new URI(scheme, authority, path, query, fragment); } - catch (URISyntaxException xx) + catch (URISyntaxException ex) { // Give up } diff --git a/jetty-client/src/main/java/org/eclipse/jetty/client/HttpRequest.java b/jetty-client/src/main/java/org/eclipse/jetty/client/HttpRequest.java index 2ea5cb6ed43..c2d0d02df88 100644 --- a/jetty-client/src/main/java/org/eclipse/jetty/client/HttpRequest.java +++ b/jetty-client/src/main/java/org/eclipse/jetty/client/HttpRequest.java @@ -203,7 +203,7 @@ public class HttpRequest implements Request { if (uri == null) uri = buildURI(true); - + @SuppressWarnings("ReferenceEquality") boolean isNullURI = (uri == NULL_URI); return isNullURI ? null : uri; @@ -344,8 +344,10 @@ public class HttpRequest implements Request ArrayList result = new ArrayList<>(); for (RequestListener listener : requestListeners) + { if (type.isInstance(listener)) result.add((T)listener); + } return result; } @@ -683,7 +685,7 @@ public class HttpRequest implements Request return listener.get(); } catch (ExecutionException x) - { + { // Previously this method used a timed get on the future, which was in a race // with the timeouts implemented in HttpDestination and HttpConnection. The change to // make those timeouts relative to the timestamp taken in sent() has made that race @@ -695,7 +697,7 @@ public class HttpRequest implements Request // Thus for backwards compatibility we unwrap the timeout exception here if (x.getCause() instanceof TimeoutException) { - TimeoutException t = (TimeoutException) (x.getCause()); + TimeoutException t = (TimeoutException)(x.getCause()); abort(t); throw t; } @@ -704,7 +706,7 @@ public class HttpRequest implements Request throw x; } catch (Throwable x) - { + { // Differently from the Future, the semantic of this method is that if // the send() is interrupted or times out, we abort the request. abort(x); @@ -717,7 +719,7 @@ public class HttpRequest implements Request { send(this, listener); } - + private void send(HttpRequest request, Response.CompleteListener listener) { if (listener != null) @@ -731,7 +733,7 @@ public class HttpRequest implements Request long timeout = getTimeout(); timeoutAt = timeout > 0 ? System.nanoTime() + TimeUnit.MILLISECONDS.toNanos(timeout) : -1; } - + /** * @return The nanoTime at which the timeout expires or -1 if there is no timeout. * @see #timeout(long, TimeUnit) @@ -740,7 +742,7 @@ public class HttpRequest implements Request { return timeoutAt; } - + protected List getResponseListeners() { return responseListeners; diff --git a/jetty-client/src/main/java/org/eclipse/jetty/client/HttpResponse.java b/jetty-client/src/main/java/org/eclipse/jetty/client/HttpResponse.java index a746ca0be5e..b4a82af8d6c 100644 --- a/jetty-client/src/main/java/org/eclipse/jetty/client/HttpResponse.java +++ b/jetty-client/src/main/java/org/eclipse/jetty/client/HttpResponse.java @@ -96,8 +96,10 @@ public class HttpResponse implements Response { ArrayList result = new ArrayList<>(); for (ResponseListener listener : listeners) + { if (type == null || type.isInstance(listener)) result.add((T)listener); + } return result; } diff --git a/jetty-client/src/main/java/org/eclipse/jetty/client/HttpResponseException.java b/jetty-client/src/main/java/org/eclipse/jetty/client/HttpResponseException.java index e0d9c625a6b..9477ae736c8 100644 --- a/jetty-client/src/main/java/org/eclipse/jetty/client/HttpResponseException.java +++ b/jetty-client/src/main/java/org/eclipse/jetty/client/HttpResponseException.java @@ -28,7 +28,7 @@ public class HttpResponseException extends RuntimeException { this(message, response, null); } - + public HttpResponseException(String message, Response response, Throwable cause) { super(message, cause); diff --git a/jetty-client/src/main/java/org/eclipse/jetty/client/HttpSender.java b/jetty-client/src/main/java/org/eclipse/jetty/client/HttpSender.java index d29c09663b8..e9e74b7c6f4 100644 --- a/jetty-client/src/main/java/org/eclipse/jetty/client/HttpSender.java +++ b/jetty-client/src/main/java/org/eclipse/jetty/client/HttpSender.java @@ -180,7 +180,8 @@ public abstract class HttpSender implements AsyncContentProvider.Listener if (expects100Continue(request)) newSenderState = content.hasContent() ? SenderState.EXPECTING_WITH_CONTENT : SenderState.EXPECTING; - out: while (true) + out: + while (true) { SenderState current = senderState.get(); switch (current) @@ -530,7 +531,8 @@ public abstract class HttpSender implements AsyncContentProvider.Listener { // Update the state to avoid more request processing. boolean terminate; - out: while (true) + out: + while (true) { RequestState current = requestState.get(); switch (current) @@ -602,11 +604,11 @@ public abstract class HttpSender implements AsyncContentProvider.Listener public String toString() { return String.format("%s@%x(req=%s,snd=%s,failure=%s)", - getClass().getSimpleName(), - hashCode(), - requestState, - senderState, - failure); + getClass().getSimpleName(), + hashCode(), + requestState, + senderState, + failure); } /** @@ -729,7 +731,7 @@ public abstract class HttpSender implements AsyncContentProvider.Listener if (!headersToCommit(exchange)) return; - HttpContent content = HttpSender.this.content; + HttpContent content = HttpSender.this.content; if (content == null) return; diff --git a/jetty-client/src/main/java/org/eclipse/jetty/client/MultiplexConnectionPool.java b/jetty-client/src/main/java/org/eclipse/jetty/client/MultiplexConnectionPool.java index cfdfbd530a9..389b05fd76e 100644 --- a/jetty-client/src/main/java/org/eclipse/jetty/client/MultiplexConnectionPool.java +++ b/jetty-client/src/main/java/org/eclipse/jetty/client/MultiplexConnectionPool.java @@ -235,9 +235,9 @@ public class MultiplexConnectionPool extends AbstractConnectionPool implements C synchronized (this) { activeConnections.values().stream() - .map(holder -> holder.connection) - .filter(connection -> connection instanceof Sweeper.Sweepable) - .collect(Collectors.toCollection(() -> toSweep)); + .map(holder -> holder.connection) + .filter(connection -> connection instanceof Sweeper.Sweepable) + .collect(Collectors.toCollection(() -> toSweep)); } for (Connection connection : toSweep) { @@ -245,11 +245,11 @@ public class MultiplexConnectionPool extends AbstractConnectionPool implements C { boolean removed = remove(connection, true); LOG.warn("Connection swept: {}{}{} from active connections{}{}", - connection, - System.lineSeparator(), - removed ? "Removed" : "Not removed", - System.lineSeparator(), - dump()); + connection, + System.lineSeparator(), + removed ? "Removed" : "Not removed", + System.lineSeparator(), + dump()); } } return false; @@ -266,13 +266,13 @@ public class MultiplexConnectionPool extends AbstractConnectionPool implements C idleSize = idleConnections.size(); } return String.format("%s@%x[connections=%d/%d,multiplex=%d,active=%d,idle=%d]", - getClass().getSimpleName(), - hashCode(), - getConnectionCount(), - getMaxConnectionCount(), - getMaxMultiplex(), - activeSize, - idleSize); + getClass().getSimpleName(), + hashCode(), + getConnectionCount(), + getMaxConnectionCount(), + getMaxMultiplex(), + activeSize, + idleSize); } private static class Holder diff --git a/jetty-client/src/main/java/org/eclipse/jetty/client/ProtocolHandler.java b/jetty-client/src/main/java/org/eclipse/jetty/client/ProtocolHandler.java index c7d60b907d9..a5486831832 100644 --- a/jetty-client/src/main/java/org/eclipse/jetty/client/ProtocolHandler.java +++ b/jetty-client/src/main/java/org/eclipse/jetty/client/ProtocolHandler.java @@ -44,7 +44,7 @@ public interface ProtocolHandler *

    This method is being called just after the response line has * been parsed, and before the response headers are available.

    * - * @param request the request to accept + * @param request the request to accept * @param response the response to accept * @return true if this protocol handler can handle the given request and response */ diff --git a/jetty-client/src/main/java/org/eclipse/jetty/client/ProtocolHandlers.java b/jetty-client/src/main/java/org/eclipse/jetty/client/ProtocolHandlers.java index 04ab05278f2..fd34210d916 100644 --- a/jetty-client/src/main/java/org/eclipse/jetty/client/ProtocolHandlers.java +++ b/jetty-client/src/main/java/org/eclipse/jetty/client/ProtocolHandlers.java @@ -79,7 +79,7 @@ public class ProtocolHandlers implements Dumpable * {@link ProtocolHandler#accept(Request, Response) accepts} * the given request and response.

    * - * @param request the request to accept + * @param request the request to accept * @param response the response to accept * @return the protocol handler that accepted the request and response, * or null if none of the protocol handlers accepted the request and response diff --git a/jetty-client/src/main/java/org/eclipse/jetty/client/ProxyConfiguration.java b/jetty-client/src/main/java/org/eclipse/jetty/client/ProxyConfiguration.java index 4bfeb5b4805..d8e8acbbc05 100644 --- a/jetty-client/src/main/java/org/eclipse/jetty/client/ProxyConfiguration.java +++ b/jetty-client/src/main/java/org/eclipse/jetty/client/ProxyConfiguration.java @@ -57,7 +57,7 @@ public class ProxyConfiguration return null; } - public static abstract class Proxy + public abstract static class Proxy { // TO use IPAddress Map private final Set included = new HashSet<>(); @@ -154,7 +154,7 @@ public class ProxyConfiguration HostPort hostPort = new HostPort(pattern); String host = hostPort.getHost(); int port = hostPort.getPort(); - return host.equals(address.getHost()) && ( port<=0 || port==address.getPort() ); + return host.equals(address.getHost()) && (port <= 0 || port == address.getPort()); } /** @@ -169,5 +169,4 @@ public class ProxyConfiguration return address.toString(); } } - } diff --git a/jetty-client/src/main/java/org/eclipse/jetty/client/ResponseNotifier.java b/jetty-client/src/main/java/org/eclipse/jetty/client/ResponseNotifier.java index 7db9af83851..7561e6f63ca 100644 --- a/jetty-client/src/main/java/org/eclipse/jetty/client/ResponseNotifier.java +++ b/jetty-client/src/main/java/org/eclipse/jetty/client/ResponseNotifier.java @@ -106,9 +106,9 @@ public class ResponseNotifier public void notifyContent(List listeners, Response response, ByteBuffer buffer, Callback callback) { List contentListeners = listeners.stream() - .filter(Response.AsyncContentListener.class::isInstance) - .map(Response.AsyncContentListener.class::cast) - .collect(Collectors.toList()); + .filter(Response.AsyncContentListener.class::isInstance) + .map(Response.AsyncContentListener.class::cast) + .collect(Collectors.toList()); notifyContent(response, buffer, callback, contentListeners); } @@ -122,7 +122,9 @@ public class ResponseNotifier { CountingCallback counter = new CountingCallback(callback, contentListeners.size()); for (Response.AsyncContentListener listener : contentListeners) + { notifyContent(listener, response, buffer.slice(), counter); + } } } diff --git a/jetty-client/src/main/java/org/eclipse/jetty/client/RoundRobinConnectionPool.java b/jetty-client/src/main/java/org/eclipse/jetty/client/RoundRobinConnectionPool.java index 64cda710b16..d16af4f2d87 100644 --- a/jetty-client/src/main/java/org/eclipse/jetty/client/RoundRobinConnectionPool.java +++ b/jetty-client/src/main/java/org/eclipse/jetty/client/RoundRobinConnectionPool.java @@ -45,7 +45,9 @@ public class RoundRobinConnectionPool extends AbstractConnectionPool implements super(destination, maxConnections, requester); entries = new ArrayList<>(maxConnections); for (int i = 0; i < maxConnections; ++i) + { entries.add(new Entry()); + } this.maxMultiplex = maxMultiplex; } @@ -213,11 +215,11 @@ public class RoundRobinConnectionPool extends AbstractConnectionPool implements } } return String.format("%s@%x[c=%d/%d,a=%d]", - getClass().getSimpleName(), - hashCode(), - present, - getMaxConnectionCount(), - active + getClass().getSimpleName(), + hashCode(), + present, + getMaxConnectionCount(), + active ); } diff --git a/jetty-client/src/main/java/org/eclipse/jetty/client/Socks4Proxy.java b/jetty-client/src/main/java/org/eclipse/jetty/client/Socks4Proxy.java index 0cfee584cfa..677867f1f6a 100644 --- a/jetty-client/src/main/java/org/eclipse/jetty/client/Socks4Proxy.java +++ b/jetty-client/src/main/java/org/eclipse/jetty/client/Socks4Proxy.java @@ -112,7 +112,9 @@ public class Socks4Proxy extends ProxyConfiguration.Proxy ByteBuffer buffer = ByteBuffer.allocate(9); buffer.put((byte)4).put((byte)1).putShort(port); for (int i = 1; i <= 4; ++i) + { buffer.put((byte)Integer.parseInt(matcher.group(i))); + } buffer.put((byte)0); buffer.flip(); getEndPoint().write(this, buffer); diff --git a/jetty-client/src/main/java/org/eclipse/jetty/client/ValidatingConnectionPool.java b/jetty-client/src/main/java/org/eclipse/jetty/client/ValidatingConnectionPool.java index f1ffad9e7d3..9f6e2e7d475 100644 --- a/jetty-client/src/main/java/org/eclipse/jetty/client/ValidatingConnectionPool.java +++ b/jetty-client/src/main/java/org/eclipse/jetty/client/ValidatingConnectionPool.java @@ -203,8 +203,8 @@ public class ValidatingConnectionPool extends DuplexConnectionPool public String toString() { return String.format("%s[validationLeft=%dms]", - connection, - timeout - TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - timestamp) + connection, + timeout - TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - timestamp) ); } } diff --git a/jetty-client/src/main/java/org/eclipse/jetty/client/api/Authentication.java b/jetty-client/src/main/java/org/eclipse/jetty/client/api/Authentication.java index ddd2716145e..1b94643e51b 100644 --- a/jetty-client/src/main/java/org/eclipse/jetty/client/api/Authentication.java +++ b/jetty-client/src/main/java/org/eclipse/jetty/client/api/Authentication.java @@ -42,12 +42,14 @@ public interface Authentication { /** * Constant used to indicate that any realm will match. + * * @see #matches(String, URI, String) */ public static final String ANY_REALM = "<>"; /** * Matches {@link Authentication}s based on the given parameters + * * @param type the {@link Authentication} type such as "Basic" or "Digest" * @param uri the request URI * @param realm the authentication realm as provided in the {@code WWW-Authenticate} response header @@ -66,9 +68,9 @@ public interface Authentication * @param request the request to execute the authentication mechanism for * @param response the 401 response obtained in the previous attempt to request the protected resource * @param headerInfo the {@code WWW-Authenticate} (or {@code Proxy-Authenticate}) header chosen for this - * authentication (among the many that the response may contain) + * authentication (among the many that the response may contain) * @param context the conversation context in case the authentication needs multiple exchanges - * to be completed and information needs to be stored across exchanges + * to be completed and information needs to be stored across exchanges * @return the authentication result, or null if the authentication could not be performed */ Result authenticate(Request request, ContentResponse response, HeaderInfo headerInfo, Attributes context); @@ -80,16 +82,15 @@ public interface Authentication { private final HttpHeader header; private final String type; - private final Map params; + private final Map params; - - public HeaderInfo(HttpHeader header, String type, Map params) throws IllegalArgumentException + public HeaderInfo(HttpHeader header, String type, Map params) throws IllegalArgumentException { this.header = header; this.type = type; this.params = params; } - + /** * @return the authentication type (for example "Basic" or "Digest") */ @@ -113,7 +114,7 @@ public interface Authentication { return params.get("base64"); } - + /** * @return additional authentication parameters */ @@ -121,7 +122,7 @@ public interface Authentication { return params; } - + /** * @return specified authentication parameter or null if does not exist */ diff --git a/jetty-client/src/main/java/org/eclipse/jetty/client/api/Request.java b/jetty-client/src/main/java/org/eclipse/jetty/client/api/Request.java index 09f35d9ec12..9e872adb16c 100644 --- a/jetty-client/src/main/java/org/eclipse/jetty/client/api/Request.java +++ b/jetty-client/src/main/java/org/eclipse/jetty/client/api/Request.java @@ -243,7 +243,7 @@ public interface Request /** * @param accepts the media types that are acceptable in the response, such as - * "text/plain;q=0.5" or "text/html" (corresponds to the {@code Accept} header) + * "text/plain;q=0.5" or "text/html" (corresponds to the {@code Accept} header) * @return this request object */ Request accept(String... accepts); @@ -268,7 +268,7 @@ public interface Request /** * @param timeout the total timeout for the request/response conversation; - * use zero or a negative value to disable the timeout + * use zero or a negative value to disable the timeout * @param unit the timeout unit * @return this request object */ @@ -287,8 +287,8 @@ public interface Request /** * @param listenerClass the class of the listener, or null for all listeners classes - * @return the listeners for request events of the given class * @param the type of listener class + * @return the listeners for request events of the given class */ List getRequestListeners(Class listenerClass); @@ -477,6 +477,7 @@ public interface Request * Callback method invoked when the request headers (and perhaps small content) are ready to be sent. * The request has been converted into bytes, but not yet sent to the server, and further modifications * to the request may have no effect. + * * @param request the request that is about to be committed */ public void onHeaders(Request request); @@ -491,6 +492,7 @@ public interface Request * Callback method invoked when the request headers (and perhaps small content) have been sent. * The request is now committed, and in transit to the server, and further modifications to the * request may have no effect. + * * @param request the request that has been committed */ public void onCommit(Request request); @@ -504,6 +506,7 @@ public interface Request /** * Callback method invoked when a chunk of request content has been sent successfully. * Changes to bytes in the given buffer have no effect, as the content has already been sent. + * * @param request the request that has been committed * @param content the content */ @@ -530,6 +533,7 @@ public interface Request { /** * Callback method invoked when the request has failed to be sent + * * @param request the request that failed * @param failure the failure */ diff --git a/jetty-client/src/main/java/org/eclipse/jetty/client/api/Response.java b/jetty-client/src/main/java/org/eclipse/jetty/client/api/Response.java index 98efe012e1b..95605aad404 100644 --- a/jetty-client/src/main/java/org/eclipse/jetty/client/api/Response.java +++ b/jetty-client/src/main/java/org/eclipse/jetty/client/api/Response.java @@ -47,8 +47,8 @@ public interface Response /** * @param listenerClass the listener class - * @return the response listener passed to {@link org.eclipse.jetty.client.api.Request#send(org.eclipse.jetty.client.api.Response.CompleteListener)} * @param the type of class + * @return the response listener passed to {@link org.eclipse.jetty.client.api.Request#send(org.eclipse.jetty.client.api.Response.CompleteListener)} */ List getListeners(Class listenerClass); diff --git a/jetty-client/src/main/java/org/eclipse/jetty/client/api/Result.java b/jetty-client/src/main/java/org/eclipse/jetty/client/api/Result.java index c014562ef5a..d354c881607 100644 --- a/jetty-client/src/main/java/org/eclipse/jetty/client/api/Result.java +++ b/jetty-client/src/main/java/org/eclipse/jetty/client/api/Result.java @@ -120,9 +120,9 @@ public class Result public String toString() { return String.format("%s[%s > %s] %s", - Result.class.getSimpleName(), - request, - response, - getFailure()); + Result.class.getSimpleName(), + request, + response, + getFailure()); } } diff --git a/jetty-client/src/main/java/org/eclipse/jetty/client/dynamic/HttpClientTransportDynamic.java b/jetty-client/src/main/java/org/eclipse/jetty/client/dynamic/HttpClientTransportDynamic.java index 33820ecf1ff..27cb983c197 100644 --- a/jetty-client/src/main/java/org/eclipse/jetty/client/dynamic/HttpClientTransportDynamic.java +++ b/jetty-client/src/main/java/org/eclipse/jetty/client/dynamic/HttpClientTransportDynamic.java @@ -105,13 +105,15 @@ public class HttpClientTransportDynamic extends AbstractConnectorHttpClientTrans throw new IllegalArgumentException("Missing ClientConnectionFactory"); this.factoryInfos = Arrays.asList(factoryInfos); this.protocols = Arrays.stream(factoryInfos) - .flatMap(info -> info.getProtocols().stream()) - .distinct() - .collect(Collectors.toList()); + .flatMap(info -> info.getProtocols().stream()) + .distinct() + .collect(Collectors.toList()); for (ClientConnectionFactory.Info factoryInfo : factoryInfos) + { addBean(factoryInfo); + } setConnectionPoolFactory(destination -> - new MultiplexConnectionPool(destination, destination.getHttpClient().getMaxConnectionsPerDestination(), destination, 1)); + new MultiplexConnectionPool(destination, destination.getHttpClient().getMaxConnectionsPerDestination(), destination, 1)); } @Override @@ -130,8 +132,8 @@ public class HttpClientTransportDynamic extends AbstractConnectorHttpClientTrans { // Preserve the order of protocols chosen by the application. protocols = this.protocols.stream() - .filter(p -> p.equals("http/1.1") || p.equals(http2)) - .collect(Collectors.toList()); + .filter(p -> p.equals("http/1.1") || p.equals(http2)) + .collect(Collectors.toList()); } if (protocols.isEmpty()) return new HttpDestination.Key(origin, null); @@ -164,7 +166,7 @@ public class HttpClientTransportDynamic extends AbstractConnectorHttpClientTrans else { factoryInfo = findClientConnectionFactoryInfo(protocol.getProtocols()) - .orElseThrow(() -> new IOException("Cannot find " + ClientConnectionFactory.class.getSimpleName() + " for " + protocol)); + .orElseThrow(() -> new IOException("Cannot find " + ClientConnectionFactory.class.getSimpleName() + " for " + protocol)); } } return factoryInfo.getClientConnectionFactory().newConnection(endPoint, context); @@ -182,7 +184,7 @@ public class HttpClientTransportDynamic extends AbstractConnectorHttpClientTrans throw new IOException("Could not negotiate protocol among " + alpnConnection.getProtocols()); List protocols = List.of(protocol); Info factoryInfo = findClientConnectionFactoryInfo(protocols) - .orElseThrow(() -> new IOException("Cannot find " + ClientConnectionFactory.class.getSimpleName() + " for negotiated protocol " + protocol)); + .orElseThrow(() -> new IOException("Cannot find " + ClientConnectionFactory.class.getSimpleName() + " for negotiated protocol " + protocol)); return factoryInfo.getClientConnectionFactory().newConnection(endPoint, context); } catch (Throwable failure) @@ -195,7 +197,7 @@ public class HttpClientTransportDynamic extends AbstractConnectorHttpClientTrans private Optional findClientConnectionFactoryInfo(List protocols) { return factoryInfos.stream() - .filter(info -> info.matches(protocols)) - .findFirst(); + .filter(info -> info.matches(protocols)) + .findFirst(); } } diff --git a/jetty-client/src/main/java/org/eclipse/jetty/client/http/HttpChannelOverHTTP.java b/jetty-client/src/main/java/org/eclipse/jetty/client/http/HttpChannelOverHTTP.java index 892ff052e7c..6bd8cd84d9d 100644 --- a/jetty-client/src/main/java/org/eclipse/jetty/client/http/HttpChannelOverHTTP.java +++ b/jetty-client/src/main/java/org/eclipse/jetty/client/http/HttpChannelOverHTTP.java @@ -82,7 +82,7 @@ public class HttpChannelOverHTTP extends HttpChannel public void send(HttpExchange exchange) { outMessages.increment(); - sender.send( exchange ); + sender.send(exchange); } @Override @@ -98,19 +98,19 @@ public class HttpChannelOverHTTP extends HttpChannel return result; HttpResponse response = exchange.getResponse(); - - if ((response.getVersion() == HttpVersion.HTTP_1_1) && + + if ((response.getVersion() == HttpVersion.HTTP_1_1) && (response.getStatus() == HttpStatus.SWITCHING_PROTOCOLS_101)) { - String next_connection = response.getHeaders().get(HttpHeader.CONNECTION); - if ((next_connection == null) || !next_connection.toLowerCase(Locale.US).contains("upgrade")) + String nextConnection = response.getHeaders().get(HttpHeader.CONNECTION); + if ((nextConnection == null) || !nextConnection.toLowerCase(Locale.US).contains("upgrade")) { - return new Result(result,new HttpResponseException("101 Switching Protocols without Connection: Upgrade not supported",response)); + return new Result(result, new HttpResponseException("101 Switching Protocols without Connection: Upgrade not supported", response)); } - + // Upgrade Response HttpRequest request = exchange.getRequest(); - HttpConnectionUpgrader upgrader = (HttpConnectionUpgrader) request.getConversation().getAttribute(HttpConnectionUpgrader.class.getName()); + HttpConnectionUpgrader upgrader = (HttpConnectionUpgrader)request.getConversation().getAttribute(HttpConnectionUpgrader.class.getName()); if (upgrader != null) { try @@ -197,9 +197,8 @@ public class HttpChannelOverHTTP extends HttpChannel public String toString() { return String.format("%s[send=%s,recv=%s]", - super.toString(), - sender, - receiver); + super.toString(), + sender, + receiver); } - } diff --git a/jetty-client/src/main/java/org/eclipse/jetty/client/http/HttpReceiverOverHTTP.java b/jetty-client/src/main/java/org/eclipse/jetty/client/http/HttpReceiverOverHTTP.java index cdfbad98ec6..0df897bd79b 100644 --- a/jetty-client/src/main/java/org/eclipse/jetty/client/http/HttpReceiverOverHTTP.java +++ b/jetty-client/src/main/java/org/eclipse/jetty/client/http/HttpReceiverOverHTTP.java @@ -237,7 +237,7 @@ public class HttpReceiverOverHTTP extends HttpReceiver implements HttpParser.Res String method = exchange.getRequest().getMethod(); parser.setHeadResponse(HttpMethod.HEAD.is(method) || - (HttpMethod.CONNECT.is(method) && status == HttpStatus.OK_200)); + (HttpMethod.CONNECT.is(method) && status == HttpStatus.OK_200)); exchange.getResponse().version(version).status(status).reason(reason); return !responseBegin(exchange); @@ -328,7 +328,7 @@ public class HttpReceiverOverHTTP extends HttpReceiver implements HttpParser.Res return true; if (HttpMethod.CONNECT.is(exchange.getRequest().getMethod()) && - status == HttpStatus.OK_200) + status == HttpStatus.OK_200) return true; return false; diff --git a/jetty-client/src/main/java/org/eclipse/jetty/client/package-info.java b/jetty-client/src/main/java/org/eclipse/jetty/client/package-info.java index 44bdf682a96..af26327a722 100644 --- a/jetty-client/src/main/java/org/eclipse/jetty/client/package-info.java +++ b/jetty-client/src/main/java/org/eclipse/jetty/client/package-info.java @@ -18,7 +18,7 @@ /** * Jetty Client : Implementation and Core Classes - * + * * This package provides APIs, utility classes and an implementation of an asynchronous HTTP client. *

    * The core class is {@link org.eclipse.jetty.client.HttpClient}, which acts as a central configuration object (for example @@ -48,6 +48,3 @@ */ package org.eclipse.jetty.client; -import org.eclipse.jetty.client.api.Response; - - diff --git a/jetty-client/src/main/java/org/eclipse/jetty/client/proxy/ProxyProtocolClientConnectionFactory.java b/jetty-client/src/main/java/org/eclipse/jetty/client/proxy/ProxyProtocolClientConnectionFactory.java index 87350b6ef8d..e60c0d90aa6 100644 --- a/jetty-client/src/main/java/org/eclipse/jetty/client/proxy/ProxyProtocolClientConnectionFactory.java +++ b/jetty-client/src/main/java/org/eclipse/jetty/client/proxy/ProxyProtocolClientConnectionFactory.java @@ -61,7 +61,7 @@ public class ProxyProtocolClientConnectionFactory implements ClientConnectionFac private class ProxyProtocolConnection extends AbstractConnection implements Callback { - private final Logger LOG = Log.getLogger(ProxyProtocolConnection.class); + private final Logger log = Log.getLogger(ProxyProtocolConnection.class); private final Map context; public ProxyProtocolConnection(EndPoint endPoint, Executor executor, Map context) @@ -77,6 +77,8 @@ public class ProxyProtocolClientConnectionFactory implements ClientConnectionFac writePROXYLine(); } + // @checkstyle-disable-check : MethodNameCheck + protected void writePROXYLine() { Origin.Address proxiedAddress = proxiedAddressSupplier.get(); @@ -93,13 +95,15 @@ public class ProxyProtocolClientConnectionFactory implements ClientConnectionFac int serverPort = serverSocketAddress.getPort(); boolean ipv6 = serverAddress instanceof Inet6Address; - String line = String.format("PROXY %s %s %s %d %d\r\n", ipv6 ? "TCP6" : "TCP4" , proxiedIP, serverIP, proxiedPort, serverPort); - if (LOG.isDebugEnabled()) - LOG.debug("Writing PROXY line: {}", line.trim()); + String line = String.format("PROXY %s %s %s %d %d\r\n", ipv6 ? "TCP6" : "TCP4", proxiedIP, serverIP, proxiedPort, serverPort); + if (log.isDebugEnabled()) + log.debug("Writing PROXY line: {}", line.trim()); ByteBuffer buffer = ByteBuffer.wrap(line.getBytes(StandardCharsets.US_ASCII)); getEndPoint().write(this, buffer); } + // @checkstyle-enable-check : MethodNameCheck + @Override public void succeeded() { @@ -107,8 +111,8 @@ public class ProxyProtocolClientConnectionFactory implements ClientConnectionFac { EndPoint endPoint = getEndPoint(); org.eclipse.jetty.io.Connection connection = connectionFactory.newConnection(endPoint, context); - if (LOG.isDebugEnabled()) - LOG.debug("Written PROXY line, upgrading to {}", connection); + if (log.isDebugEnabled()) + log.debug("Written PROXY line, upgrading to {}", connection); endPoint.upgrade(connection); } catch (Throwable x) diff --git a/jetty-client/src/main/java/org/eclipse/jetty/client/util/BufferingResponseListener.java b/jetty-client/src/main/java/org/eclipse/jetty/client/util/BufferingResponseListener.java index c50d0ca0ef9..68e3313c416 100644 --- a/jetty-client/src/main/java/org/eclipse/jetty/client/util/BufferingResponseListener.java +++ b/jetty-client/src/main/java/org/eclipse/jetty/client/util/BufferingResponseListener.java @@ -188,7 +188,7 @@ public abstract class BufferingResponseListener extends Listener.Adapter return null; return BufferUtil.toString(buffer, encoding); } - + /** * @return Content as InputStream */ diff --git a/jetty-client/src/main/java/org/eclipse/jetty/client/util/ByteBufferContentProvider.java b/jetty-client/src/main/java/org/eclipse/jetty/client/util/ByteBufferContentProvider.java index 7b4fe2f034b..845d6eb0a33 100644 --- a/jetty-client/src/main/java/org/eclipse/jetty/client/util/ByteBufferContentProvider.java +++ b/jetty-client/src/main/java/org/eclipse/jetty/client/util/ByteBufferContentProvider.java @@ -47,7 +47,9 @@ public class ByteBufferContentProvider extends AbstractTypedContentProvider this.buffers = buffers; int length = 0; for (ByteBuffer buffer : buffers) + { length += buffer.remaining(); + } this.length = length; } diff --git a/jetty-client/src/main/java/org/eclipse/jetty/client/util/BytesContentProvider.java b/jetty-client/src/main/java/org/eclipse/jetty/client/util/BytesContentProvider.java index 44fe38d9900..534b98ed7fa 100644 --- a/jetty-client/src/main/java/org/eclipse/jetty/client/util/BytesContentProvider.java +++ b/jetty-client/src/main/java/org/eclipse/jetty/client/util/BytesContentProvider.java @@ -43,7 +43,9 @@ public class BytesContentProvider extends AbstractTypedContentProvider this.bytes = bytes; long length = 0; for (byte[] buffer : bytes) + { length += buffer.length; + } this.length = length; } diff --git a/jetty-client/src/main/java/org/eclipse/jetty/client/util/DeferredContentProvider.java b/jetty-client/src/main/java/org/eclipse/jetty/client/util/DeferredContentProvider.java index 909495ae2c2..29b8ed9a925 100644 --- a/jetty-client/src/main/java/org/eclipse/jetty/client/util/DeferredContentProvider.java +++ b/jetty-client/src/main/java/org/eclipse/jetty/client/util/DeferredContentProvider.java @@ -54,8 +54,8 @@ import org.eclipse.jetty.util.Callback; * However, it is possible for subclasses to override {@link #offer(ByteBuffer)} and {@link #close()} to copy * the content to another location (for example a file) and be able to support multiple invocations * of of {@link #iterator()} returning the iterator provided by this - * class on the first invocation, and an iterator on the bytes copied to the other location - * for subsequent invocations. + * class on the first invocation, and an iterator on the bytes copied to the other location + * for subsequent invocations. *

    * Typical usage of {@link DeferredContentProvider} is in asynchronous proxies, where HTTP headers arrive * separately from HTTP content chunks. @@ -107,7 +107,9 @@ public class DeferredContentProvider implements AsyncContentProvider, Callback, public DeferredContentProvider(ByteBuffer... buffers) { for (ByteBuffer buffer : buffers) + { offer(buffer); + } } @Override @@ -115,7 +117,7 @@ public class DeferredContentProvider implements AsyncContentProvider, Callback, { if (!this.listener.compareAndSet(null, listener)) throw new IllegalStateException(String.format("The same %s instance cannot be used in multiple requests", - AsyncContentProvider.class.getName())); + AsyncContentProvider.class.getName())); if (isClosed()) { @@ -123,7 +125,9 @@ public class DeferredContentProvider implements AsyncContentProvider, Callback, { long total = 0; for (Chunk chunk : chunks) + { total += chunk.buffer.remaining(); + } length = total; } } @@ -308,7 +312,9 @@ public class DeferredContentProvider implements AsyncContentProvider, Callback, lock.notify(); } for (Chunk chunk : chunks) + { chunk.callback.failed(x); + } } @Override diff --git a/jetty-client/src/main/java/org/eclipse/jetty/client/util/DigestAuthentication.java b/jetty-client/src/main/java/org/eclipse/jetty/client/util/DigestAuthentication.java index 50152277725..9d2079fd078 100644 --- a/jetty-client/src/main/java/org/eclipse/jetty/client/util/DigestAuthentication.java +++ b/jetty-client/src/main/java/org/eclipse/jetty/client/util/DigestAuthentication.java @@ -36,7 +36,6 @@ import org.eclipse.jetty.http.HttpHeader; import org.eclipse.jetty.util.Attributes; import org.eclipse.jetty.util.StringUtil; import org.eclipse.jetty.util.TypeUtil; -import org.eclipse.jetty.util.log.Log; /** * Implementation of the HTTP "Digest" authentication defined in RFC 2617. @@ -69,15 +68,14 @@ public class DigestAuthentication extends AbstractAuthentication return "Digest"; } - @Override public boolean matches(String type, URI uri, String realm) { // digest authenication requires a realm if (realm == null) return false; - - return super.matches(type,uri,realm); + + return super.matches(type, uri, realm); } @Override @@ -98,7 +96,7 @@ public class DigestAuthentication extends AbstractAuthentication String clientQOP = null; if (serverQOP != null) { - List serverQOPValues = StringUtil.csvSplit(null,serverQOP,0,serverQOP.length()); + List serverQOPValues = StringUtil.csvSplit(null, serverQOP, 0, serverQOP.length()); if (serverQOPValues.contains("auth")) clientQOP = "auth"; else if (serverQOPValues.contains("auth-int")) @@ -162,33 +160,33 @@ public class DigestAuthentication extends AbstractAuthentication if (digester == null) return; - String A1 = user + ":" + realm + ":" + password; - String hashA1 = toHexString(digester.digest(A1.getBytes(StandardCharsets.ISO_8859_1))); + String a1 = user + ":" + realm + ":" + password; + String hashA1 = toHexString(digester.digest(a1.getBytes(StandardCharsets.ISO_8859_1))); String query = request.getQuery(); String path = request.getPath(); String uri = (query == null) ? path : path + "?" + query; - String A2 = request.getMethod() + ":" + uri; + String a2 = request.getMethod() + ":" + uri; if ("auth-int".equals(qop)) - A2 += ":" + toHexString(digester.digest(content)); - String hashA2 = toHexString(digester.digest(A2.getBytes(StandardCharsets.ISO_8859_1))); + a2 += ":" + toHexString(digester.digest(content)); + String hashA2 = toHexString(digester.digest(a2.getBytes(StandardCharsets.ISO_8859_1))); String nonceCount; String clientNonce; - String A3; + String a3; if (qop != null) { nonceCount = nextNonceCount(); clientNonce = newClientNonce(); - A3 = hashA1 + ":" + nonce + ":" + nonceCount + ":" + clientNonce + ":" + qop + ":" + hashA2; + a3 = hashA1 + ":" + nonce + ":" + nonceCount + ":" + clientNonce + ":" + qop + ":" + hashA2; } else { nonceCount = null; clientNonce = null; - A3 = hashA1 + ":" + nonce + ":" + hashA2; + a3 = hashA1 + ":" + nonce + ":" + hashA2; } - String hashA3 = toHexString(digester.digest(A3.getBytes(StandardCharsets.ISO_8859_1))); + String hashA3 = toHexString(digester.digest(a3.getBytes(StandardCharsets.ISO_8859_1))); StringBuilder value = new StringBuilder("Digest"); value.append(" username=\"").append(user).append("\""); diff --git a/jetty-client/src/main/java/org/eclipse/jetty/client/util/MultiPartContentProvider.java b/jetty-client/src/main/java/org/eclipse/jetty/client/util/MultiPartContentProvider.java index 1c223fecb84..e6441371d57 100644 --- a/jetty-client/src/main/java/org/eclipse/jetty/client/util/MultiPartContentProvider.java +++ b/jetty-client/src/main/java/org/eclipse/jetty/client/util/MultiPartContentProvider.java @@ -115,10 +115,10 @@ public class MultiPartContentProvider extends AbstractTypedContentProvider imple * {@code content} as part content.

    *

    The {@code Content-Type} of this part will be obtained from:

    *
      - *
    • the {@code Content-Type} header in the {@code fields} parameter; otherwise
    • - *
    • the {@link org.eclipse.jetty.client.api.ContentProvider.Typed#getContentType()} method if the {@code content} parameter - * implements {@link org.eclipse.jetty.client.api.ContentProvider.Typed}; otherwise
    • - *
    • "text/plain"
    • + *
    • the {@code Content-Type} header in the {@code fields} parameter; otherwise
    • + *
    • the {@link org.eclipse.jetty.client.api.ContentProvider.Typed#getContentType()} method if the {@code content} parameter + * implements {@link org.eclipse.jetty.client.api.ContentProvider.Typed}; otherwise
    • + *
    • "text/plain"
    • *
    * * @param name the part name @@ -135,10 +135,10 @@ public class MultiPartContentProvider extends AbstractTypedContentProvider imple * {@code fileName} as file name, and the given {@code content} as part content.

    *

    The {@code Content-Type} of this part will be obtained from:

    *
      - *
    • the {@code Content-Type} header in the {@code fields} parameter; otherwise
    • - *
    • the {@link org.eclipse.jetty.client.api.ContentProvider.Typed#getContentType()} method if the {@code content} parameter - * implements {@link org.eclipse.jetty.client.api.ContentProvider.Typed}; otherwise
    • - *
    • "application/octet-stream"
    • + *
    • the {@code Content-Type} header in the {@code fields} parameter; otherwise
    • + *
    • the {@link org.eclipse.jetty.client.api.ContentProvider.Typed#getContentType()} method if the {@code content} parameter + * implements {@link org.eclipse.jetty.client.api.ContentProvider.Typed}; otherwise
    • + *
    • "application/octet-stream"
    • *
    * * @param name the part name @@ -289,12 +289,12 @@ public class MultiPartContentProvider extends AbstractTypedContentProvider imple public String toString() { return String.format("%s@%x[name=%s,fileName=%s,length=%d,headers=%s]", - getClass().getSimpleName(), - hashCode(), - name, - fileName, - content.getLength(), - fields); + getClass().getSimpleName(), + hashCode(), + name, + fileName, + content.getLength(), + fields); } } diff --git a/jetty-client/src/main/java/org/eclipse/jetty/client/util/OutputStreamContentProvider.java b/jetty-client/src/main/java/org/eclipse/jetty/client/util/OutputStreamContentProvider.java index a56b472a52b..096c4a85c17 100644 --- a/jetty-client/src/main/java/org/eclipse/jetty/client/util/OutputStreamContentProvider.java +++ b/jetty-client/src/main/java/org/eclipse/jetty/client/util/OutputStreamContentProvider.java @@ -29,7 +29,6 @@ import org.eclipse.jetty.client.api.ContentProvider; import org.eclipse.jetty.client.api.Request; import org.eclipse.jetty.client.api.Response; import org.eclipse.jetty.util.Callback; -import org.eclipse.jetty.util.thread.Invocable.InvocationType; /** * A {@link ContentProvider} that provides content asynchronously through an {@link OutputStream} @@ -84,7 +83,7 @@ public class OutputStreamContentProvider implements AsyncContentProvider, Callba { return deferred.getInvocationType(); } - + @Override public long getLength() { diff --git a/jetty-client/src/main/java/org/eclipse/jetty/client/util/PathContentProvider.java b/jetty-client/src/main/java/org/eclipse/jetty/client/util/PathContentProvider.java index 720b7cd99c7..aa562e5111b 100644 --- a/jetty-client/src/main/java/org/eclipse/jetty/client/util/PathContentProvider.java +++ b/jetty-client/src/main/java/org/eclipse/jetty/client/util/PathContentProvider.java @@ -126,9 +126,9 @@ public class PathContentProvider extends AbstractTypedContentProvider { if (channel == null) { - buffer = bufferPool == null ? - ByteBuffer.allocateDirect(bufferSize) : - bufferPool.acquire(bufferSize, true); + buffer = bufferPool == null + ? ByteBuffer.allocateDirect(bufferSize) + : bufferPool.acquire(bufferSize, true); channel = Files.newByteChannel(filePath, StandardOpenOption.READ); if (LOG.isDebugEnabled()) LOG.debug("Opened file {}", filePath); diff --git a/jetty-client/src/main/java/org/eclipse/jetty/client/util/SPNEGOAuthentication.java b/jetty-client/src/main/java/org/eclipse/jetty/client/util/SPNEGOAuthentication.java index 9e7add21783..b8dc609f011 100644 --- a/jetty-client/src/main/java/org/eclipse/jetty/client/util/SPNEGOAuthentication.java +++ b/jetty-client/src/main/java/org/eclipse/jetty/client/util/SPNEGOAuthentication.java @@ -26,7 +26,6 @@ import java.util.Arrays; import java.util.Base64; import java.util.HashMap; import java.util.Map; - import javax.security.auth.Subject; import javax.security.auth.callback.Callback; import javax.security.auth.callback.CallbackHandler; @@ -332,11 +331,11 @@ public class SPNEGOAuthentication extends AbstractAuthentication public void handle(Callback[] callbacks) throws IOException { PasswordCallback callback = Arrays.stream(callbacks) - .filter(PasswordCallback.class::isInstance) - .map(PasswordCallback.class::cast) - .findAny() - .filter(c -> c.getPrompt().contains(getUserName())) - .orElseThrow(IOException::new); + .filter(PasswordCallback.class::isInstance) + .map(PasswordCallback.class::cast) + .findAny() + .filter(c -> c.getPrompt().contains(getUserName())) + .orElseThrow(IOException::new); callback.setPassword(getUserPassword().toCharArray()); } } diff --git a/jetty-client/src/test/java/org/eclipse/jetty/client/AbstractHttpClientServerTest.java b/jetty-client/src/test/java/org/eclipse/jetty/client/AbstractHttpClientServerTest.java index d5c7218362f..6aae24e7b0e 100644 --- a/jetty-client/src/test/java/org/eclipse/jetty/client/AbstractHttpClientServerTest.java +++ b/jetty-client/src/test/java/org/eclipse/jetty/client/AbstractHttpClientServerTest.java @@ -120,9 +120,9 @@ public abstract class AbstractHttpClientServerTest public Stream provideArguments(ExtensionContext context) { return Stream.of( - new NormalScenario(), - new SslScenario() - // TODO: add more ssl / non-ssl scenarios here + new NormalScenario(), + new SslScenario() + // TODO: add more ssl / non-ssl scenarios here ).map(Arguments::of); } } @@ -133,8 +133,8 @@ public abstract class AbstractHttpClientServerTest public Stream provideArguments(ExtensionContext context) { return Stream.of( - new NormalScenario() - // TODO: add more non-ssl scenarios here + new NormalScenario() + // TODO: add more non-ssl scenarios here ).map(Arguments::of); } } diff --git a/jetty-client/src/test/java/org/eclipse/jetty/client/ClientConnectionCloseTest.java b/jetty-client/src/test/java/org/eclipse/jetty/client/ClientConnectionCloseTest.java index 0ed5dcf2d7d..ca6137238f4 100644 --- a/jetty-client/src/test/java/org/eclipse/jetty/client/ClientConnectionCloseTest.java +++ b/jetty-client/src/test/java/org/eclipse/jetty/client/ClientConnectionCloseTest.java @@ -23,7 +23,6 @@ import java.io.InterruptedIOException; import java.nio.ByteBuffer; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; - import javax.servlet.ServletException; import javax.servlet.ServletInputStream; import javax.servlet.http.HttpServletRequest; @@ -90,15 +89,15 @@ public class ClientConnectionCloseTest extends AbstractHttpClientServerTest DuplexConnectionPool connectionPool = (DuplexConnectionPool)destination.getConnectionPool(); ContentResponse response = client.newRequest(host, port) - .scheme(scenario.getScheme()) - .header(HttpHeader.CONNECTION, HttpHeaderValue.CLOSE.asString()) - .content(new StringContentProvider("0")) - .onRequestSuccess(request -> - { - HttpConnectionOverHTTP connection = (HttpConnectionOverHTTP)connectionPool.getActiveConnections().iterator().next(); - assertFalse(connection.getEndPoint().isOutputShutdown()); - }) - .send(); + .scheme(scenario.getScheme()) + .header(HttpHeader.CONNECTION, HttpHeaderValue.CLOSE.asString()) + .content(new StringContentProvider("0")) + .onRequestSuccess(request -> + { + HttpConnectionOverHTTP connection = (HttpConnectionOverHTTP)connectionPool.getActiveConnections().iterator().next(); + assertFalse(connection.getEndPoint().isOutputShutdown()); + }) + .send(); assertEquals(HttpStatus.OK_200, response.getStatus()); assertArrayEquals(data, response.getContent()); @@ -129,19 +128,19 @@ public class ClientConnectionCloseTest extends AbstractHttpClientServerTest CountDownLatch resultLatch = new CountDownLatch(1); long idleTimeout = 1000; client.newRequest(host, port) - .scheme(scenario.getScheme()) - .header(HttpHeader.CONNECTION, HttpHeaderValue.CLOSE.asString()) - .idleTimeout(idleTimeout, TimeUnit.MILLISECONDS) - .onRequestSuccess(request -> - { - HttpConnectionOverHTTP connection = (HttpConnectionOverHTTP)connectionPool.getActiveConnections().iterator().next(); - assertFalse(connection.getEndPoint().isOutputShutdown()); - }) - .send(result -> - { - if (result.isFailed()) - resultLatch.countDown(); - }); + .scheme(scenario.getScheme()) + .header(HttpHeader.CONNECTION, HttpHeaderValue.CLOSE.asString()) + .idleTimeout(idleTimeout, TimeUnit.MILLISECONDS) + .onRequestSuccess(request -> + { + HttpConnectionOverHTTP connection = (HttpConnectionOverHTTP)connectionPool.getActiveConnections().iterator().next(); + assertFalse(connection.getEndPoint().isOutputShutdown()); + }) + .send(result -> + { + if (result.isFailed()) + resultLatch.countDown(); + }); assertTrue(resultLatch.await(2 * idleTimeout, TimeUnit.MILLISECONDS)); assertEquals(0, connectionPool.getConnectionCount()); @@ -190,20 +189,20 @@ public class ClientConnectionCloseTest extends AbstractHttpClientServerTest DeferredContentProvider content = new DeferredContentProvider(ByteBuffer.allocate(8)); CountDownLatch resultLatch = new CountDownLatch(1); client.newRequest(host, port) - .scheme(scenario.getScheme()) - .header(HttpHeader.CONNECTION, HttpHeaderValue.CLOSE.asString()) - .content(content) - .idleTimeout(idleTimeout, TimeUnit.MILLISECONDS) - .onRequestSuccess(request -> - { - HttpConnectionOverHTTP connection = (HttpConnectionOverHTTP)connectionPool.getActiveConnections().iterator().next(); - assertFalse(connection.getEndPoint().isOutputShutdown()); - }) - .send(result -> - { - if (result.isFailed()) - resultLatch.countDown(); - }); + .scheme(scenario.getScheme()) + .header(HttpHeader.CONNECTION, HttpHeaderValue.CLOSE.asString()) + .content(content) + .idleTimeout(idleTimeout, TimeUnit.MILLISECONDS) + .onRequestSuccess(request -> + { + HttpConnectionOverHTTP connection = (HttpConnectionOverHTTP)connectionPool.getActiveConnections().iterator().next(); + assertFalse(connection.getEndPoint().isOutputShutdown()); + }) + .send(result -> + { + if (result.isFailed()) + resultLatch.countDown(); + }); content.offer(ByteBuffer.allocate(8)); content.close(); @@ -243,15 +242,15 @@ public class ClientConnectionCloseTest extends AbstractHttpClientServerTest DuplexConnectionPool connectionPool = (DuplexConnectionPool)destination.getConnectionPool(); ContentResponse response = client.newRequest(host, port) - .scheme(scenario.getScheme()) - .header(HttpHeader.CONNECTION, HttpHeaderValue.CLOSE.asString()) - .onRequestSuccess(request -> - { - HttpConnectionOverHTTP connection = (HttpConnectionOverHTTP)connectionPool.getActiveConnections().iterator().next(); - assertFalse(connection.getEndPoint().isOutputShutdown()); - }) - .onResponseHeaders(r -> r.getHeaders().remove(HttpHeader.CONNECTION)) - .send(); + .scheme(scenario.getScheme()) + .header(HttpHeader.CONNECTION, HttpHeaderValue.CLOSE.asString()) + .onRequestSuccess(request -> + { + HttpConnectionOverHTTP connection = (HttpConnectionOverHTTP)connectionPool.getActiveConnections().iterator().next(); + assertFalse(connection.getEndPoint().isOutputShutdown()); + }) + .onResponseHeaders(r -> r.getHeaders().remove(HttpHeader.CONNECTION)) + .send(); assertEquals(HttpStatus.OK_200, response.getStatus()); assertEquals(0, connectionPool.getConnectionCount()); diff --git a/jetty-client/src/test/java/org/eclipse/jetty/client/ConnectionPoolTest.java b/jetty-client/src/test/java/org/eclipse/jetty/client/ConnectionPoolTest.java index 7dece557831..39eb9c52f62 100644 --- a/jetty-client/src/test/java/org/eclipse/jetty/client/ConnectionPoolTest.java +++ b/jetty-client/src/test/java/org/eclipse/jetty/client/ConnectionPoolTest.java @@ -27,7 +27,6 @@ import java.util.concurrent.ThreadLocalRandom; import java.util.concurrent.TimeUnit; import java.util.stream.IntStream; import java.util.stream.Stream; - import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; @@ -62,12 +61,16 @@ public class ConnectionPoolTest public static Stream pools() { List pools = new ArrayList<>(); - pools.add(new Object[] { DuplexConnectionPool.class, - (ConnectionPool.Factory) - destination -> new DuplexConnectionPool(destination, 8, destination)}); - pools.add(new Object[] { RoundRobinConnectionPool.class, - (ConnectionPool.Factory) - destination -> new RoundRobinConnectionPool(destination, 8, destination)}); + pools.add(new Object[]{ + DuplexConnectionPool.class, + (ConnectionPool.Factory) + destination -> new DuplexConnectionPool(destination, 8, destination) + }); + pools.add(new Object[]{ + RoundRobinConnectionPool.class, + (ConnectionPool.Factory) + destination -> new RoundRobinConnectionPool(destination, 8, destination) + }); return pools.stream().map(Arguments::of); } @@ -153,8 +156,8 @@ public class ConnectionPoolTest CountDownLatch latch = new CountDownLatch(parallelism * runs); List failures = new CopyOnWriteArrayList<>(); IntStream.range(0, parallelism).parallel().forEach(i -> - IntStream.range(0, runs).forEach(j -> - run(latch, iterations, failures))); + IntStream.range(0, runs).forEach(j -> + run(latch, iterations, failures))); assertTrue(latch.await(iterations, TimeUnit.SECONDS)); assertTrue(failures.isEmpty(), failures.toString()); } @@ -163,7 +166,9 @@ public class ConnectionPoolTest { long begin = System.nanoTime(); for (int i = 0; i < iterations; ++i) + { test(failures); + } long end = System.nanoTime(); long elapsed = TimeUnit.NANOSECONDS.toMillis(end - begin); System.err.printf("%d requests in %d ms, %.3f req/s%n", iterations, elapsed, elapsed > 0 ? iterations * 1000D / elapsed : -1D); @@ -193,8 +198,8 @@ public class ConnectionPoolTest private void test(HttpMethod method, boolean clientClose, boolean serverClose, int contentLength, List failures) { Request request = client.newRequest("localhost", connector.getLocalPort()) - .path("/") - .method(method); + .path("/") + .method(method); if (clientClose) request.header(HttpHeader.CONNECTION, "close"); diff --git a/jetty-client/src/test/java/org/eclipse/jetty/client/ContentResponseTest.java b/jetty-client/src/test/java/org/eclipse/jetty/client/ContentResponseTest.java index 43adc8bc0fe..8c230c80858 100644 --- a/jetty-client/src/test/java/org/eclipse/jetty/client/ContentResponseTest.java +++ b/jetty-client/src/test/java/org/eclipse/jetty/client/ContentResponseTest.java @@ -18,14 +18,9 @@ package org.eclipse.jetty.client; -import static org.junit.jupiter.api.Assertions.assertArrayEquals; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertNull; - import java.io.IOException; import java.util.Random; import java.util.concurrent.TimeUnit; - import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; @@ -37,6 +32,10 @@ import org.eclipse.jetty.server.handler.AbstractHandler; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.ArgumentsSource; +import static org.junit.jupiter.api.Assertions.assertArrayEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; + public class ContentResponseTest extends AbstractHttpClientServerTest { @ParameterizedTest @@ -56,9 +55,9 @@ public class ContentResponseTest extends AbstractHttpClientServerTest }); ContentResponse response = client.newRequest("localhost", connector.getLocalPort()) - .scheme(scenario.getScheme()) - .timeout(5, TimeUnit.SECONDS) - .send(); + .scheme(scenario.getScheme()) + .timeout(5, TimeUnit.SECONDS) + .send(); assertEquals(200, response.getStatus()); assertArrayEquals(content, response.getContent()); @@ -84,9 +83,9 @@ public class ContentResponseTest extends AbstractHttpClientServerTest }); ContentResponse response = client.newRequest("localhost", connector.getLocalPort()) - .scheme(scenario.getScheme()) - .timeout(5, TimeUnit.SECONDS) - .send(); + .scheme(scenario.getScheme()) + .timeout(5, TimeUnit.SECONDS) + .send(); assertEquals(200, response.getStatus()); assertEquals(content, response.getContentAsString()); @@ -114,9 +113,9 @@ public class ContentResponseTest extends AbstractHttpClientServerTest }); ContentResponse response = client.newRequest("localhost", connector.getLocalPort()) - .scheme(scenario.getScheme()) - .timeout(5, TimeUnit.SECONDS) - .send(); + .scheme(scenario.getScheme()) + .timeout(5, TimeUnit.SECONDS) + .send(); assertEquals(200, response.getStatus()); assertEquals(content, response.getContentAsString()); @@ -144,9 +143,9 @@ public class ContentResponseTest extends AbstractHttpClientServerTest }); ContentResponse response = client.newRequest("localhost", connector.getLocalPort()) - .scheme(scenario.getScheme()) - .timeout(5, TimeUnit.SECONDS) - .send(); + .scheme(scenario.getScheme()) + .timeout(5, TimeUnit.SECONDS) + .send(); assertEquals(200, response.getStatus()); assertEquals(content, response.getContentAsString()); diff --git a/jetty-client/src/test/java/org/eclipse/jetty/client/EmptyServerHandler.java b/jetty-client/src/test/java/org/eclipse/jetty/client/EmptyServerHandler.java index cc36ad4126c..1287ed445e1 100644 --- a/jetty-client/src/test/java/org/eclipse/jetty/client/EmptyServerHandler.java +++ b/jetty-client/src/test/java/org/eclipse/jetty/client/EmptyServerHandler.java @@ -19,7 +19,6 @@ package org.eclipse.jetty.client; import java.io.IOException; - import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; diff --git a/jetty-client/src/test/java/org/eclipse/jetty/client/ExternalSiteTest.java b/jetty-client/src/test/java/org/eclipse/jetty/client/ExternalSiteTest.java index aa72bcd3538..7be1119be48 100644 --- a/jetty-client/src/test/java/org/eclipse/jetty/client/ExternalSiteTest.java +++ b/jetty-client/src/test/java/org/eclipse/jetty/client/ExternalSiteTest.java @@ -118,22 +118,22 @@ public class ExternalSiteTest { final CountDownLatch latch = new CountDownLatch(3); client.newRequest(host, port) - .onResponseFailure((response, failure) -> latch.countDown()) - .send(new Response.Listener.Adapter() + .onResponseFailure((response, failure) -> latch.countDown()) + .send(new Response.Listener.Adapter() + { + @Override + public void onFailure(Response response, Throwable failure) { - @Override - public void onFailure(Response response, Throwable failure) - { - latch.countDown(); - } + latch.countDown(); + } - @Override - public void onComplete(Result result) - { - assertTrue(result.isFailed()); - latch.countDown(); - } - }); + @Override + public void onComplete(Result result) + { + assertTrue(result.isFailed()); + latch.countDown(); + } + }); assertTrue(latch.await(15, TimeUnit.SECONDS)); } } @@ -149,10 +149,10 @@ public class ExternalSiteTest assumeCanConnectTo(host, port); ContentResponse response = client.newRequest(host, port) - .scheme(HttpScheme.HTTPS.asString()) - .path("/twitter") - .timeout(15, TimeUnit.SECONDS) - .send(); + .scheme(HttpScheme.HTTPS.asString()) + .path("/twitter") + .timeout(15, TimeUnit.SECONDS) + .send(); assertEquals(200, response.getStatus()); } diff --git a/jetty-client/src/test/java/org/eclipse/jetty/client/HostnameVerificationTest.java b/jetty-client/src/test/java/org/eclipse/jetty/client/HostnameVerificationTest.java index c8e1d5feb3a..99614a56d2d 100644 --- a/jetty-client/src/test/java/org/eclipse/jetty/client/HostnameVerificationTest.java +++ b/jetty-client/src/test/java/org/eclipse/jetty/client/HostnameVerificationTest.java @@ -21,7 +21,6 @@ package org.eclipse.jetty.client; import java.io.IOException; import java.security.cert.CertificateException; import java.util.concurrent.ExecutionException; - import javax.net.ssl.SSLHandshakeException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; @@ -117,7 +116,7 @@ public class HostnameVerificationTest clientSslContextFactory.setEndpointIdentificationAlgorithm("HTTPS"); String uri = "https://localhost:" + connector.getLocalPort() + "/"; - ExecutionException x = assertThrows(ExecutionException.class, ()-> client.GET(uri)); + ExecutionException x = assertThrows(ExecutionException.class, () -> client.GET(uri)); Throwable cause = x.getCause(); assertThat(cause, Matchers.instanceOf(SSLHandshakeException.class)); Throwable root = cause.getCause().getCause(); @@ -129,7 +128,6 @@ public class HostnameVerificationTest * work fine. * * @throws Exception on test failure - * */ @Test public void simpleGetWithHostnameVerificationDisabledTest() throws Exception diff --git a/jetty-client/src/test/java/org/eclipse/jetty/client/HttpAuthenticationStoreTest.java b/jetty-client/src/test/java/org/eclipse/jetty/client/HttpAuthenticationStoreTest.java index dbf8e0f9673..d775854090b 100644 --- a/jetty-client/src/test/java/org/eclipse/jetty/client/HttpAuthenticationStoreTest.java +++ b/jetty-client/src/test/java/org/eclipse/jetty/client/HttpAuthenticationStoreTest.java @@ -18,8 +18,6 @@ package org.eclipse.jetty.client; -import static org.junit.jupiter.api.Assertions.assertNotNull; - import java.net.URI; import org.eclipse.jetty.client.api.Authentication; @@ -27,9 +25,10 @@ import org.eclipse.jetty.client.api.AuthenticationStore; import org.eclipse.jetty.client.api.Request; import org.eclipse.jetty.client.util.BasicAuthentication; import org.eclipse.jetty.client.util.DigestAuthentication; - import org.junit.jupiter.api.Test; +import static org.junit.jupiter.api.Assertions.assertNotNull; + public class HttpAuthenticationStoreTest { @Test diff --git a/jetty-client/src/test/java/org/eclipse/jetty/client/HttpClientAsyncContentTest.java b/jetty-client/src/test/java/org/eclipse/jetty/client/HttpClientAsyncContentTest.java index b1f3bb78988..ee980f6dc47 100644 --- a/jetty-client/src/test/java/org/eclipse/jetty/client/HttpClientAsyncContentTest.java +++ b/jetty-client/src/test/java/org/eclipse/jetty/client/HttpClientAsyncContentTest.java @@ -18,16 +18,12 @@ package org.eclipse.jetty.client; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertTrue; - import java.io.IOException; import java.nio.ByteBuffer; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicReference; - import javax.servlet.ServletException; import javax.servlet.ServletOutputStream; import javax.servlet.http.HttpServletRequest; @@ -41,6 +37,9 @@ import org.eclipse.jetty.util.Callback; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.ArgumentsSource; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + public class HttpClientAsyncContentTest extends AbstractHttpClientServerTest { @ParameterizedTest @@ -64,25 +63,25 @@ public class HttpClientAsyncContentTest extends AbstractHttpClientServerTest final AtomicReference contentLatch = new AtomicReference<>(new CountDownLatch(1)); final CountDownLatch completeLatch = new CountDownLatch(1); client.newRequest("localhost", connector.getLocalPort()) - .scheme(scenario.getScheme()) - .onResponseContentAsync(new Response.AsyncContentListener() + .scheme(scenario.getScheme()) + .onResponseContentAsync(new Response.AsyncContentListener() + { + @Override + public void onContent(Response response, ByteBuffer content, Callback callback) { - @Override - public void onContent(Response response, ByteBuffer content, Callback callback) - { - contentCount.incrementAndGet(); - callbackRef.set(callback); - contentLatch.get().countDown(); - } - }) - .send(new Response.CompleteListener() + contentCount.incrementAndGet(); + callbackRef.set(callback); + contentLatch.get().countDown(); + } + }) + .send(new Response.CompleteListener() + { + @Override + public void onComplete(Result result) { - @Override - public void onComplete(Result result) - { - completeLatch.countDown(); - } - }); + completeLatch.countDown(); + } + }); assertTrue(contentLatch.get().await(5, TimeUnit.SECONDS)); Callback callback = callbackRef.get(); diff --git a/jetty-client/src/test/java/org/eclipse/jetty/client/HttpClientAuthenticationTest.java b/jetty-client/src/test/java/org/eclipse/jetty/client/HttpClientAuthenticationTest.java index 672b6272501..2a732d2b92f 100644 --- a/jetty-client/src/test/java/org/eclipse/jetty/client/HttpClientAuthenticationTest.java +++ b/jetty-client/src/test/java/org/eclipse/jetty/client/HttpClientAuthenticationTest.java @@ -31,7 +31,6 @@ import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicReference; import java.util.function.IntFunction; - import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; @@ -260,10 +259,10 @@ public class HttpClientAuthenticationTest extends AbstractHttpClientServerTest client.getRequestListeners().add(requestListener); ContentResponse response = client.newRequest("localhost", connector.getLocalPort()) - .scheme(scenario.getScheme()) - .path("/secure") - .timeout(5, TimeUnit.SECONDS) - .send(); + .scheme(scenario.getScheme()) + .path("/secure") + .timeout(5, TimeUnit.SECONDS) + .send(); assertNotNull(response); assertEquals(200, response.getStatus()); assertTrue(requests.await(5, TimeUnit.SECONDS)); @@ -299,10 +298,10 @@ public class HttpClientAuthenticationTest extends AbstractHttpClientServerTest client.getRequestListeners().add(requestListener); ContentResponse response = client.newRequest("localhost", connector.getLocalPort()) - .scheme(scenario.getScheme()) - .path("/redirect") - .timeout(5, TimeUnit.SECONDS) - .send(); + .scheme(scenario.getScheme()) + .path("/redirect") + .timeout(5, TimeUnit.SECONDS) + .send(); assertNotNull(response); assertEquals(200, response.getStatus()); assertTrue(requests.await(5, TimeUnit.SECONDS)); @@ -405,15 +404,15 @@ public class HttpClientAuthenticationTest extends AbstractHttpClientServerTest final CountDownLatch latch = new CountDownLatch(1); client.newRequest("localhost", connector.getLocalPort()) - .scheme(scenario.getScheme()) - .path("/secure") - .timeout(5, TimeUnit.SECONDS) - .send(result -> - { - assertTrue(result.isFailed()); - assertEquals(cause, result.getFailure().getMessage()); - latch.countDown(); - }); + .scheme(scenario.getScheme()) + .path("/secure") + .timeout(5, TimeUnit.SECONDS) + .send(result -> + { + assertTrue(result.isFailed()); + assertEquals(cause, result.getFailure().getMessage()); + latch.countDown(); + }); assertTrue(latch.await(5, TimeUnit.SECONDS)); } @@ -439,10 +438,10 @@ public class HttpClientAuthenticationTest extends AbstractHttpClientServerTest }); ContentResponse response = client.newRequest("localhost", connector.getLocalPort()) - .scheme(scenario.getScheme()) - .path("/secure") - .timeout(5, TimeUnit.SECONDS) - .send(); + .scheme(scenario.getScheme()) + .path("/secure") + .timeout(5, TimeUnit.SECONDS) + .send(); assertEquals(200, response.getStatus()); assertEquals(1, requests.get()); @@ -470,8 +469,8 @@ public class HttpClientAuthenticationTest extends AbstractHttpClientServerTest } }; Request request = client.newRequest(uri) - .path("/secure") - .content(content); + .path("/secure") + .content(content); request.send(result -> { if (result.isSucceeded() && result.getResponse().getStatus() == HttpStatus.UNAUTHORIZED_401) @@ -486,7 +485,7 @@ public class HttpClientAuthenticationTest extends AbstractHttpClientServerTest @ParameterizedTest @ArgumentsSource(ScenarioProvider.class) public void test_RequestFailsAfterResponse(Scenario scenario) throws Exception - { + { startBasic(scenario, new EmptyServerHandler() { @Override @@ -495,7 +494,7 @@ public class HttpClientAuthenticationTest extends AbstractHttpClientServerTest IO.readBytes(jettyRequest.getInputStream()); } }); - + CountDownLatch authLatch = new CountDownLatch(1); client.getProtocolHandlers().remove(WWWAuthenticationProtocolHandler.NAME); client.getProtocolHandlers().put(new WWWAuthenticationProtocolHandler(client) @@ -520,7 +519,7 @@ public class HttpClientAuthenticationTest extends AbstractHttpClientServerTest }; } }); - + AuthenticationStore authenticationStore = client.getAuthenticationStore(); URI uri = URI.create(scenario.getScheme() + "://localhost:" + connector.getLocalPort()); @@ -544,10 +543,10 @@ public class HttpClientAuthenticationTest extends AbstractHttpClientServerTest { authLatch.await(); } - catch(InterruptedException ignored) + catch (InterruptedException ignored) { } - + // Trigger request failure. throw new RuntimeException(); } @@ -555,22 +554,22 @@ public class HttpClientAuthenticationTest extends AbstractHttpClientServerTest { return null; } - + default: throw new IllegalStateException(); } }); CountDownLatch resultLatch = new CountDownLatch(1); client.newRequest("localhost", connector.getLocalPort()) - .scheme(scenario.getScheme()) - .path("/secure") - .content(content) - .onResponseSuccess(r->authLatch.countDown()) - .send(result -> - { - if (result.isSucceeded() && result.getResponse().getStatus() == HttpStatus.OK_200) - resultLatch.countDown(); - }); + .scheme(scenario.getScheme()) + .path("/secure") + .content(content) + .onResponseSuccess(r -> authLatch.countDown()) + .send(result -> + { + if (result.isSucceeded() && result.getResponse().getStatus() == HttpStatus.OK_200) + resultLatch.countDown(); + }); assertTrue(resultLatch.await(5, TimeUnit.SECONDS)); } @@ -622,14 +621,15 @@ public class HttpClientAuthenticationTest extends AbstractHttpClientServerTest }); ContentResponse response = client.newRequest("localhost", connector.getLocalPort()) - .scheme(scenario.getScheme()) - .send(); + .scheme(scenario.getScheme()) + .send(); assertEquals(HttpStatus.UNAUTHORIZED_401, response.getStatus()); } @Test - public void testTestHeaderInfoParsing() { + public void testTestHeaderInfoParsing() + { AuthenticationProtocolHandler aph = new WWWAuthenticationProtocolHandler(client); HeaderInfo headerInfo = aph.getHeaderInfo("Digest realm=\"thermostat\", qop=\"auth\", nonce=\"1523430383\"").get(0); @@ -658,9 +658,9 @@ public class HttpClientAuthenticationTest extends AbstractHttpClientServerTest // test multiple authentications List headerInfoList = aph.getHeaderInfo("Digest qop=\"auth\", realm=\"thermostat\", nonce=\"1523430383\", " - + "Digest realm=\"thermostat2\", qop=\"auth2\", nonce=\"4522530354\", " - + "Digest qop=\"auth3\", nonce=\"9523570528\", realm=\"thermostat3\", " - + "Digest qop=\"auth4\", nonce=\"3526435321\""); + + "Digest realm=\"thermostat2\", qop=\"auth2\", nonce=\"4522530354\", " + + "Digest qop=\"auth3\", nonce=\"9523570528\", realm=\"thermostat3\", " + + "Digest qop=\"auth4\", nonce=\"3526435321\""); assertTrue(headerInfoList.get(0).getType().equalsIgnoreCase("Digest")); assertEquals("auth", headerInfoList.get(0).getParameter("qop")); @@ -687,14 +687,15 @@ public class HttpClientAuthenticationTest extends AbstractHttpClientServerTest assertEquals("apps", headerInfos.get(0).getParameter("realm")); assertEquals("1", headerInfos.get(0).getParameter("type")); - assertEquals(headerInfos.get(0).getParameter("title"),"Login to \"apps\""); + assertEquals(headerInfos.get(0).getParameter("title"), "Login to \"apps\""); assertTrue(headerInfos.get(1).getType().equalsIgnoreCase("Basic")); assertEquals("simple", headerInfos.get(1).getParameter("realm")); } @Test - public void testTestHeaderInfoParsingUnusualCases() { + public void testTestHeaderInfoParsingUnusualCases() + { AuthenticationProtocolHandler aph = new WWWAuthenticationProtocolHandler(client); HeaderInfo headerInfo = aph.getHeaderInfo("Scheme").get(0); @@ -744,7 +745,7 @@ public class HttpClientAuthenticationTest extends AbstractHttpClientServerTest assertEquals("TlRMTVNTUAABAAAAB4IIogAAAAAAAAAAAAAAAAAAAAAFAs4OAAAADw==", headerInfo.getBase64()); headerInfos = aph.getHeaderInfo("Negotiate TlRMTVNTUAABAAAAAAAAAFAs4OAAAADw==, " - + "Negotiate YIIJvwYGKwYBBQUCoIIJszCCCa+gJDAi="); + + "Negotiate YIIJvwYGKwYBBQUCoIIJszCCCa+gJDAi="); assertTrue(headerInfos.get(0).getType().equalsIgnoreCase("Negotiate")); assertEquals("TlRMTVNTUAABAAAAAAAAAFAs4OAAAADw==", headerInfos.get(0).getBase64()); @@ -766,8 +767,8 @@ public class HttpClientAuthenticationTest extends AbstractHttpClientServerTest // test multiple authentications List headerInfoList = aph.getHeaderInfo("Digest qop=\"=au=th=\", realm=\"=ther=mostat=\", nonce=\"=152343=0383=\", " - + "Digest realm=\"=thermostat2\", qop=\"=auth2\", nonce=\"=4522530354\", " - + "Digest qop=\"auth3=\", nonce=\"9523570528=\", realm=\"thermostat3=\", "); + + "Digest realm=\"=thermostat2\", qop=\"=auth2\", nonce=\"=4522530354\", " + + "Digest qop=\"auth3=\", nonce=\"9523570528=\", realm=\"thermostat3=\", "); assertTrue(headerInfoList.get(0).getType().equalsIgnoreCase("Digest")); assertEquals("=au=th=", headerInfoList.get(0).getParameter("qop")); diff --git a/jetty-client/src/test/java/org/eclipse/jetty/client/HttpClientChunkedContentTest.java b/jetty-client/src/test/java/org/eclipse/jetty/client/HttpClientChunkedContentTest.java index 289f78f52ab..f35bffdb027 100644 --- a/jetty-client/src/test/java/org/eclipse/jetty/client/HttpClientChunkedContentTest.java +++ b/jetty-client/src/test/java/org/eclipse/jetty/client/HttpClientChunkedContentTest.java @@ -18,9 +18,6 @@ package org.eclipse.jetty.client; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertTrue; - import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; @@ -40,9 +37,11 @@ import org.eclipse.jetty.client.util.FutureResponseListener; import org.eclipse.jetty.util.Callback; import org.eclipse.jetty.util.thread.QueuedThreadPool; import org.junit.jupiter.api.AfterEach; - import org.junit.jupiter.api.Test; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + public class HttpClientChunkedContentTest { private HttpClient client; @@ -75,24 +74,24 @@ public class HttpClientChunkedContentTest final AtomicReference resultRef = new AtomicReference<>(); final CountDownLatch completeLatch = new CountDownLatch(1); client.newRequest("localhost", server.getLocalPort()) - .timeout(5, TimeUnit.SECONDS) - .send(new Response.CompleteListener() + .timeout(5, TimeUnit.SECONDS) + .send(new Response.CompleteListener() + { + @Override + public void onComplete(Result result) { - @Override - public void onComplete(Result result) - { - resultRef.set(result); - completeLatch.countDown(); - } - }); + resultRef.set(result); + completeLatch.countDown(); + } + }); try (Socket socket = server.accept()) { consumeRequestHeaders(socket); OutputStream output = socket.getOutputStream(); - String headers = "" + - "HTTP/1.1 200 OK\r\n" + + String headers = + "HTTP/1.1 200 OK\r\n" + "Transfer-Encoding: chunked\r\n" + "\r\n"; output.write(headers.getBytes(StandardCharsets.UTF_8)); @@ -100,8 +99,8 @@ public class HttpClientChunkedContentTest Thread.sleep(1000); - String terminal = "" + - "0\r\n" + + String terminal = + "0\r\n" + "\r\n"; output.write(terminal.getBytes(StandardCharsets.UTF_8)); output.flush(); @@ -129,35 +128,35 @@ public class HttpClientChunkedContentTest final AtomicReference resultRef = new AtomicReference<>(); final CountDownLatch completeLatch = new CountDownLatch(1); client.newRequest("localhost", server.getLocalPort()) - .onResponseContentAsync(new Response.AsyncContentListener() + .onResponseContentAsync(new Response.AsyncContentListener() + { + @Override + public void onContent(Response response, ByteBuffer content, Callback callback) { - @Override - public void onContent(Response response, ByteBuffer content, Callback callback) - { - if (callbackRef.compareAndSet(null, callback)) - firstContentLatch.countDown(); - else - callback.succeeded(); - } - }) - .timeout(5, TimeUnit.SECONDS) - .send(new Response.CompleteListener() + if (callbackRef.compareAndSet(null, callback)) + firstContentLatch.countDown(); + else + callback.succeeded(); + } + }) + .timeout(5, TimeUnit.SECONDS) + .send(new Response.CompleteListener() + { + @Override + public void onComplete(Result result) { - @Override - public void onComplete(Result result) - { - resultRef.set(result); - completeLatch.countDown(); - } - }); + resultRef.set(result); + completeLatch.countDown(); + } + }); try (Socket socket = server.accept()) { consumeRequestHeaders(socket); OutputStream output = socket.getOutputStream(); - String response = "" + - "HTTP/1.1 200 OK\r\n" + + String response = + "HTTP/1.1 200 OK\r\n" + "Transfer-Encoding: chunked\r\n" + "\r\n" + "8\r\n" + @@ -182,7 +181,7 @@ public class HttpClientChunkedContentTest // Issue another request to be sure the connection is sane. Request request = client.newRequest("localhost", server.getLocalPort()) - .timeout(5, TimeUnit.SECONDS); + .timeout(5, TimeUnit.SECONDS); FutureResponseListener listener = new FutureResponseListener(request); request.send(listener); diff --git a/jetty-client/src/test/java/org/eclipse/jetty/client/HttpClientCustomProxyTest.java b/jetty-client/src/test/java/org/eclipse/jetty/client/HttpClientCustomProxyTest.java index 4dffe0b939b..ea4d68982ab 100644 --- a/jetty-client/src/test/java/org/eclipse/jetty/client/HttpClientCustomProxyTest.java +++ b/jetty-client/src/test/java/org/eclipse/jetty/client/HttpClientCustomProxyTest.java @@ -23,7 +23,6 @@ import java.nio.ByteBuffer; import java.util.Map; import java.util.concurrent.Executor; import java.util.concurrent.TimeUnit; - import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; @@ -107,8 +106,8 @@ public class HttpClientCustomProxyTest client.getProxyConfiguration().getProxies().add(new CAFEBABEProxy(new Origin.Address("localhost", proxyPort), false)); ContentResponse response = client.newRequest(serverHost, serverPort) - .timeout(5, TimeUnit.SECONDS) - .send(); + .timeout(5, TimeUnit.SECONDS) + .send(); assertEquals(status, response.getStatus()); } diff --git a/jetty-client/src/test/java/org/eclipse/jetty/client/HttpClientExplicitConnectionTest.java b/jetty-client/src/test/java/org/eclipse/jetty/client/HttpClientExplicitConnectionTest.java index ee3559261f2..762c002bf83 100644 --- a/jetty-client/src/test/java/org/eclipse/jetty/client/HttpClientExplicitConnectionTest.java +++ b/jetty-client/src/test/java/org/eclipse/jetty/client/HttpClientExplicitConnectionTest.java @@ -111,8 +111,8 @@ public class HttpClientExplicitConnectionTest extends AbstractHttpClientServerTe Connection connection = futureConnection.get(5, TimeUnit.SECONDS); CountDownLatch responseLatch = new CountDownLatch(1); Request request = client.newRequest(destination.getHost(), destination.getPort()) - .scheme(scenario.getScheme()) - .onResponseSuccess(response -> responseLatch.countDown()); + .scheme(scenario.getScheme()) + .onResponseSuccess(response -> responseLatch.countDown()); FutureResponseListener listener = new FutureResponseListener(request); connection.send(request, listener); diff --git a/jetty-client/src/test/java/org/eclipse/jetty/client/HttpClientFailureTest.java b/jetty-client/src/test/java/org/eclipse/jetty/client/HttpClientFailureTest.java index eada0ae3a5b..b3f2af246ad 100644 --- a/jetty-client/src/test/java/org/eclipse/jetty/client/HttpClientFailureTest.java +++ b/jetty-client/src/test/java/org/eclipse/jetty/client/HttpClientFailureTest.java @@ -87,7 +87,7 @@ public class HttpClientFailureTest client.start(); assertThrows(ExecutionException.class, () -> - client.newRequest("localhost", connector.getLocalPort()) + client.newRequest("localhost", connector.getLocalPort()) .onRequestHeaders(request -> connectionRef.get().getEndPoint().close()) .timeout(5, TimeUnit.SECONDS) .send()); @@ -120,18 +120,18 @@ public class HttpClientFailureTest final CountDownLatch completeLatch = new CountDownLatch(1); DeferredContentProvider content = new DeferredContentProvider(); client.newRequest("localhost", connector.getLocalPort()) - .onRequestCommit(request -> - { - connectionRef.get().getEndPoint().close(); - commitLatch.countDown(); - }) - .content(content) - .idleTimeout(2, TimeUnit.SECONDS) - .send(result -> - { - if (result.isFailed()) - completeLatch.countDown(); - }); + .onRequestCommit(request -> + { + connectionRef.get().getEndPoint().close(); + commitLatch.countDown(); + }) + .content(content) + .idleTimeout(2, TimeUnit.SECONDS) + .send(result -> + { + if (result.isFailed()) + completeLatch.countDown(); + }); assertTrue(commitLatch.await(5, TimeUnit.SECONDS)); final CountDownLatch contentLatch = new CountDownLatch(1); diff --git a/jetty-client/src/test/java/org/eclipse/jetty/client/HttpClientGZIPTest.java b/jetty-client/src/test/java/org/eclipse/jetty/client/HttpClientGZIPTest.java index acd6232cec0..6ec23d1c966 100644 --- a/jetty-client/src/test/java/org/eclipse/jetty/client/HttpClientGZIPTest.java +++ b/jetty-client/src/test/java/org/eclipse/jetty/client/HttpClientGZIPTest.java @@ -27,7 +27,6 @@ import java.util.Random; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; import java.util.zip.GZIPOutputStream; - import javax.servlet.ServletOutputStream; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; @@ -68,9 +67,9 @@ public class HttpClientGZIPTest extends AbstractHttpClientServerTest }); ContentResponse response = client.newRequest("localhost", connector.getLocalPort()) - .scheme(scenario.getScheme()) - .timeout(5, TimeUnit.SECONDS) - .send(); + .scheme(scenario.getScheme()) + .timeout(5, TimeUnit.SECONDS) + .send(); assertEquals(200, response.getStatus()); assertArrayEquals(data, response.getContent()); @@ -105,8 +104,8 @@ public class HttpClientGZIPTest extends AbstractHttpClientServerTest }); ContentResponse response = client.newRequest("localhost", connector.getLocalPort()) - .scheme(scenario.getScheme()) - .send(); + .scheme(scenario.getScheme()) + .send(); assertEquals(200, response.getStatus()); assertArrayEquals(data, response.getContent()); @@ -139,8 +138,8 @@ public class HttpClientGZIPTest extends AbstractHttpClientServerTest }); ContentResponse response = client.newRequest("localhost", connector.getLocalPort()) - .scheme(scenario.getScheme()) - .send(); + .scheme(scenario.getScheme()) + .send(); assertEquals(200, response.getStatus()); @@ -196,8 +195,8 @@ public class HttpClientGZIPTest extends AbstractHttpClientServerTest }); ContentResponse response = client.newRequest("localhost", connector.getLocalPort()) - .scheme(scenario.getScheme()) - .send(); + .scheme(scenario.getScheme()) + .send(); assertEquals(200, response.getStatus()); assertArrayEquals(data, response.getContent()); @@ -220,12 +219,12 @@ public class HttpClientGZIPTest extends AbstractHttpClientServerTest final CountDownLatch latch = new CountDownLatch(1); client.newRequest("localhost", connector.getLocalPort()) - .scheme(scenario.getScheme()) - .send(result -> - { - if (result.isFailed()) - latch.countDown(); - }); + .scheme(scenario.getScheme()) + .send(result -> + { + if (result.isFailed()) + latch.countDown(); + }); assertTrue(latch.await(5, TimeUnit.SECONDS)); } @@ -238,7 +237,9 @@ public class HttpClientGZIPTest extends AbstractHttpClientServerTest Random random = new Random(); byte[] content = new byte[1024 * 1024]; for (int i = 0; i < content.length; ++i) + { content[i] = (byte)digits.charAt(random.nextInt(digits.length())); + } start(scenario, new EmptyServerHandler() { @Override @@ -257,9 +258,9 @@ public class HttpClientGZIPTest extends AbstractHttpClientServerTest MappedByteBufferPool bufferPool = (MappedByteBufferPool)pool; ContentResponse response = client.newRequest("localhost", connector.getLocalPort()) - .scheme(scenario.getScheme()) - .timeout(5, TimeUnit.SECONDS) - .send(); + .scheme(scenario.getScheme()) + .timeout(5, TimeUnit.SECONDS) + .send(); assertEquals(HttpStatus.OK_200, response.getStatus()); assertArrayEquals(content, response.getContent()); diff --git a/jetty-client/src/test/java/org/eclipse/jetty/client/HttpClientProxyTest.java b/jetty-client/src/test/java/org/eclipse/jetty/client/HttpClientProxyTest.java index 781e1414554..605c4b7795e 100644 --- a/jetty-client/src/test/java/org/eclipse/jetty/client/HttpClientProxyTest.java +++ b/jetty-client/src/test/java/org/eclipse/jetty/client/HttpClientProxyTest.java @@ -68,9 +68,9 @@ public class HttpClientProxyTest extends AbstractHttpClientServerTest client.getProxyConfiguration().getProxies().add(new HttpProxy("localhost", proxyPort)); ContentResponse response = client.newRequest(serverHost, serverPort) - .scheme(scenario.getScheme()) - .timeout(5, TimeUnit.SECONDS) - .send(); + .scheme(scenario.getScheme()) + .timeout(5, TimeUnit.SECONDS) + .send(); assertEquals(status, response.getStatus()); } @@ -116,9 +116,9 @@ public class HttpClientProxyTest extends AbstractHttpClientServerTest client.getProxyConfiguration().getProxies().add(new HttpProxy(proxyHost, proxyPort)); ContentResponse response1 = client.newRequest(serverHost, serverPort) - .scheme(scenario.getScheme()) - .timeout(5, TimeUnit.SECONDS) - .send(); + .scheme(scenario.getScheme()) + .timeout(5, TimeUnit.SECONDS) + .send(); // No Authentication available => 407 assertEquals(HttpStatus.PROXY_AUTHENTICATION_REQUIRED_407, response1.getStatus()); @@ -137,9 +137,9 @@ public class HttpClientProxyTest extends AbstractHttpClientServerTest }); // ...and perform the request again => 407 + 204 ContentResponse response2 = client.newRequest(serverHost, serverPort) - .scheme(scenario.getScheme()) - .timeout(5, TimeUnit.SECONDS) - .send(); + .scheme(scenario.getScheme()) + .timeout(5, TimeUnit.SECONDS) + .send(); assertEquals(status, response2.getStatus()); assertEquals(2, requests.get()); @@ -147,9 +147,9 @@ public class HttpClientProxyTest extends AbstractHttpClientServerTest // Now the authentication result is cached => 204 requests.set(0); ContentResponse response3 = client.newRequest(serverHost, serverPort) - .scheme(scenario.getScheme()) - .timeout(5, TimeUnit.SECONDS) - .send(); + .scheme(scenario.getScheme()) + .timeout(5, TimeUnit.SECONDS) + .send(); assertEquals(status, response3.getStatus()); assertEquals(1, requests.get()); @@ -210,10 +210,10 @@ public class HttpClientProxyTest extends AbstractHttpClientServerTest client.getProxyConfiguration().getProxies().add(new HttpProxy(proxyHost, proxyPort)); ContentResponse response1 = client.newRequest(serverHost, serverPort) - .scheme(scenario.getScheme()) - .path("/proxy") - .timeout(5, TimeUnit.SECONDS) - .send(); + .scheme(scenario.getScheme()) + .path("/proxy") + .timeout(5, TimeUnit.SECONDS) + .send(); // No Authentication available => 407. assertEquals(HttpStatus.PROXY_AUTHENTICATION_REQUIRED_407, response1.getStatus()); @@ -232,10 +232,10 @@ public class HttpClientProxyTest extends AbstractHttpClientServerTest }); // ...and perform the request again => 407 + 302 + 204. ContentResponse response2 = client.newRequest(serverHost, serverPort) - .scheme(scenario.getScheme()) - .path("/proxy") - .timeout(5, TimeUnit.SECONDS) - .send(); + .scheme(scenario.getScheme()) + .path("/proxy") + .timeout(5, TimeUnit.SECONDS) + .send(); assertEquals(status, response2.getStatus()); assertEquals(3, requests.get()); @@ -243,10 +243,10 @@ public class HttpClientProxyTest extends AbstractHttpClientServerTest // Now the authentication result is cached => 204. requests.set(0); ContentResponse response3 = client.newRequest(serverHost, serverPort) - .scheme(scenario.getScheme()) - .path("/server") - .timeout(5, TimeUnit.SECONDS) - .send(); + .scheme(scenario.getScheme()) + .path("/server") + .timeout(5, TimeUnit.SECONDS) + .send(); assertEquals(status, response3.getStatus()); assertEquals(1, requests.get()); @@ -307,9 +307,9 @@ public class HttpClientProxyTest extends AbstractHttpClientServerTest }); // Make a request, expect 407 + 401 + 204. ContentResponse response1 = client.newRequest(serverHost, serverPort) - .scheme(scenario.getScheme()) - .timeout(5, TimeUnit.SECONDS) - .send(); + .scheme(scenario.getScheme()) + .timeout(5, TimeUnit.SECONDS) + .send(); assertEquals(status, response1.getStatus()); assertEquals(3, requests.get()); @@ -317,9 +317,9 @@ public class HttpClientProxyTest extends AbstractHttpClientServerTest // Make again the request, only the server authentication is cached, expect 407 + 204. requests.set(0); ContentResponse response2 = client.newRequest(serverHost, serverPort) - .scheme(scenario.getScheme()) - .timeout(5, TimeUnit.SECONDS) - .send(); + .scheme(scenario.getScheme()) + .timeout(5, TimeUnit.SECONDS) + .send(); assertEquals(status, response2.getStatus()); assertEquals(2, requests.get()); @@ -378,10 +378,10 @@ public class HttpClientProxyTest extends AbstractHttpClientServerTest }); // Make a request, expect 407 + 204. ContentResponse response1 = client.newRequest(serverHost, serverPort) - .scheme(scenario.getScheme()) - .header(HttpHeader.AUTHORIZATION, "Basic foobar") - .timeout(5, TimeUnit.SECONDS) - .send(); + .scheme(scenario.getScheme()) + .header(HttpHeader.AUTHORIZATION, "Basic foobar") + .timeout(5, TimeUnit.SECONDS) + .send(); assertEquals(status, response1.getStatus()); assertEquals(2, requests.get()); @@ -389,10 +389,10 @@ public class HttpClientProxyTest extends AbstractHttpClientServerTest // Make again the request, authentication is cached, expect 204. requests.set(0); ContentResponse response2 = client.newRequest(serverHost, serverPort) - .scheme(scenario.getScheme()) - .header(HttpHeader.AUTHORIZATION, "Basic foobar") - .timeout(5, TimeUnit.SECONDS) - .send(); + .scheme(scenario.getScheme()) + .header(HttpHeader.AUTHORIZATION, "Basic foobar") + .timeout(5, TimeUnit.SECONDS) + .send(); assertEquals(status, response2.getStatus()); assertEquals(1, requests.get()); diff --git a/jetty-client/src/test/java/org/eclipse/jetty/client/HttpClientRedirectTest.java b/jetty-client/src/test/java/org/eclipse/jetty/client/HttpClientRedirectTest.java index 8da2a30390b..6a6999d1282 100644 --- a/jetty-client/src/test/java/org/eclipse/jetty/client/HttpClientRedirectTest.java +++ b/jetty-client/src/test/java/org/eclipse/jetty/client/HttpClientRedirectTest.java @@ -29,7 +29,6 @@ import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicLong; - import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; @@ -65,10 +64,10 @@ public class HttpClientRedirectTest extends AbstractHttpClientServerTest start(scenario, new RedirectHandler()); Response response = client.newRequest("localhost", connector.getLocalPort()) - .scheme(scenario.getScheme()) - .path("/303/localhost/done") - .timeout(5, TimeUnit.SECONDS) - .send(); + .scheme(scenario.getScheme()) + .path("/303/localhost/done") + .timeout(5, TimeUnit.SECONDS) + .send(); assertNotNull(response); assertEquals(200, response.getStatus()); assertFalse(response.getHeaders().containsKey(HttpHeader.LOCATION.asString())); @@ -81,10 +80,10 @@ public class HttpClientRedirectTest extends AbstractHttpClientServerTest start(scenario, new RedirectHandler()); Response response = client.newRequest("localhost", connector.getLocalPort()) - .scheme(scenario.getScheme()) - .path("/303/localhost/302/localhost/done") - .timeout(5, TimeUnit.SECONDS) - .send(); + .scheme(scenario.getScheme()) + .path("/303/localhost/302/localhost/done") + .timeout(5, TimeUnit.SECONDS) + .send(); assertNotNull(response); assertEquals(200, response.getStatus()); assertFalse(response.getHeaders().containsKey(HttpHeader.LOCATION.asString())); @@ -97,10 +96,10 @@ public class HttpClientRedirectTest extends AbstractHttpClientServerTest start(scenario, new RedirectHandler()); Response response = client.newRequest("localhost", connector.getLocalPort()) - .scheme(scenario.getScheme()) - .path("/303/127.0.0.1/302/localhost/done") - .timeout(5, TimeUnit.SECONDS) - .send(); + .scheme(scenario.getScheme()) + .path("/303/127.0.0.1/302/localhost/done") + .timeout(5, TimeUnit.SECONDS) + .send(); assertNotNull(response); assertEquals(200, response.getStatus()); assertFalse(response.getHeaders().containsKey(HttpHeader.LOCATION.asString())); @@ -113,11 +112,11 @@ public class HttpClientRedirectTest extends AbstractHttpClientServerTest start(scenario, new RedirectHandler()); Response response = client.newRequest("localhost", connector.getLocalPort()) - .scheme(scenario.getScheme()) - .method(HttpMethod.HEAD) - .path("/301/localhost/done") - .timeout(5, TimeUnit.SECONDS) - .send(); + .scheme(scenario.getScheme()) + .method(HttpMethod.HEAD) + .path("/301/localhost/done") + .timeout(5, TimeUnit.SECONDS) + .send(); assertNotNull(response); assertEquals(200, response.getStatus()); assertFalse(response.getHeaders().containsKey(HttpHeader.LOCATION.asString())); @@ -130,12 +129,12 @@ public class HttpClientRedirectTest extends AbstractHttpClientServerTest start(scenario, new RedirectHandler()); ExecutionException x = assertThrows(ExecutionException.class, () -> - client.newRequest("localhost", connector.getLocalPort()) - .scheme(scenario.getScheme()) - .method(HttpMethod.DELETE) - .path("/301/localhost/done") - .timeout(5, TimeUnit.SECONDS) - .send()); + client.newRequest("localhost", connector.getLocalPort()) + .scheme(scenario.getScheme()) + .method(HttpMethod.DELETE) + .path("/301/localhost/done") + .timeout(5, TimeUnit.SECONDS) + .send()); HttpResponseException xx = (HttpResponseException)x.getCause(); Response response = xx.getResponse(); assertNotNull(response); @@ -151,12 +150,12 @@ public class HttpClientRedirectTest extends AbstractHttpClientServerTest byte[] data = new byte[]{0, 1, 2, 3, 4, 5, 6, 7}; ContentResponse response = client.newRequest("localhost", connector.getLocalPort()) - .scheme(scenario.getScheme()) - .method(HttpMethod.POST) - .path("/307/localhost/done") - .content(new ByteBufferContentProvider(ByteBuffer.wrap(data))) - .timeout(5, TimeUnit.SECONDS) - .send(); + .scheme(scenario.getScheme()) + .method(HttpMethod.POST) + .path("/307/localhost/done") + .content(new ByteBufferContentProvider(ByteBuffer.wrap(data))) + .timeout(5, TimeUnit.SECONDS) + .send(); assertNotNull(response); assertEquals(200, response.getStatus()); assertFalse(response.getHeaders().containsKey(HttpHeader.LOCATION.asString())); @@ -171,11 +170,11 @@ public class HttpClientRedirectTest extends AbstractHttpClientServerTest client.setMaxRedirects(1); ExecutionException x = assertThrows(ExecutionException.class, () -> - client.newRequest("localhost", connector.getLocalPort()) - .scheme(scenario.getScheme()) - .path("/303/localhost/302/localhost/done") - .timeout(5, TimeUnit.SECONDS) - .send()); + client.newRequest("localhost", connector.getLocalPort()) + .scheme(scenario.getScheme()) + .path("/303/localhost/302/localhost/done") + .timeout(5, TimeUnit.SECONDS) + .send()); HttpResponseException xx = (HttpResponseException)x.getCause(); Response response = xx.getResponse(); assertNotNull(response); @@ -190,10 +189,10 @@ public class HttpClientRedirectTest extends AbstractHttpClientServerTest start(scenario, new RedirectHandler()); Response response = client.newRequest("localhost", connector.getLocalPort()) - .scheme(scenario.getScheme()) - .path("/303/localhost/done?close=true") - .timeout(5, TimeUnit.SECONDS) - .send(); + .scheme(scenario.getScheme()) + .path("/303/localhost/done?close=true") + .timeout(5, TimeUnit.SECONDS) + .send(); assertNotNull(response); assertEquals(200, response.getStatus()); assertFalse(response.getHeaders().containsKey(HttpHeader.LOCATION.asString())); @@ -206,11 +205,11 @@ public class HttpClientRedirectTest extends AbstractHttpClientServerTest start(scenario, new RedirectHandler()); Response response = client.newRequest("localhost", connector.getLocalPort()) - .scheme(scenario.getScheme()) - .followRedirects(false) - .path("/303/localhost/done?close=true") - .timeout(5, TimeUnit.SECONDS) - .send(); + .scheme(scenario.getScheme()) + .followRedirects(false) + .path("/303/localhost/done?close=true") + .timeout(5, TimeUnit.SECONDS) + .send(); assertNotNull(response); assertEquals(303, response.getStatus()); assertTrue(response.getHeaders().containsKey(HttpHeader.LOCATION.asString())); @@ -223,10 +222,10 @@ public class HttpClientRedirectTest extends AbstractHttpClientServerTest start(scenario, new RedirectHandler()); Response response = client.newRequest("localhost", connector.getLocalPort()) - .scheme(scenario.getScheme()) - .path("/303/localhost/done?relative=true") - .timeout(5, TimeUnit.SECONDS) - .send(); + .scheme(scenario.getScheme()) + .path("/303/localhost/done?relative=true") + .timeout(5, TimeUnit.SECONDS) + .send(); assertNotNull(response); assertEquals(200, response.getStatus()); assertFalse(response.getHeaders().containsKey(HttpHeader.LOCATION.asString())); @@ -239,10 +238,10 @@ public class HttpClientRedirectTest extends AbstractHttpClientServerTest start(scenario, new RedirectHandler()); Response response = client.newRequest("localhost", connector.getLocalPort()) - .scheme(scenario.getScheme()) - .path("/303/localhost/a+space?decode=true") - .timeout(5, TimeUnit.SECONDS) - .send(); + .scheme(scenario.getScheme()) + .path("/303/localhost/a+space?decode=true") + .timeout(5, TimeUnit.SECONDS) + .send(); assertNotNull(response); assertEquals(200, response.getStatus()); assertFalse(response.getHeaders().containsKey(HttpHeader.LOCATION.asString())); @@ -255,10 +254,10 @@ public class HttpClientRedirectTest extends AbstractHttpClientServerTest start(scenario, new RedirectHandler()); Response response = client.newRequest("localhost", connector.getLocalPort()) - .scheme(scenario.getScheme()) - .path("/303/localhost/a+space?relative=true&decode=true") - .timeout(5, TimeUnit.SECONDS) - .send(); + .scheme(scenario.getScheme()) + .path("/303/localhost/a+space?relative=true&decode=true") + .timeout(5, TimeUnit.SECONDS) + .send(); assertNotNull(response); assertEquals(200, response.getStatus()); assertFalse(response.getHeaders().containsKey(HttpHeader.LOCATION.asString())); @@ -280,14 +279,14 @@ public class HttpClientRedirectTest extends AbstractHttpClientServerTest final CountDownLatch latch = new CountDownLatch(1); client.newRequest("localhost", connector.getLocalPort()) - .scheme(scenario.getScheme()) - .path("/path") - .timeout(5, TimeUnit.SECONDS) - .send(result -> - { - assertTrue(result.isFailed()); - latch.countDown(); - }); + .scheme(scenario.getScheme()) + .path("/path") + .timeout(5, TimeUnit.SECONDS) + .send(result -> + { + assertTrue(result.isFailed()); + latch.countDown(); + }); assertTrue(latch.await(5, TimeUnit.SECONDS)); } @@ -302,10 +301,10 @@ public class HttpClientRedirectTest extends AbstractHttpClientServerTest try { client.newRequest("localhost", connector.getLocalPort()) - .scheme(scenario.getScheme()) - .path("/303/doesNotExist/done") - .timeout(5, TimeUnit.SECONDS) - .send(); + .scheme(scenario.getScheme()) + .path("/303/doesNotExist/done") + .timeout(5, TimeUnit.SECONDS) + .send(); } catch (ExecutionException x) { @@ -405,10 +404,10 @@ public class HttpClientRedirectTest extends AbstractHttpClientServerTest final HttpRedirector redirector = new HttpRedirector(client); org.eclipse.jetty.client.api.Request request1 = client.newRequest("localhost", connector.getLocalPort()) - .scheme(scenario.getScheme()) - .path("/303/localhost/302/localhost/done") - .timeout(5, TimeUnit.SECONDS) - .followRedirects(false); + .scheme(scenario.getScheme()) + .path("/303/localhost/302/localhost/done") + .timeout(5, TimeUnit.SECONDS) + .followRedirects(false); ContentResponse response1 = request1.send(); assertEquals(303, response1.getStatus()); @@ -459,10 +458,10 @@ public class HttpClientRedirectTest extends AbstractHttpClientServerTest }); ContentResponse response = client.newRequest("localhost", connector.getLocalPort()) - .scheme(scenario.getScheme()) - .path("/redirect") - .timeout(5, TimeUnit.SECONDS) - .send(); + .scheme(scenario.getScheme()) + .path("/redirect") + .timeout(5, TimeUnit.SECONDS) + .send(); assertEquals(200, response.getStatus()); assertArrayEquals(bytes, response.getContent()); @@ -483,9 +482,9 @@ public class HttpClientRedirectTest extends AbstractHttpClientServerTest }); ExecutionException x = assertThrows(ExecutionException.class, () -> - client.newRequest("localhost", connector.getLocalPort()) - .scheme(scenario.getScheme()) - .send()); + client.newRequest("localhost", connector.getLocalPort()) + .scheme(scenario.getScheme()) + .send()); assertThat(x.getCause(), Matchers.instanceOf(HttpResponseException.class)); } @@ -516,9 +515,9 @@ public class HttpClientRedirectTest extends AbstractHttpClientServerTest { client.setMaxRedirects(-1); client.newRequest("localhost", connector.getLocalPort()) - .scheme(scenario.getScheme()) - .timeout(1, TimeUnit.SECONDS) - .send(); + .scheme(scenario.getScheme()) + .timeout(1, TimeUnit.SECONDS) + .send(); }); } @@ -561,11 +560,11 @@ public class HttpClientRedirectTest extends AbstractHttpClientServerTest }); ContentResponse response = client.newRequest("localhost", connector.getLocalPort()) - .scheme(scenario.getScheme()) - .method(requestMethod) - .path("/" + redirectCode + "/localhost/done") - .timeout(5, TimeUnit.SECONDS) - .send(); + .scheme(scenario.getScheme()) + .method(requestMethod) + .path("/" + redirectCode + "/localhost/done") + .timeout(5, TimeUnit.SECONDS) + .send(); assertEquals(200, response.getStatus()); } diff --git a/jetty-client/src/test/java/org/eclipse/jetty/client/HttpClientSynchronizationTest.java b/jetty-client/src/test/java/org/eclipse/jetty/client/HttpClientSynchronizationTest.java index 4834df9fa69..a0d8d24f267 100644 --- a/jetty-client/src/test/java/org/eclipse/jetty/client/HttpClientSynchronizationTest.java +++ b/jetty-client/src/test/java/org/eclipse/jetty/client/HttpClientSynchronizationTest.java @@ -18,10 +18,6 @@ package org.eclipse.jetty.client; -import static org.hamcrest.MatcherAssert.assertThat; -import static org.junit.jupiter.api.Assertions.assertFalse; -import static org.junit.jupiter.api.Assertions.assertTrue; - import java.net.ConnectException; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; @@ -33,6 +29,10 @@ import org.hamcrest.Matchers; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.ArgumentsSource; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; + /** * Verifies that synchronization performed from outside HttpClient does not cause deadlocks */ @@ -51,7 +51,7 @@ public class HttpClientSynchronizationTest extends AbstractHttpClientServerTest for (int i = 0; i < count; ++i) { Request request = client.newRequest("localhost", port) - .scheme(scenario.getScheme()); + .scheme(scenario.getScheme()); synchronized (this) { @@ -84,7 +84,7 @@ public class HttpClientSynchronizationTest extends AbstractHttpClientServerTest for (int i = 0; i < count; ++i) { Request request = client.newRequest("localhost", connector.getLocalPort()) - .scheme(scenario.getScheme()); + .scheme(scenario.getScheme()); synchronized (this) { diff --git a/jetty-client/src/test/java/org/eclipse/jetty/client/HttpClientTLSTest.java b/jetty-client/src/test/java/org/eclipse/jetty/client/HttpClientTLSTest.java index c37ba125586..de240b7bcd1 100644 --- a/jetty-client/src/test/java/org/eclipse/jetty/client/HttpClientTLSTest.java +++ b/jetty-client/src/test/java/org/eclipse/jetty/client/HttpClientTLSTest.java @@ -156,10 +156,10 @@ public class HttpClientTLSTest }); assertThrows(ExecutionException.class, () -> - client.newRequest("localhost", connector.getLocalPort()) - .scheme(HttpScheme.HTTPS.asString()) - .timeout(5, TimeUnit.SECONDS) - .send()); + client.newRequest("localhost", connector.getLocalPort()) + .scheme(HttpScheme.HTTPS.asString()) + .timeout(5, TimeUnit.SECONDS) + .send()); assertTrue(serverLatch.await(1, TimeUnit.SECONDS)); assertTrue(clientLatch.await(1, TimeUnit.SECONDS)); @@ -197,10 +197,10 @@ public class HttpClientTLSTest }); assertThrows(ExecutionException.class, () -> - client.newRequest("localhost", connector.getLocalPort()) - .scheme(HttpScheme.HTTPS.asString()) - .timeout(5, TimeUnit.SECONDS) - .send()); + client.newRequest("localhost", connector.getLocalPort()) + .scheme(HttpScheme.HTTPS.asString()) + .timeout(5, TimeUnit.SECONDS) + .send()); assertTrue(serverLatch.await(1, TimeUnit.SECONDS)); assertTrue(clientLatch.await(1, TimeUnit.SECONDS)); @@ -239,10 +239,10 @@ public class HttpClientTLSTest }); assertThrows(ExecutionException.class, () -> - client.newRequest("localhost", connector.getLocalPort()) - .scheme(HttpScheme.HTTPS.asString()) - .timeout(5, TimeUnit.SECONDS) - .send()); + client.newRequest("localhost", connector.getLocalPort()) + .scheme(HttpScheme.HTTPS.asString()) + .timeout(5, TimeUnit.SECONDS) + .send()); assertTrue(serverLatch.await(1, TimeUnit.SECONDS)); assertTrue(clientLatch.await(1, TimeUnit.SECONDS)); @@ -284,10 +284,10 @@ public class HttpClientTLSTest }); assertThrows(ExecutionException.class, () -> - client.newRequest("localhost", connector.getLocalPort()) - .scheme(HttpScheme.HTTPS.asString()) - .timeout(5, TimeUnit.SECONDS) - .send()); + client.newRequest("localhost", connector.getLocalPort()) + .scheme(HttpScheme.HTTPS.asString()) + .timeout(5, TimeUnit.SECONDS) + .send()); assertTrue(serverLatch.await(1, TimeUnit.SECONDS)); assertTrue(clientLatch.await(1, TimeUnit.SECONDS)); @@ -363,10 +363,10 @@ public class HttpClientTLSTest // First request primes the TLS session. ContentResponse response = client.newRequest("localhost", connector.getLocalPort()) - .scheme(HttpScheme.HTTPS.asString()) - .header(HttpHeader.CONNECTION, "close") - .timeout(5, TimeUnit.SECONDS) - .send(); + .scheme(HttpScheme.HTTPS.asString()) + .header(HttpHeader.CONNECTION, "close") + .timeout(5, TimeUnit.SECONDS) + .send(); assertEquals(HttpStatus.OK_200, response.getStatus()); assertNotNull(serverSession.get()); @@ -399,10 +399,10 @@ public class HttpClientTLSTest // Second request should have the same session ID. response = client.newRequest("localhost", connector.getLocalPort()) - .scheme(HttpScheme.HTTPS.asString()) - .header(HttpHeader.CONNECTION, "close") - .timeout(5, TimeUnit.SECONDS) - .send(); + .scheme(HttpScheme.HTTPS.asString()) + .header(HttpHeader.CONNECTION, "close") + .timeout(5, TimeUnit.SECONDS) + .send(); assertEquals(HttpStatus.OK_200, response.getStatus()); assertTrue(serverLatch.await(1, TimeUnit.SECONDS)); @@ -494,12 +494,12 @@ public class HttpClientTLSTest CountDownLatch latch = new CountDownLatch(1); client.newRequest("localhost", server.getLocalPort()) - .scheme(HttpScheme.HTTPS.asString()) - .send(result -> - { - assertThat(result.getResponseFailure(), instanceOf(SSLException.class)); - latch.countDown(); - }); + .scheme(HttpScheme.HTTPS.asString()) + .send(result -> + { + assertThat(result.getResponseFailure(), instanceOf(SSLException.class)); + latch.countDown(); + }); try (Socket socket = server.accept()) { @@ -526,8 +526,8 @@ public class HttpClientTLSTest byte[] half = new byte[8]; String response = "HTTP/1.1 200 OK\r\n" + // "Content-Length: " + (half.length * 2) + "\r\n" + - "Connection: close\r\n" + - "\r\n"; + "Connection: close\r\n" + + "\r\n"; OutputStream output = sslSocket.getOutputStream(); output.write(response.getBytes(StandardCharsets.UTF_8)); output.write(half); @@ -555,13 +555,13 @@ public class HttpClientTLSTest CountDownLatch latch = new CountDownLatch(1); client.newRequest("localhost", connector.getLocalPort()) - .scheme(HttpScheme.HTTPS.asString()) - .send(result -> - { - Throwable failure = result.getFailure(); - if (failure instanceof SSLPeerUnverifiedException) - latch.countDown(); - }); + .scheme(HttpScheme.HTTPS.asString()) + .send(result -> + { + Throwable failure = result.getFailure(); + if (failure instanceof SSLPeerUnverifiedException) + latch.countDown(); + }); assertTrue(latch.await(5, TimeUnit.SECONDS)); } diff --git a/jetty-client/src/test/java/org/eclipse/jetty/client/HttpClientTest.java b/jetty-client/src/test/java/org/eclipse/jetty/client/HttpClientTest.java index 2e665d669ff..cc21b0b9df7 100644 --- a/jetty-client/src/test/java/org/eclipse/jetty/client/HttpClientTest.java +++ b/jetty-client/src/test/java/org/eclipse/jetty/client/HttpClientTest.java @@ -250,7 +250,9 @@ public class HttpClientTest extends AbstractHttpClientServerTest ServletOutputStream output = response.getOutputStream(); String[] paramValues1 = request.getParameterValues(paramName1); for (String paramValue : paramValues1) + { output.write(paramValue.getBytes(StandardCharsets.UTF_8)); + } String paramValue2 = request.getParameter(paramName2); output.write(paramValue2.getBytes(StandardCharsets.UTF_8)); baseRequest.setHandled(true); @@ -295,9 +297,9 @@ public class HttpClientTest extends AbstractHttpClientServerTest }); ContentResponse response = client.POST(scenario.getScheme() + "://localhost:" + connector.getLocalPort()) - .param(paramName, paramValue) - .timeout(5, TimeUnit.SECONDS) - .send(); + .param(paramName, paramValue) + .timeout(5, TimeUnit.SECONDS) + .send(); assertNotNull(response); assertEquals(200, response.getStatus()); @@ -329,9 +331,9 @@ public class HttpClientTest extends AbstractHttpClientServerTest URI uri = URI.create(scenario.getScheme() + "://localhost:" + connector.getLocalPort() + "/path?" + paramName + "=" + encodedParamValue); ContentResponse response = client.newRequest(uri) - .method(HttpMethod.PUT) - .timeout(5, TimeUnit.SECONDS) - .send(); + .method(HttpMethod.PUT) + .timeout(5, TimeUnit.SECONDS) + .send(); assertNotNull(response); assertEquals(200, response.getStatus()); @@ -363,10 +365,10 @@ public class HttpClientTest extends AbstractHttpClientServerTest }); ContentResponse response = client.POST(scenario.getScheme() + "://localhost:" + connector.getLocalPort() + "/?b=1") - .param(paramName, paramValue) - .content(new BytesContentProvider(content)) - .timeout(5, TimeUnit.SECONDS) - .send(); + .param(paramName, paramValue) + .content(new BytesContentProvider(content)) + .timeout(5, TimeUnit.SECONDS) + .send(); assertNotNull(response); assertEquals(200, response.getStatus()); @@ -389,16 +391,16 @@ public class HttpClientTest extends AbstractHttpClientServerTest final byte[] content = {0, 1, 2, 3}; ContentResponse response = client.POST(scenario.getScheme() + "://localhost:" + connector.getLocalPort()) - .onRequestContent((request, buffer) -> - { - byte[] bytes = new byte[buffer.remaining()]; - buffer.get(bytes); - if (!Arrays.equals(content, bytes)) - request.abort(new Exception()); - }) - .content(new BytesContentProvider(content)) - .timeout(5, TimeUnit.SECONDS) - .send(); + .onRequestContent((request, buffer) -> + { + byte[] bytes = new byte[buffer.remaining()]; + buffer.get(bytes); + if (!Arrays.equals(content, bytes)) + request.abort(new Exception()); + }) + .content(new BytesContentProvider(content)) + .timeout(5, TimeUnit.SECONDS) + .send(); assertNotNull(response); assertEquals(200, response.getStatus()); @@ -420,16 +422,18 @@ public class HttpClientTest extends AbstractHttpClientServerTest final AtomicInteger progress = new AtomicInteger(); ContentResponse response = client.POST(scenario.getScheme() + "://localhost:" + connector.getLocalPort()) - .onRequestContent((request, buffer) -> - { - byte[] bytes = new byte[buffer.remaining()]; - assertEquals(1, bytes.length); - buffer.get(bytes); - assertEquals(bytes[0], progress.getAndIncrement()); - }) - .content(new BytesContentProvider(new byte[]{0}, new byte[]{1}, new byte[]{2}, new byte[]{3}, new byte[]{4})) - .timeout(5, TimeUnit.SECONDS) - .send(); + .onRequestContent((request, buffer) -> + { + byte[] bytes = new byte[buffer.remaining()]; + assertEquals(1, bytes.length); + buffer.get(bytes); + assertEquals(bytes[0], progress.getAndIncrement()); + }) + .content(new BytesContentProvider(new byte[]{0}, new byte[]{1}, new byte[]{ + 2 + }, new byte[]{3}, new byte[]{4})) + .timeout(5, TimeUnit.SECONDS) + .send(); assertNotNull(response); assertEquals(200, response.getStatus()); @@ -447,40 +451,40 @@ public class HttpClientTest extends AbstractHttpClientServerTest final CountDownLatch latch = new CountDownLatch(1); final CountDownLatch successLatch = new CountDownLatch(2); client.newRequest("localhost", connector.getLocalPort()) - .scheme(scenario.getScheme()) - .onRequestBegin(request -> + .scheme(scenario.getScheme()) + .onRequestBegin(request -> + { + try { - try - { - latch.await(); - } - catch (InterruptedException x) - { - x.printStackTrace(); - } - }) - .send(new Response.Listener.Adapter() + latch.await(); + } + catch (InterruptedException x) { - @Override - public void onSuccess(Response response) - { - assertEquals(200, response.getStatus()); - successLatch.countDown(); - } - }); + x.printStackTrace(); + } + }) + .send(new Response.Listener.Adapter() + { + @Override + public void onSuccess(Response response) + { + assertEquals(200, response.getStatus()); + successLatch.countDown(); + } + }); client.newRequest("localhost", connector.getLocalPort()) - .scheme(scenario.getScheme()) - .onRequestQueued(request -> latch.countDown()) - .send(new Response.Listener.Adapter() + .scheme(scenario.getScheme()) + .onRequestQueued(request -> latch.countDown()) + .send(new Response.Listener.Adapter() + { + @Override + public void onSuccess(Response response) { - @Override - public void onSuccess(Response response) - { - assertEquals(200, response.getStatus()); - successLatch.countDown(); - } - }); + assertEquals(200, response.getStatus()); + successLatch.countDown(); + } + }); assertTrue(successLatch.await(5, TimeUnit.SECONDS)); } @@ -507,20 +511,20 @@ public class HttpClientTest extends AbstractHttpClientServerTest { final CountDownLatch latch = new CountDownLatch(2); client.newRequest("localhost", connector.getLocalPort()) - .scheme(scenario.getScheme()) - .path("/one") - .onResponseFailure((response, failure) -> latch.countDown()) - .send(null); + .scheme(scenario.getScheme()) + .path("/one") + .onResponseFailure((response, failure) -> latch.countDown()) + .send(null); client.newRequest("localhost", connector.getLocalPort()) - .scheme(scenario.getScheme()) - .path("/two") - .onResponseSuccess(response -> - { - assertEquals(200, response.getStatus()); - latch.countDown(); - }) - .send(null); + .scheme(scenario.getScheme()) + .path("/two") + .onResponseSuccess(response -> + { + assertEquals(200, response.getStatus()); + latch.countDown(); + }) + .send(null); assertTrue(latch.await(5, TimeUnit.SECONDS)); } @@ -530,7 +534,7 @@ public class HttpClientTest extends AbstractHttpClientServerTest @ArgumentsSource(ScenarioProvider.class) public void test_ExchangeIsComplete_OnlyWhenBothRequestAndResponseAreComplete(Scenario scenario) throws Exception { - start(scenario,new AbstractHandler.ErrorDispatchHandler() + start(scenario, new AbstractHandler.ErrorDispatchHandler() { @Override protected void doNonErrorHandle(String target, org.eclipse.jetty.server.Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException @@ -542,7 +546,7 @@ public class HttpClientTest extends AbstractHttpClientServerTest byte[] buffer = new byte[1024]; InputStream in = request.getInputStream(); - while(true) + while (true) { int read = in.read(buffer); if (read < 0) @@ -559,7 +563,9 @@ public class HttpClientTest extends AbstractHttpClientServerTest { byte[] kb = new byte[1024]; for (int i = 0; i < 10 * 1024; ++i) + { output.write(kb); + } } final CountDownLatch latch = new CountDownLatch(3); @@ -570,10 +576,10 @@ public class HttpClientTest extends AbstractHttpClientServerTest .scheme(scenario.getScheme()) .file(file) .onRequestSuccess(request -> - { - requestTime.set(System.nanoTime()); - latch.countDown(); - }) + { + requestTime.set(System.nanoTime()); + latch.countDown(); + }) .send(new Response.Listener.Adapter() { @Override @@ -603,7 +609,6 @@ public class HttpClientTest extends AbstractHttpClientServerTest Files.delete(file); } - @ParameterizedTest @ArgumentsSource(ScenarioProvider.class) public void test_ExchangeIsComplete_WhenRequestFailsMidway_WithResponse(Scenario scenario) throws Exception @@ -620,49 +625,49 @@ public class HttpClientTest extends AbstractHttpClientServerTest final CountDownLatch latch = new CountDownLatch(1); client.newRequest("localhost", connector.getLocalPort()) - .scheme(scenario.getScheme()) - // The second ByteBuffer set to null will throw an exception - .content(new ContentProvider() + .scheme(scenario.getScheme()) + // The second ByteBuffer set to null will throw an exception + .content(new ContentProvider() + { + @Override + public long getLength() { - @Override - public long getLength() - { - return -1; - } + return -1; + } - @Override - public Iterator iterator() + @Override + public Iterator iterator() + { + return new Iterator<>() { - return new Iterator<>() + @Override + public boolean hasNext() { - @Override - public boolean hasNext() - { - return true; - } + return true; + } - @Override - public ByteBuffer next() - { - throw new NoSuchElementException("explicitly_thrown_by_test"); - } + @Override + public ByteBuffer next() + { + throw new NoSuchElementException("explicitly_thrown_by_test"); + } - @Override - public void remove() - { - throw new UnsupportedOperationException(); - } - }; - } - }) - .send(new Response.Listener.Adapter() + @Override + public void remove() + { + throw new UnsupportedOperationException(); + } + }; + } + }) + .send(new Response.Listener.Adapter() + { + @Override + public void onComplete(Result result) { - @Override - public void onComplete(Result result) - { - latch.countDown(); - } - }); + latch.countDown(); + } + }); assertTrue(latch.await(5, TimeUnit.SECONDS)); } @@ -677,21 +682,21 @@ public class HttpClientTest extends AbstractHttpClientServerTest final String host = "localhost"; final int port = connector.getLocalPort(); client.newRequest(host, port) - .scheme(scenario.getScheme()) - .onRequestBegin(request -> + .scheme(scenario.getScheme()) + .onRequestBegin(request -> + { + HttpDestination destination = (HttpDestination)client.getDestination(scenario.getScheme(), host, port); + DuplexConnectionPool connectionPool = (DuplexConnectionPool)destination.getConnectionPool(); + connectionPool.getActiveConnections().iterator().next().close(); + }) + .send(new Response.Listener.Adapter() + { + @Override + public void onComplete(Result result) { - HttpDestination destination = (HttpDestination)client.getDestination(scenario.getScheme(), host, port); - DuplexConnectionPool connectionPool = (DuplexConnectionPool)destination.getConnectionPool(); - connectionPool.getActiveConnections().iterator().next().close(); - }) - .send(new Response.Listener.Adapter() - { - @Override - public void onComplete(Result result) - { - latch.countDown(); - } - }); + latch.countDown(); + } + }); assertTrue(latch.await(5, TimeUnit.SECONDS)); } @@ -722,7 +727,7 @@ public class HttpClientTest extends AbstractHttpClientServerTest final String host = "localhost"; final int port = connector.getLocalPort(); assertThrows(TimeoutException.class, () -> - client.newRequest(host, port) + client.newRequest(host, port) .scheme(scenario.getScheme()) .idleTimeout(idleTimeout, TimeUnit.MILLISECONDS) .timeout(3 * idleTimeout, TimeUnit.MILLISECONDS) @@ -730,9 +735,9 @@ public class HttpClientTest extends AbstractHttpClientServerTest // Make another request without specifying the idle timeout, should not fail ContentResponse response = client.newRequest(host, port) - .scheme(scenario.getScheme()) - .timeout(3 * idleTimeout, TimeUnit.MILLISECONDS) - .send(); + .scheme(scenario.getScheme()) + .timeout(3 * idleTimeout, TimeUnit.MILLISECONDS) + .send(); assertNotNull(response); assertEquals(200, response.getStatus()); @@ -746,9 +751,9 @@ public class HttpClientTest extends AbstractHttpClientServerTest start(scenario, new EmptyServerHandler()); ContentResponse response = client.newRequest("[::1]", connector.getLocalPort()) - .scheme(scenario.getScheme()) - .timeout(5, TimeUnit.SECONDS) - .send(); + .scheme(scenario.getScheme()) + .timeout(5, TimeUnit.SECONDS) + .send(); assertNotNull(response); assertEquals(200, response.getStatus()); @@ -770,10 +775,10 @@ public class HttpClientTest extends AbstractHttpClientServerTest }); ContentResponse response = client.newRequest("localhost", connector.getLocalPort()) - .scheme(scenario.getScheme()) - .onResponseHeader((response1, field) -> !field.getName().equals(headerName)) - .timeout(5, TimeUnit.SECONDS) - .send(); + .scheme(scenario.getScheme()) + .onResponseHeader((response1, field) -> !field.getName().equals(headerName)) + .timeout(5, TimeUnit.SECONDS) + .send(); assertNotNull(response); assertEquals(200, response.getStatus()); @@ -791,22 +796,22 @@ public class HttpClientTest extends AbstractHttpClientServerTest for (int i = 0; i < count; ++i) { client.newRequest("localhost", connector.getLocalPort()) - .scheme(scenario.getScheme()) - .send(new Response.Listener.Adapter() + .scheme(scenario.getScheme()) + .send(new Response.Listener.Adapter() + { + @Override + public boolean onHeader(Response response, HttpField field) { - @Override - public boolean onHeader(Response response, HttpField field) - { - return false; - } + return false; + } - @Override - public void onComplete(Result result) - { - if (result.isSucceeded()) - latch.countDown(); - } - }); + @Override + public void onComplete(Result result) + { + if (result.isSucceeded()) + latch.countDown(); + } + }); } assertTrue(latch.await(10, TimeUnit.SECONDS)); @@ -830,10 +835,10 @@ public class HttpClientTest extends AbstractHttpClientServerTest // HEAD requests receive a Content-Length header, but do not // receive the content so they must handle this case properly ContentResponse response = client.newRequest("localhost", connector.getLocalPort()) - .scheme(scenario.getScheme()) - .method(HttpMethod.HEAD) - .timeout(5, TimeUnit.SECONDS) - .send(); + .scheme(scenario.getScheme()) + .method(HttpMethod.HEAD) + .timeout(5, TimeUnit.SECONDS) + .send(); assertNotNull(response); assertEquals(200, response.getStatus()); @@ -841,9 +846,9 @@ public class HttpClientTest extends AbstractHttpClientServerTest // Perform a normal GET request to be sure the content is now read response = client.newRequest("localhost", connector.getLocalPort()) - .scheme(scenario.getScheme()) - .timeout(5, TimeUnit.SECONDS) - .send(); + .scheme(scenario.getScheme()) + .timeout(5, TimeUnit.SECONDS) + .send(); assertNotNull(response); assertEquals(200, response.getStatus()); @@ -857,7 +862,8 @@ public class HttpClientTest extends AbstractHttpClientServerTest String host = "idontexist"; int port = 80; - assertThrows(IOException.class, ()->{ + assertThrows(IOException.class, () -> + { Socket socket = new Socket(); socket.connect(new InetSocketAddress(host, port), 1000); }, "Host must not be resolvable"); @@ -866,13 +872,13 @@ public class HttpClientTest extends AbstractHttpClientServerTest final CountDownLatch latch = new CountDownLatch(1); client.newRequest(host, port) - .send(result -> - { - assertTrue(result.isFailed()); - Throwable failure = result.getFailure(); - assertTrue(failure instanceof UnknownHostException); - latch.countDown(); - }); + .send(result -> + { + assertTrue(result.isFailed()); + Throwable failure = result.getFailure(); + assertTrue(failure instanceof UnknownHostException); + latch.countDown(); + }); assertTrue(latch.await(10, TimeUnit.SECONDS)); } @@ -911,9 +917,9 @@ public class HttpClientTest extends AbstractHttpClientServerTest // If no exceptions the test passes. client.newRequest("localhost", connector.getLocalPort()) - .scheme(scenario.getScheme()) - .header(HttpHeader.CONNECTION, "close") - .send(); + .scheme(scenario.getScheme()) + .header(HttpHeader.CONNECTION, "close") + .send(); } @ParameterizedTest @@ -934,19 +940,19 @@ public class HttpClientTest extends AbstractHttpClientServerTest }); ContentResponse response = client.newRequest("localhost", connector.getLocalPort()) - .scheme(scenario.getScheme()) - .agent(userAgent) - .timeout(5, TimeUnit.SECONDS) - .send(); + .scheme(scenario.getScheme()) + .agent(userAgent) + .timeout(5, TimeUnit.SECONDS) + .send(); assertEquals(200, response.getStatus()); response = client.newRequest("localhost", connector.getLocalPort()) - .scheme(scenario.getScheme()) - .header(HttpHeader.USER_AGENT, null) - .header(HttpHeader.USER_AGENT, userAgent) - .timeout(5, TimeUnit.SECONDS) - .send(); + .scheme(scenario.getScheme()) + .header(HttpHeader.USER_AGENT, null) + .header(HttpHeader.USER_AGENT, userAgent) + .timeout(5, TimeUnit.SECONDS) + .send(); assertEquals(200, response.getStatus()); } @@ -971,28 +977,28 @@ public class HttpClientTest extends AbstractHttpClientServerTest // User agent not specified, use default. ContentResponse response = client.newRequest("localhost", connector.getLocalPort()) - .scheme(scenario.getScheme()) - .path("/ua") - .timeout(5, TimeUnit.SECONDS) - .send(); + .scheme(scenario.getScheme()) + .path("/ua") + .timeout(5, TimeUnit.SECONDS) + .send(); assertEquals(200, response.getStatus()); // User agent explicitly removed. response = client.newRequest("localhost", connector.getLocalPort()) - .scheme(scenario.getScheme()) - .agent(null) - .timeout(5, TimeUnit.SECONDS) - .send(); + .scheme(scenario.getScheme()) + .agent(null) + .timeout(5, TimeUnit.SECONDS) + .send(); assertEquals(200, response.getStatus()); // User agent explicitly removed. response = client.newRequest("localhost", connector.getLocalPort()) - .scheme(scenario.getScheme()) - .header(HttpHeader.USER_AGENT, null) - .timeout(5, TimeUnit.SECONDS) - .send(); + .scheme(scenario.getScheme()) + .header(HttpHeader.USER_AGENT, null) + .timeout(5, TimeUnit.SECONDS) + .send(); assertEquals(200, response.getStatus()); } @@ -1051,16 +1057,16 @@ public class HttpClientTest extends AbstractHttpClientServerTest } }; ContentResponse response = client.newRequest("localhost", connector.getLocalPort()) - .scheme(scenario.getScheme()) - .onRequestQueued(listener) - .onRequestBegin(listener) - .onRequestHeaders(listener) - .onRequestCommit(listener) - .onRequestContent(listener) - .onRequestSuccess(listener) - .onRequestFailure(listener) - .listener(listener) - .send(); + .scheme(scenario.getScheme()) + .onRequestQueued(listener) + .onRequestBegin(listener) + .onRequestHeaders(listener) + .onRequestCommit(listener) + .onRequestContent(listener) + .onRequestSuccess(listener) + .onRequestFailure(listener) + .listener(listener) + .send(); assertEquals(200, response.getStatus()); int expectedEventsTriggeredByOnRequestXXXListeners = 5; @@ -1134,15 +1140,15 @@ public class HttpClientTest extends AbstractHttpClientServerTest } }; client.newRequest("localhost", connector.getLocalPort()) - .scheme(scenario.getScheme()) - .onResponseBegin(listener) - .onResponseHeader(listener) - .onResponseHeaders(listener) - .onResponseContent(listener) - .onResponseContentAsync(listener) - .onResponseSuccess(listener) - .onResponseFailure(listener) - .send(listener); + .scheme(scenario.getScheme()) + .onResponseBegin(listener) + .onResponseHeader(listener) + .onResponseHeaders(listener) + .onResponseContent(listener) + .onResponseContentAsync(listener) + .onResponseSuccess(listener) + .onResponseFailure(listener) + .send(listener); assertTrue(latch.await(5, TimeUnit.SECONDS)); int expectedEventsTriggeredByOnResponseXXXListeners = 3; @@ -1184,16 +1190,14 @@ public class HttpClientTest extends AbstractHttpClientServerTest } }; - client.newRequest("localhost", connector.getLocalPort()) - .scheme(scenario.getScheme()) - .send(listener); + .scheme(scenario.getScheme()) + .send(listener); Response response = ex.exchange(null); assertEquals(200, response.getStatus()); assertArrayEquals(content, listener.getContent()); - } @ParameterizedTest @@ -1212,9 +1216,9 @@ public class HttpClientTest extends AbstractHttpClientServerTest }); ContentResponse response = client.newRequest("http://127.0.0.1:" + connector.getLocalPort() + "/path") - .scheme(scenario.getScheme()) - .header(HttpHeader.HOST, host) - .send(); + .scheme(scenario.getScheme()) + .header(HttpHeader.HOST, host) + .send(); assertEquals(200, response.getStatus()); } @@ -1237,11 +1241,11 @@ public class HttpClientTest extends AbstractHttpClientServerTest }); ContentResponse response = client.newRequest("localhost", connector.getLocalPort()) - .scheme(scenario.getScheme()) - .version(HttpVersion.HTTP_1_0) - .header(HttpHeader.CONNECTION, HttpHeaderValue.KEEP_ALIVE.asString()) - .timeout(5, TimeUnit.SECONDS) - .send(); + .scheme(scenario.getScheme()) + .version(HttpVersion.HTTP_1_0) + .header(HttpHeader.CONNECTION, HttpHeaderValue.KEEP_ALIVE.asString()) + .timeout(5, TimeUnit.SECONDS) + .send(); assertEquals(200, response.getStatus()); assertTrue(response.getHeaders().contains(HttpHeader.CONNECTION, HttpHeaderValue.KEEP_ALIVE.asString())); @@ -1269,10 +1273,10 @@ public class HttpClientTest extends AbstractHttpClientServerTest { long timeout = 5000; Request request = client.newRequest(destination.getHost(), destination.getPort()) - .scheme(destination.getScheme()) - .version(HttpVersion.HTTP_1_0) - .header(HttpHeader.CONNECTION, HttpHeaderValue.KEEP_ALIVE.asString()) - .timeout(timeout, TimeUnit.MILLISECONDS); + .scheme(destination.getScheme()) + .version(HttpVersion.HTTP_1_0) + .header(HttpHeader.CONNECTION, HttpHeaderValue.KEEP_ALIVE.asString()) + .timeout(timeout, TimeUnit.MILLISECONDS); FutureResponseListener listener = new FutureResponseListener(request); connection.send(request, listener); @@ -1294,11 +1298,11 @@ public class HttpClientTest extends AbstractHttpClientServerTest start(scenario, new EmptyServerHandler()); ContentResponse response = client.newRequest("localhost", connector.getLocalPort()) - .scheme(scenario.getScheme()) - .version(HttpVersion.HTTP_1_0) - .header(HttpHeader.CONNECTION, HttpHeaderValue.KEEP_ALIVE.asString()) - .timeout(5, TimeUnit.SECONDS) - .send(); + .scheme(scenario.getScheme()) + .version(HttpVersion.HTTP_1_0) + .header(HttpHeader.CONNECTION, HttpHeaderValue.KEEP_ALIVE.asString()) + .timeout(5, TimeUnit.SECONDS) + .send(); assertEquals(200, response.getStatus()); assertTrue(response.getHeaders().contains(HttpHeader.CONNECTION, HttpHeaderValue.KEEP_ALIVE.asString())); @@ -1322,12 +1326,12 @@ public class HttpClientTest extends AbstractHttpClientServerTest final CountDownLatch completeLatch = new CountDownLatch(1); client.newRequest("localhost", connector.getLocalPort()) - .scheme(scenario.getScheme()) - .send(result -> - { - if (result.isFailed()) - completeLatch.countDown(); - }); + .scheme(scenario.getScheme()) + .send(result -> + { + if (result.isFailed()) + completeLatch.countDown(); + }); assertTrue(latch.await(5, TimeUnit.SECONDS)); @@ -1344,7 +1348,7 @@ public class HttpClientTest extends AbstractHttpClientServerTest Assumptions.assumeTrue(HttpScheme.HTTP.is(scenario.getScheme())); ExecutionException e = assertThrows(ExecutionException.class, () -> - testContentDelimitedByEOFWithSlowRequest(scenario, HttpVersion.HTTP_1_0, 1024)); + testContentDelimitedByEOFWithSlowRequest(scenario, HttpVersion.HTTP_1_0, 1024)); assertThat(e.getCause(), instanceOf(BadMessageException.class)); assertThat(e.getCause().getMessage(), containsString("Unknown content")); @@ -1355,7 +1359,7 @@ public class HttpClientTest extends AbstractHttpClientServerTest public void testBigContentDelimitedByEOFWithSlowRequestHTTP10(Scenario scenario) throws Exception { ExecutionException e = assertThrows(ExecutionException.class, () -> - testContentDelimitedByEOFWithSlowRequest(scenario, HttpVersion.HTTP_1_0, 128 * 1024)); + testContentDelimitedByEOFWithSlowRequest(scenario, HttpVersion.HTTP_1_0, 128 * 1024)); assertThat(e.getCause(), instanceOf(BadMessageException.class)); assertThat(e.getCause().getMessage(), containsString("Unknown content")); @@ -1401,9 +1405,9 @@ public class HttpClientTest extends AbstractHttpClientServerTest DeferredContentProvider content = new DeferredContentProvider(ByteBuffer.wrap(new byte[]{0})); Request request = client.newRequest("localhost", connector.getLocalPort()) - .scheme(scenario.getScheme()) - .version(version) - .content(content); + .scheme(scenario.getScheme()) + .version(version) + .content(content); FutureResponseListener listener = new FutureResponseListener(request); request.send(listener); // Wait some time to simulate a slow request. @@ -1466,24 +1470,24 @@ public class HttpClientTest extends AbstractHttpClientServerTest final CountDownLatch contentLatch = new CountDownLatch(1); final CountDownLatch completeLatch = new CountDownLatch(1); client.newRequest("localhost", connector.getLocalPort()) - .scheme(scenario.getScheme()) - .send(new Response.Listener.Adapter() + .scheme(scenario.getScheme()) + .send(new Response.Listener.Adapter() + { + @Override + public void onContent(Response response, ByteBuffer content, Callback callback) { - @Override - public void onContent(Response response, ByteBuffer content, Callback callback) - { - // Do not notify the callback yet. - callbackRef.set(callback); - contentLatch.countDown(); - } + // Do not notify the callback yet. + callbackRef.set(callback); + contentLatch.countDown(); + } - @Override - public void onComplete(Result result) - { - if (result.isSucceeded()) - completeLatch.countDown(); - } - }); + @Override + public void onComplete(Result result) + { + if (result.isSucceeded()) + completeLatch.countDown(); + } + }); assertTrue(contentLatch.await(5, TimeUnit.SECONDS)); @@ -1533,17 +1537,17 @@ public class HttpClientTest extends AbstractHttpClientServerTest final CountDownLatch latch = new CountDownLatch(2); client.newRequest("localhost", connector.getLocalPort()) - .scheme(scenario.getScheme()) - .onRequestBegin(request -> - { - assertTrue(open.get()); + .scheme(scenario.getScheme()) + .onRequestBegin(request -> + { + assertTrue(open.get()); + latch.countDown(); + }) + .send(result -> + { + if (result.isSucceeded()) latch.countDown(); - }) - .send(result -> - { - if (result.isSucceeded()) - latch.countDown(); - }); + }); assertTrue(latch.await(5, TimeUnit.SECONDS)); } @@ -1560,8 +1564,8 @@ public class HttpClientTest extends AbstractHttpClientServerTest int port = server.getLocalPort(); Request request = client.newRequest(host, port) - .method(HttpMethod.CONNECT) - .version(HttpVersion.HTTP_1_0); + .method(HttpMethod.CONNECT) + .version(HttpVersion.HTTP_1_0); FuturePromise promise = new FuturePromise<>(); client.getDestination("http", host, port).newConnection(promise); Connection connection = promise.get(5, TimeUnit.SECONDS); @@ -1574,8 +1578,8 @@ public class HttpClientTest extends AbstractHttpClientServerTest consume(input, false); // HTTP/1.0 response, the client must not close the connection. - String httpResponse = "" + - "HTTP/1.0 200 OK\r\n" + + String httpResponse = + "HTTP/1.0 200 OK\r\n" + "\r\n"; OutputStream output = socket.getOutputStream(); output.write(httpResponse.getBytes(StandardCharsets.UTF_8)); @@ -1596,8 +1600,8 @@ public class HttpClientTest extends AbstractHttpClientServerTest consume(input, false); - httpResponse = "" + - "HTTP/1.1 200 OK\r\n" + + httpResponse = + "HTTP/1.1 200 OK\r\n" + "Content-Length: 0\r\n" + "\r\n"; output.write(httpResponse.getBytes(StandardCharsets.UTF_8)); @@ -1632,7 +1636,7 @@ public class HttpClientTest extends AbstractHttpClientServerTest assertNotNull(response); assertEquals(200, response.getStatus()); - assertThat(new String(response.getContent(), StandardCharsets.ISO_8859_1),Matchers.startsWith("[::1]:")); + assertThat(new String(response.getContent(), StandardCharsets.ISO_8859_1), Matchers.startsWith("[::1]:")); } @ParameterizedTest @@ -1642,46 +1646,46 @@ public class HttpClientTest extends AbstractHttpClientServerTest startClient(scenario); assertCopyRequest(client.newRequest("http://example.com/some/url") - .method(HttpMethod.HEAD) - .version(HttpVersion.HTTP_2) - .content(new StringContentProvider("some string")) - .timeout(321, TimeUnit.SECONDS) - .idleTimeout(2221, TimeUnit.SECONDS) - .followRedirects(true) - .header(HttpHeader.CONTENT_TYPE, "application/json") - .header("X-Some-Custom-Header", "some-value")); + .method(HttpMethod.HEAD) + .version(HttpVersion.HTTP_2) + .content(new StringContentProvider("some string")) + .timeout(321, TimeUnit.SECONDS) + .idleTimeout(2221, TimeUnit.SECONDS) + .followRedirects(true) + .header(HttpHeader.CONTENT_TYPE, "application/json") + .header("X-Some-Custom-Header", "some-value")); assertCopyRequest(client.newRequest("https://example.com") - .method(HttpMethod.POST) - .version(HttpVersion.HTTP_1_0) - .content(new StringContentProvider("some other string")) - .timeout(123231, TimeUnit.SECONDS) - .idleTimeout(232342, TimeUnit.SECONDS) - .followRedirects(false) - .header(HttpHeader.ACCEPT, "application/json") - .header("X-Some-Other-Custom-Header", "some-other-value")); + .method(HttpMethod.POST) + .version(HttpVersion.HTTP_1_0) + .content(new StringContentProvider("some other string")) + .timeout(123231, TimeUnit.SECONDS) + .idleTimeout(232342, TimeUnit.SECONDS) + .followRedirects(false) + .header(HttpHeader.ACCEPT, "application/json") + .header("X-Some-Other-Custom-Header", "some-other-value")); assertCopyRequest(client.newRequest("https://example.com") - .header(HttpHeader.ACCEPT, "application/json") - .header(HttpHeader.ACCEPT, "application/xml") - .header("x-same-name", "value1") - .header("x-same-name", "value2")); + .header(HttpHeader.ACCEPT, "application/json") + .header(HttpHeader.ACCEPT, "application/xml") + .header("x-same-name", "value1") + .header("x-same-name", "value2")); assertCopyRequest(client.newRequest("https://example.com") - .header(HttpHeader.ACCEPT, "application/json") - .header(HttpHeader.CONTENT_TYPE, "application/json")); + .header(HttpHeader.ACCEPT, "application/json") + .header(HttpHeader.CONTENT_TYPE, "application/json")); assertCopyRequest(client.newRequest("https://example.com") - .header("Accept", "application/json") - .header("Content-Type", "application/json")); + .header("Accept", "application/json") + .header("Content-Type", "application/json")); assertCopyRequest(client.newRequest("https://example.com") - .header("X-Custom-Header-1", "value1") - .header("X-Custom-Header-2", "value2")); + .header("X-Custom-Header-1", "value1") + .header("X-Custom-Header-2", "value2")); assertCopyRequest(client.newRequest("https://example.com") - .header("X-Custom-Header-1", "value") - .header("X-Custom-Header-2", "value")); + .header("X-Custom-Header-1", "value") + .header("X-Custom-Header-2", "value")); } @ParameterizedTest @@ -1699,10 +1703,10 @@ public class HttpClientTest extends AbstractHttpClientServerTest }); ContentResponse response = client.newRequest("localhost", connector.getLocalPort()) - .scheme(scenario.getScheme()) - .version(HttpVersion.HTTP_1_0) - .timeout(5, TimeUnit.SECONDS) - .send(); + .scheme(scenario.getScheme()) + .version(HttpVersion.HTTP_1_0) + .timeout(5, TimeUnit.SECONDS) + .send(); assertEquals(200, response.getStatus()); } @@ -1724,8 +1728,8 @@ public class HttpClientTest extends AbstractHttpClientServerTest }); Request request = client.newRequest("localhost", server.getLocalPort()) - .scheme(scenario.getScheme()) - .timeout(5, TimeUnit.SECONDS); + .scheme(scenario.getScheme()) + .timeout(5, TimeUnit.SECONDS); FutureResponseListener listener = new FutureResponseListener(request); request.send(listener); @@ -1737,8 +1741,8 @@ public class HttpClientTest extends AbstractHttpClientServerTest consume(input, false); // Send a bad response. - String httpResponse = "" + - "HTTP/1.1 204 No Content\r\n" + + String httpResponse = + "HTTP/1.1 204 No Content\r\n" + "\r\n" + "No Content"; OutputStream output = socket.getOutputStream(); @@ -1754,15 +1758,15 @@ public class HttpClientTest extends AbstractHttpClientServerTest // Send another request to verify we have handled the wrong response correctly. request = client.newRequest("localhost", server.getLocalPort()) - .scheme(scenario.getScheme()) - .timeout(5, TimeUnit.SECONDS); + .scheme(scenario.getScheme()) + .timeout(5, TimeUnit.SECONDS); listener = new FutureResponseListener(request); request.send(listener); consume(input, false); - httpResponse = "" + - "HTTP/1.1 200 OK\r\n" + + httpResponse = + "HTTP/1.1 200 OK\r\n" + "Content-Length: 0\r\n" + "\r\n"; output.write(httpResponse.getBytes(StandardCharsets.UTF_8)); @@ -1776,7 +1780,7 @@ public class HttpClientTest extends AbstractHttpClientServerTest private void assertCopyRequest(Request original) { - Request copy = client.copyRequest((HttpRequest) original, original.getURI()); + Request copy = client.copyRequest((HttpRequest)original, original.getURI()); assertEquals(original.getURI(), copy.getURI()); assertEquals(original.getMethod(), copy.getMethod()); assertEquals(original.getVersion(), copy.getVersion()); @@ -1804,7 +1808,7 @@ public class HttpClientTest extends AbstractHttpClientServerTest } } - public static abstract class RetryListener implements Response.CompleteListener + public abstract static class RetryListener implements Response.CompleteListener { private final HttpClient client; private final String scheme; @@ -1842,11 +1846,11 @@ public class HttpClientTest extends AbstractHttpClientServerTest public void perform() { client.newRequest(host, port) - .scheme(scheme) - .method("POST") - .param("attempt", String.valueOf(retries)) - .content(new StringContentProvider("0123456789ABCDEF")) - .send(this); + .scheme(scheme) + .method("POST") + .param("attempt", String.valueOf(retries)) + .content(new StringContentProvider("0123456789ABCDEF")) + .send(this); } } } diff --git a/jetty-client/src/test/java/org/eclipse/jetty/client/HttpClientURITest.java b/jetty-client/src/test/java/org/eclipse/jetty/client/HttpClientURITest.java index 0863fcc770d..15d62f1b6bb 100644 --- a/jetty-client/src/test/java/org/eclipse/jetty/client/HttpClientURITest.java +++ b/jetty-client/src/test/java/org/eclipse/jetty/client/HttpClientURITest.java @@ -68,8 +68,8 @@ public class HttpClientURITest extends AbstractHttpClientServerTest String host = "::1"; Request request = client.newRequest(host, connector.getLocalPort()) - .scheme(scenario.getScheme()) - .timeout(5, TimeUnit.SECONDS); + .scheme(scenario.getScheme()) + .timeout(5, TimeUnit.SECONDS); assertEquals(host, request.getHost()); StringBuilder uri = new StringBuilder(); @@ -84,7 +84,8 @@ public class HttpClientURITest extends AbstractHttpClientServerTest public void testIDNHost(Scenario scenario) throws Exception { startClient(scenario); - assertThrows(IllegalArgumentException.class, ()-> { + assertThrows(IllegalArgumentException.class, () -> + { client.newRequest(scenario.getScheme() + "://пример.рф"); // example.com-like host in IDN domain }); } @@ -107,18 +108,19 @@ public class HttpClientURITest extends AbstractHttpClientServerTest startClient(scenario); ContentResponse response = client.newRequest("localhost", server.getLocalPort()) - .timeout(5, TimeUnit.SECONDS) - .followRedirects(false) - .send(); + .timeout(5, TimeUnit.SECONDS) + .followRedirects(false) + .send(); HttpField location = response.getHeaders().getField(HttpHeader.LOCATION); assertEquals(incorrectlyDecoded, location.getValue()); - ExecutionException x = assertThrows(ExecutionException.class, ()-> { + ExecutionException x = assertThrows(ExecutionException.class, () -> + { client.newRequest("localhost", server.getLocalPort()) - .timeout(5, TimeUnit.SECONDS) - .followRedirects(true) - .send(); + .timeout(5, TimeUnit.SECONDS) + .followRedirects(true) + .send(); }); assertThat(x.getCause(), instanceOf(IllegalArgumentException.class)); } @@ -144,9 +146,9 @@ public class HttpClientURITest extends AbstractHttpClientServerTest }); Request request = client.newRequest("localhost", connector.getLocalPort()) - .scheme(scenario.getScheme()) - .timeout(5, TimeUnit.SECONDS) - .path(path); + .scheme(scenario.getScheme()) + .timeout(5, TimeUnit.SECONDS) + .path(path); assertEquals(path, request.getPath()); assertNull(request.getQuery()); @@ -180,9 +182,9 @@ public class HttpClientURITest extends AbstractHttpClientServerTest String pathQuery = path + "?" + query; Request request = client.newRequest("localhost", connector.getLocalPort()) - .scheme(scenario.getScheme()) - .timeout(5, TimeUnit.SECONDS) - .path(pathQuery); + .scheme(scenario.getScheme()) + .timeout(5, TimeUnit.SECONDS) + .path(pathQuery); assertEquals(path, request.getPath()); assertEquals(query, request.getQuery()); @@ -217,10 +219,10 @@ public class HttpClientURITest extends AbstractHttpClientServerTest }); Request request = client.newRequest("localhost", connector.getLocalPort()) - .scheme(scenario.getScheme()) - .timeout(5, TimeUnit.SECONDS) - .path(path) - .param(name, value); + .scheme(scenario.getScheme()) + .timeout(5, TimeUnit.SECONDS) + .path(path) + .param(name, value); assertEquals(path, request.getPath()); assertEquals(query, request.getQuery()); @@ -257,10 +259,10 @@ public class HttpClientURITest extends AbstractHttpClientServerTest }); Request request = client.newRequest("localhost", connector.getLocalPort()) - .scheme(scenario.getScheme()) - .timeout(5, TimeUnit.SECONDS) - .path(path + "?" + name1 + "=" + value1) - .param(name2, value2); + .scheme(scenario.getScheme()) + .timeout(5, TimeUnit.SECONDS) + .path(path + "?" + name1 + "=" + value1) + .param(name2, value2); assertEquals(path, request.getPath()); assertEquals(query, request.getQuery()); @@ -302,10 +304,10 @@ public class HttpClientURITest extends AbstractHttpClientServerTest }); Request request = client.newRequest("localhost", connector.getLocalPort()) - .scheme(scenario.getScheme()) - .timeout(5, TimeUnit.SECONDS) - .path(path + "?" + name1 + "=" + encodedValue1) - .param(name2, value2); + .scheme(scenario.getScheme()) + .timeout(5, TimeUnit.SECONDS) + .path(path + "?" + name1 + "=" + encodedValue1) + .param(name2, value2); assertEquals(path, request.getPath()); assertEquals(query, request.getQuery()); @@ -339,9 +341,9 @@ public class HttpClientURITest extends AbstractHttpClientServerTest }); Request request = client.newRequest("localhost", connector.getLocalPort()) - .scheme(scenario.getScheme()) - .timeout(5, TimeUnit.SECONDS) - .path(pathQuery); + .scheme(scenario.getScheme()) + .timeout(5, TimeUnit.SECONDS) + .path(pathQuery); assertEquals(path, request.getPath()); assertEquals(query, request.getQuery()); @@ -373,9 +375,9 @@ public class HttpClientURITest extends AbstractHttpClientServerTest }); Request request = client.newRequest("localhost", connector.getLocalPort()) - .scheme(scenario.getScheme()) - .timeout(5, TimeUnit.SECONDS) - .path(pathQuery); + .scheme(scenario.getScheme()) + .timeout(5, TimeUnit.SECONDS) + .path(pathQuery); assertEquals(path, request.getPath()); assertEquals(query, request.getQuery()); @@ -406,11 +408,11 @@ public class HttpClientURITest extends AbstractHttpClientServerTest }); ContentResponse response = client.newRequest("localhost", connector.getLocalPort()) - .scheme(scenario.getScheme()) - .path("/path?" + name1 + "=" + name1) - .param(name2, name2) - .timeout(5, TimeUnit.SECONDS) - .send(); + .scheme(scenario.getScheme()) + .path("/path?" + name1 + "=" + name1) + .param(name2, name2) + .timeout(5, TimeUnit.SECONDS) + .send(); assertEquals(HttpStatus.OK_200, response.getStatus()); } @@ -436,7 +438,7 @@ public class HttpClientURITest extends AbstractHttpClientServerTest String uri = scenario.getScheme() + "://localhost:" + connector.getLocalPort() + "/path?" + rawQuery; Request request = client.newRequest(uri) - .timeout(5, TimeUnit.SECONDS); + .timeout(5, TimeUnit.SECONDS); assertEquals(rawQuery, request.getQuery()); ContentResponse response = request.send(); @@ -464,9 +466,9 @@ public class HttpClientURITest extends AbstractHttpClientServerTest }); Request request = client.newRequest("localhost", connector.getLocalPort()) - .scheme(scenario.getScheme()) - .path("/path?" + rawQuery) - .timeout(5, TimeUnit.SECONDS); + .scheme(scenario.getScheme()) + .path("/path?" + rawQuery) + .timeout(5, TimeUnit.SECONDS); assertEquals(rawQuery, request.getQuery()); ContentResponse response = request.send(); @@ -499,10 +501,10 @@ public class HttpClientURITest extends AbstractHttpClientServerTest }); Request request = client.newRequest("localhost", connector.getLocalPort()) - .scheme(scenario.getScheme()) - .path("/path?" + rawQuery1) - .param(name2, value2) - .timeout(5, TimeUnit.SECONDS); + .scheme(scenario.getScheme()) + .path("/path?" + rawQuery1) + .param(name2, value2) + .timeout(5, TimeUnit.SECONDS); assertEquals(query, request.getQuery()); ContentResponse response = request.send(); @@ -524,9 +526,9 @@ public class HttpClientURITest extends AbstractHttpClientServerTest }); ContentResponse response = client.newRequest("localhost", connector.getLocalPort()) - .scheme(scenario.getScheme().toUpperCase(Locale.ENGLISH)) - .timeout(5, TimeUnit.SECONDS) - .send(); + .scheme(scenario.getScheme().toUpperCase(Locale.ENGLISH)) + .timeout(5, TimeUnit.SECONDS) + .send(); assertEquals(HttpStatus.OK_200, response.getStatus()); } @@ -545,9 +547,9 @@ public class HttpClientURITest extends AbstractHttpClientServerTest }); ContentResponse response = client.newRequest("LOCALHOST", connector.getLocalPort()) - .scheme(scenario.getScheme()) - .timeout(5, TimeUnit.SECONDS) - .send(); + .scheme(scenario.getScheme()) + .timeout(5, TimeUnit.SECONDS) + .send(); assertEquals(HttpStatus.OK_200, response.getStatus()); } @@ -568,10 +570,10 @@ public class HttpClientURITest extends AbstractHttpClientServerTest }); Request request = client.newRequest("localhost", connector.getLocalPort()) - .method(HttpMethod.OPTIONS) - .scheme(scenario.getScheme()) - .path("*") - .timeout(5, TimeUnit.SECONDS); + .method(HttpMethod.OPTIONS) + .scheme(scenario.getScheme()) + .path("*") + .timeout(5, TimeUnit.SECONDS); assertEquals("*", request.getPath()); assertNull(request.getQuery()); @@ -615,10 +617,10 @@ public class HttpClientURITest extends AbstractHttpClientServerTest } writer.append("HTTP/1.1 302 Found\r\n") - .append("Location: ").append(location).append("\r\n") - .append("Content-Length: 0\r\n") - .append("Connection: close\r\n") - .append("\r\n"); + .append("Location: ").append(location).append("\r\n") + .append("Content-Length: 0\r\n") + .append("Connection: close\r\n") + .append("\r\n"); writer.flush(); } } diff --git a/jetty-client/src/test/java/org/eclipse/jetty/client/HttpClientUploadDuringServerShutdown.java b/jetty-client/src/test/java/org/eclipse/jetty/client/HttpClientUploadDuringServerShutdown.java index 148ecd6156b..5af26fcd6a6 100644 --- a/jetty-client/src/test/java/org/eclipse/jetty/client/HttpClientUploadDuringServerShutdown.java +++ b/jetty-client/src/test/java/org/eclipse/jetty/client/HttpClientUploadDuringServerShutdown.java @@ -25,7 +25,6 @@ import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicReference; - import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; @@ -118,8 +117,8 @@ public class HttpClientUploadDuringServerShutdown { int length = 16 * 1024 * 1024 + random.nextInt(16 * 1024 * 1024); client.newRequest("localhost", 8888) - .content(new BytesContentProvider(new byte[length])) - .send(result -> latch.countDown()); + .content(new BytesContentProvider(new byte[length])) + .send(result -> latch.countDown()); long sleep = 1 + random.nextInt(10); TimeUnit.MILLISECONDS.sleep(sleep); } @@ -232,20 +231,20 @@ public class HttpClientUploadDuringServerShutdown final CountDownLatch completeLatch = new CountDownLatch(1); client.newRequest("localhost", connector.getLocalPort()) - .timeout(10, TimeUnit.SECONDS) - .onRequestBegin(request -> + .timeout(10, TimeUnit.SECONDS) + .onRequestBegin(request -> + { + try { - try - { - beginLatch.countDown(); - completeLatch.await(5, TimeUnit.SECONDS); - } - catch (InterruptedException x) - { - x.printStackTrace(); - } - }) - .send(result -> completeLatch.countDown()); + beginLatch.countDown(); + completeLatch.await(5, TimeUnit.SECONDS); + } + catch (InterruptedException x) + { + x.printStackTrace(); + } + }) + .send(result -> completeLatch.countDown()); assertTrue(completeLatch.await(5, TimeUnit.SECONDS)); diff --git a/jetty-client/src/test/java/org/eclipse/jetty/client/HttpConnectionLifecycleTest.java b/jetty-client/src/test/java/org/eclipse/jetty/client/HttpConnectionLifecycleTest.java index f4b2fbdf2a1..5089df3d728 100644 --- a/jetty-client/src/test/java/org/eclipse/jetty/client/HttpConnectionLifecycleTest.java +++ b/jetty-client/src/test/java/org/eclipse/jetty/client/HttpConnectionLifecycleTest.java @@ -25,7 +25,6 @@ import java.util.Collection; import java.util.Queue; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; - import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; @@ -80,29 +79,29 @@ public class HttpConnectionLifecycleTest extends AbstractHttpClientServerTest final CountDownLatch headersLatch = new CountDownLatch(1); final CountDownLatch successLatch = new CountDownLatch(3); client.newRequest(host, port) - .scheme(scenario.getScheme()) - .onRequestSuccess(request -> successLatch.countDown()) - .onResponseHeaders(response -> + .scheme(scenario.getScheme()) + .onRequestSuccess(request -> successLatch.countDown()) + .onResponseHeaders(response -> + { + assertEquals(0, idleConnections.size()); + assertEquals(1, activeConnections.size()); + headersLatch.countDown(); + }) + .send(new Response.Listener.Adapter() + { + @Override + public void onSuccess(Response response) { - assertEquals(0, idleConnections.size()); - assertEquals(1, activeConnections.size()); - headersLatch.countDown(); - }) - .send(new Response.Listener.Adapter() - { - @Override - public void onSuccess(Response response) - { - successLatch.countDown(); - } + successLatch.countDown(); + } - @Override - public void onComplete(Result result) - { - assertFalse(result.isFailed()); - successLatch.countDown(); - } - }); + @Override + public void onComplete(Result result) + { + assertFalse(result.isFailed()); + successLatch.countDown(); + } + }); assertTrue(headersLatch.await(30, TimeUnit.SECONDS)); assertTrue(successLatch.await(30, TimeUnit.SECONDS)); @@ -182,40 +181,40 @@ public class HttpConnectionLifecycleTest extends AbstractHttpClientServerTest final CountDownLatch successLatch = new CountDownLatch(3); client.newRequest(host, port) - .scheme(scenario.getScheme()) - .listener(new Request.Listener.Adapter() + .scheme(scenario.getScheme()) + .listener(new Request.Listener.Adapter() + { + @Override + public void onBegin(Request request) { - @Override - public void onBegin(Request request) - { - // Remove the host header, this will make the request invalid - request.header(HttpHeader.HOST, null); - } + // Remove the host header, this will make the request invalid + request.header(HttpHeader.HOST, null); + } - @Override - public void onSuccess(Request request) - { - successLatch.countDown(); - } - }) - .send(new Response.Listener.Adapter() + @Override + public void onSuccess(Request request) { - @Override - public void onSuccess(Response response) - { - assertEquals(400, response.getStatus()); - // 400 response also come with a Connection: close, - // so the connection is closed and removed - successLatch.countDown(); - } + successLatch.countDown(); + } + }) + .send(new Response.Listener.Adapter() + { + @Override + public void onSuccess(Response response) + { + assertEquals(400, response.getStatus()); + // 400 response also come with a Connection: close, + // so the connection is closed and removed + successLatch.countDown(); + } - @Override - public void onComplete(Result result) - { - assertFalse(result.isFailed()); - successLatch.countDown(); - } - }); + @Override + public void onComplete(Result result) + { + assertFalse(result.isFailed()); + successLatch.countDown(); + } + }); assertTrue(successLatch.await(30, TimeUnit.SECONDS)); @@ -245,53 +244,53 @@ public class HttpConnectionLifecycleTest extends AbstractHttpClientServerTest final long delay = 1000; final CountDownLatch successLatch = new CountDownLatch(3); client.newRequest(host, port) - .scheme(scenario.getScheme()) - .listener(new Request.Listener.Adapter() + .scheme(scenario.getScheme()) + .listener(new Request.Listener.Adapter() + { + @Override + public void onBegin(Request request) { - @Override - public void onBegin(Request request) - { - // Remove the host header, this will make the request invalid - request.header(HttpHeader.HOST, null); - } + // Remove the host header, this will make the request invalid + request.header(HttpHeader.HOST, null); + } - @Override - public void onHeaders(Request request) - { - try - { - TimeUnit.MILLISECONDS.sleep(delay); - } - catch (InterruptedException e) - { - e.printStackTrace(); - } - } - - @Override - public void onSuccess(Request request) - { - successLatch.countDown(); - } - }) - .send(new Response.Listener.Adapter() + @Override + public void onHeaders(Request request) { - @Override - public void onSuccess(Response response) + try { - assertEquals(400, response.getStatus()); - // 400 response also come with a Connection: close, - // so the connection is closed and removed - successLatch.countDown(); + TimeUnit.MILLISECONDS.sleep(delay); } + catch (InterruptedException e) + { + e.printStackTrace(); + } + } - @Override - public void onComplete(Result result) - { - assertFalse(result.isFailed()); - successLatch.countDown(); - } - }); + @Override + public void onSuccess(Request request) + { + successLatch.countDown(); + } + }) + .send(new Response.Listener.Adapter() + { + @Override + public void onSuccess(Response response) + { + assertEquals(400, response.getStatus()); + // 400 response also come with a Connection: close, + // so the connection is closed and removed + successLatch.countDown(); + } + + @Override + public void onComplete(Result result) + { + assertFalse(result.isFailed()); + successLatch.countDown(); + } + }); assertTrue(successLatch.await(delay * 30, TimeUnit.MILLISECONDS)); @@ -320,13 +319,13 @@ public class HttpConnectionLifecycleTest extends AbstractHttpClientServerTest final CountDownLatch failureLatch = new CountDownLatch(2); client.newRequest(host, port) - .scheme(scenario.getScheme()) - .onRequestFailure((request, failure) -> failureLatch.countDown()) - .send(result -> - { - assertTrue(result.isFailed()); - failureLatch.countDown(); - }); + .scheme(scenario.getScheme()) + .onRequestFailure((request, failure) -> failureLatch.countDown()) + .send(result -> + { + assertTrue(result.isFailed()); + failureLatch.countDown(); + }); assertTrue(failureLatch.await(30, TimeUnit.SECONDS)); @@ -361,18 +360,18 @@ public class HttpConnectionLifecycleTest extends AbstractHttpClientServerTest final CountDownLatch latch = new CountDownLatch(1); client.newRequest(host, port) - .scheme(scenario.getScheme()) - .send(new Response.Listener.Adapter() + .scheme(scenario.getScheme()) + .send(new Response.Listener.Adapter() + { + @Override + public void onComplete(Result result) { - @Override - public void onComplete(Result result) - { - assertFalse(result.isFailed()); - assertEquals(0, idleConnections.size()); - assertEquals(0, activeConnections.size()); - latch.countDown(); - } - }); + assertFalse(result.isFailed()); + assertEquals(0, idleConnections.size()); + assertEquals(0, activeConnections.size()); + latch.countDown(); + } + }); assertTrue(latch.await(30, TimeUnit.SECONDS)); @@ -412,21 +411,21 @@ public class HttpConnectionLifecycleTest extends AbstractHttpClientServerTest final CountDownLatch latch = new CountDownLatch(1); ByteBuffer buffer = ByteBuffer.allocate(16 * 1024 * 1024); - Arrays.fill(buffer.array(),(byte)'x'); + Arrays.fill(buffer.array(), (byte)'x'); client.newRequest(host, port) - .scheme(scenario.getScheme()) - .content(new ByteBufferContentProvider(buffer)) - .send(new Response.Listener.Adapter() + .scheme(scenario.getScheme()) + .content(new ByteBufferContentProvider(buffer)) + .send(new Response.Listener.Adapter() + { + @Override + public void onComplete(Result result) { - @Override - public void onComplete(Result result) - { - assertEquals(1, latch.getCount()); - assertEquals(0, idleConnections.size()); - assertEquals(0, activeConnections.size()); - latch.countDown(); - } - }); + assertEquals(1, latch.getCount()); + assertEquals(0, idleConnections.size()); + assertEquals(0, activeConnections.size()); + latch.countDown(); + } + }); assertTrue(latch.await(30, TimeUnit.SECONDS)); @@ -457,9 +456,9 @@ public class HttpConnectionLifecycleTest extends AbstractHttpClientServerTest assertEquals(0, activeConnections.size()); ContentResponse response = client.newRequest(host, port) - .scheme(scenario.getScheme()) - .timeout(30, TimeUnit.SECONDS) - .send(); + .scheme(scenario.getScheme()) + .timeout(30, TimeUnit.SECONDS) + .send(); assertEquals(200, response.getStatus()); @@ -491,13 +490,13 @@ public class HttpConnectionLifecycleTest extends AbstractHttpClientServerTest client.setStrictEventOrdering(false); ContentResponse response = client.newRequest(host, port) - .scheme(scenario.getScheme()) - .onResponseBegin(response1 -> - { - // Simulate a HTTP 1.0 response has been received. - ((HttpResponse)response1).version(HttpVersion.HTTP_1_0); - }) - .send(); + .scheme(scenario.getScheme()) + .onResponseBegin(response1 -> + { + // Simulate a HTTP 1.0 response has been received. + ((HttpResponse)response1).version(HttpVersion.HTTP_1_0); + }) + .send(); assertEquals(200, response.getStatus()); diff --git a/jetty-client/src/test/java/org/eclipse/jetty/client/HttpCookieTest.java b/jetty-client/src/test/java/org/eclipse/jetty/client/HttpCookieTest.java index aaf68f81d9f..c90c821a70e 100644 --- a/jetty-client/src/test/java/org/eclipse/jetty/client/HttpCookieTest.java +++ b/jetty-client/src/test/java/org/eclipse/jetty/client/HttpCookieTest.java @@ -18,13 +18,6 @@ package org.eclipse.jetty.client; -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.containsInAnyOrder; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertNotNull; -import static org.junit.jupiter.api.Assertions.assertTrue; -import static org.junit.jupiter.api.Assertions.fail; - import java.io.IOException; import java.net.HttpCookie; import java.net.URI; @@ -34,7 +27,6 @@ import java.util.List; import java.util.Optional; import java.util.Set; import java.util.concurrent.TimeUnit; - import javax.servlet.ServletException; import javax.servlet.http.Cookie; import javax.servlet.http.HttpServletRequest; @@ -47,6 +39,13 @@ import org.eclipse.jetty.server.Request; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.ArgumentsSource; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.containsInAnyOrder; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.fail; + public class HttpCookieTest extends AbstractHttpClientServerTest { private static final Cookie[] EMPTY_COOKIES = new Cookie[0]; @@ -126,8 +125,8 @@ public class HttpCookieTest extends AbstractHttpClientServerTest }); ContentResponse response = client.newRequest("localhost", connector.getLocalPort()) - .scheme(scenario.getScheme()) - .send(); + .scheme(scenario.getScheme()) + .send(); assertEquals(200, response.getStatus()); assertTrue(client.getCookieStore().getCookies().isEmpty()); } @@ -153,10 +152,10 @@ public class HttpCookieTest extends AbstractHttpClientServerTest }); ContentResponse response = client.newRequest("localhost", connector.getLocalPort()) - .scheme(scenario.getScheme()) - .cookie(new HttpCookie(name, value)) - .timeout(5, TimeUnit.SECONDS) - .send(); + .scheme(scenario.getScheme()) + .cookie(new HttpCookie(name, value)) + .timeout(5, TimeUnit.SECONDS) + .send(); assertEquals(200, response.getStatus()); } @@ -199,19 +198,19 @@ public class HttpCookieTest extends AbstractHttpClientServerTest }); ContentResponse response = send(client.newRequest("localhost", connector.getLocalPort()) - .scheme(scenario.getScheme()) - .path("/foo") - .header(headerName, "0") - .timeout(5, TimeUnit.SECONDS)); + .scheme(scenario.getScheme()) + .path("/foo") + .header(headerName, "0") + .timeout(5, TimeUnit.SECONDS)); assertEquals(HttpStatus.OK_200, response.getStatus()); Arrays.asList("/", "/foo", "/foo/bar").forEach(path -> { ContentResponse r = send(client.newRequest("localhost", connector.getLocalPort()) - .scheme(scenario.getScheme()) - .path(path) - .header(headerName, "1") - .timeout(5, TimeUnit.SECONDS)); + .scheme(scenario.getScheme()) + .path(path) + .header(headerName, "1") + .timeout(5, TimeUnit.SECONDS)); assertEquals(HttpStatus.OK_200, r.getStatus()); }); } @@ -260,19 +259,19 @@ public class HttpCookieTest extends AbstractHttpClientServerTest }); ContentResponse response = send(client.newRequest("localhost", connector.getLocalPort()) - .scheme(scenario.getScheme()) - .path("/foo/bar") - .header(headerName, "0") - .timeout(5, TimeUnit.SECONDS)); + .scheme(scenario.getScheme()) + .path("/foo/bar") + .header(headerName, "0") + .timeout(5, TimeUnit.SECONDS)); assertEquals(HttpStatus.OK_200, response.getStatus()); Arrays.asList("/", "/foo", "/foo/", "/foobar", "/foo/bar", "/foo/bar/baz").forEach(path -> { ContentResponse r = send(client.newRequest("localhost", connector.getLocalPort()) - .scheme(scenario.getScheme()) - .path(path) - .header(headerName, "1") - .timeout(5, TimeUnit.SECONDS)); + .scheme(scenario.getScheme()) + .path(path) + .header(headerName, "1") + .timeout(5, TimeUnit.SECONDS)); assertEquals(HttpStatus.OK_200, r.getStatus()); }); } @@ -321,19 +320,19 @@ public class HttpCookieTest extends AbstractHttpClientServerTest }); ContentResponse response = send(client.newRequest("localhost", connector.getLocalPort()) - .scheme(scenario.getScheme()) - .path("/foo") - .header(headerName, "0") - .timeout(5, TimeUnit.SECONDS)); + .scheme(scenario.getScheme()) + .path("/foo") + .header(headerName, "0") + .timeout(5, TimeUnit.SECONDS)); assertEquals(HttpStatus.OK_200, response.getStatus()); Arrays.asList("/", "/foo", "/foo/bar", "/foo/bar/", "/foo/barbaz").forEach(path -> { ContentResponse r = send(client.newRequest("localhost", connector.getLocalPort()) - .scheme(scenario.getScheme()) - .path(path) - .header(headerName, "1") - .timeout(5, TimeUnit.SECONDS)); + .scheme(scenario.getScheme()) + .path(path) + .header(headerName, "1") + .timeout(5, TimeUnit.SECONDS)); assertEquals(HttpStatus.OK_200, r.getStatus()); }); } @@ -382,19 +381,19 @@ public class HttpCookieTest extends AbstractHttpClientServerTest }); ContentResponse response = send(client.newRequest("localhost", connector.getLocalPort()) - .scheme(scenario.getScheme()) - .path("/foo/bar") - .header(headerName, "0") - .timeout(5, TimeUnit.SECONDS)); + .scheme(scenario.getScheme()) + .path("/foo/bar") + .header(headerName, "0") + .timeout(5, TimeUnit.SECONDS)); assertEquals(HttpStatus.OK_200, response.getStatus()); Arrays.asList("/", "/foo", "/foo/", "/foobar", "/foo/bar").forEach(path -> { ContentResponse r = send(client.newRequest("localhost", connector.getLocalPort()) - .scheme(scenario.getScheme()) - .path(path) - .header(headerName, "1") - .timeout(5, TimeUnit.SECONDS)); + .scheme(scenario.getScheme()) + .path(path) + .header(headerName, "1") + .timeout(5, TimeUnit.SECONDS)); assertEquals(HttpStatus.OK_200, r.getStatus()); }); } @@ -445,19 +444,19 @@ public class HttpCookieTest extends AbstractHttpClientServerTest }); ContentResponse response = send(client.newRequest("localhost", connector.getLocalPort()) - .scheme(scenario.getScheme()) - .path("/foo") - .header(headerName, "0") - .timeout(5, TimeUnit.SECONDS)); + .scheme(scenario.getScheme()) + .path("/foo") + .header(headerName, "0") + .timeout(5, TimeUnit.SECONDS)); assertEquals(HttpStatus.OK_200, response.getStatus()); Arrays.asList("/", "/foo", "/foo/bar").forEach(path -> { ContentResponse r = send(client.newRequest("localhost", connector.getLocalPort()) - .scheme(scenario.getScheme()) - .path(path) - .header(headerName, "1") - .timeout(5, TimeUnit.SECONDS)); + .scheme(scenario.getScheme()) + .path(path) + .header(headerName, "1") + .timeout(5, TimeUnit.SECONDS)); assertEquals(HttpStatus.OK_200, r.getStatus()); }); } @@ -515,19 +514,19 @@ public class HttpCookieTest extends AbstractHttpClientServerTest }); ContentResponse response = send(client.newRequest("localhost", connector.getLocalPort()) - .scheme(scenario.getScheme()) - .path("/foo") - .header(headerName, "0") - .timeout(5, TimeUnit.SECONDS)); + .scheme(scenario.getScheme()) + .path("/foo") + .header(headerName, "0") + .timeout(5, TimeUnit.SECONDS)); assertEquals(HttpStatus.OK_200, response.getStatus()); Arrays.asList("/", "/foo", "/foo/bar", "/bar", "/bar/foo").forEach(path -> { ContentResponse r = send(client.newRequest("localhost", connector.getLocalPort()) - .scheme(scenario.getScheme()) - .path(path) - .header(headerName, "1") - .timeout(5, TimeUnit.SECONDS)); + .scheme(scenario.getScheme()) + .path(path) + .header(headerName, "1") + .timeout(5, TimeUnit.SECONDS)); assertEquals(HttpStatus.OK_200, r.getStatus()); }); } @@ -588,19 +587,19 @@ public class HttpCookieTest extends AbstractHttpClientServerTest }); ContentResponse response = send(client.newRequest("localhost", connector.getLocalPort()) - .scheme(scenario.getScheme()) - .path("/foo") - .header(headerName, "0") - .timeout(5, TimeUnit.SECONDS)); + .scheme(scenario.getScheme()) + .path("/foo") + .header(headerName, "0") + .timeout(5, TimeUnit.SECONDS)); assertEquals(HttpStatus.OK_200, response.getStatus()); Arrays.asList("/", "/foo", "/foo/bar").forEach(path -> { ContentResponse r = send(client.newRequest("localhost", connector.getLocalPort()) - .scheme(scenario.getScheme()) - .path(path) - .header(headerName, "1") - .timeout(5, TimeUnit.SECONDS)); + .scheme(scenario.getScheme()) + .path(path) + .header(headerName, "1") + .timeout(5, TimeUnit.SECONDS)); assertEquals(HttpStatus.OK_200, r.getStatus()); }); } @@ -649,19 +648,19 @@ public class HttpCookieTest extends AbstractHttpClientServerTest }); ContentResponse response = send(client.newRequest("localhost", connector.getLocalPort()) - .scheme(scenario.getScheme()) - .path("/foo/bar") - .header(headerName, "0") - .timeout(5, TimeUnit.SECONDS)); + .scheme(scenario.getScheme()) + .path("/foo/bar") + .header(headerName, "0") + .timeout(5, TimeUnit.SECONDS)); assertEquals(HttpStatus.OK_200, response.getStatus()); Arrays.asList("/", "/foo", "/foo/", "/foobar", "/foo/bar").forEach(path -> { ContentResponse r = send(client.newRequest("localhost", connector.getLocalPort()) - .scheme(scenario.getScheme()) - .path(path) - .header(headerName, "1") - .timeout(5, TimeUnit.SECONDS)); + .scheme(scenario.getScheme()) + .path(path) + .header(headerName, "1") + .timeout(5, TimeUnit.SECONDS)); assertEquals(HttpStatus.OK_200, r.getStatus()); }); } diff --git a/jetty-client/src/test/java/org/eclipse/jetty/client/HttpRequestAbortTest.java b/jetty-client/src/test/java/org/eclipse/jetty/client/HttpRequestAbortTest.java index b9c4c82f5f3..199e4cb003e 100644 --- a/jetty-client/src/test/java/org/eclipse/jetty/client/HttpRequestAbortTest.java +++ b/jetty-client/src/test/java/org/eclipse/jetty/client/HttpRequestAbortTest.java @@ -25,7 +25,6 @@ import java.util.concurrent.ExecutionException; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicReference; - import javax.servlet.DispatcherType; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; @@ -56,10 +55,11 @@ public class HttpRequestAbortTest extends AbstractHttpClientServerTest Exception failure = new Exception("oops"); - ExecutionException x = assertThrows(ExecutionException.class, ()->{ + ExecutionException x = assertThrows(ExecutionException.class, () -> + { Request request = client.newRequest("localhost", connector.getLocalPort()) - .scheme(scenario.getScheme()) - .timeout(5, TimeUnit.SECONDS); + .scheme(scenario.getScheme()) + .timeout(5, TimeUnit.SECONDS); request.abort(failure); request.send(); }); @@ -84,26 +84,27 @@ public class HttpRequestAbortTest extends AbstractHttpClientServerTest final CountDownLatch latch = new CountDownLatch(1); final AtomicBoolean begin = new AtomicBoolean(); - ExecutionException x = assertThrows(ExecutionException.class, ()->{ + ExecutionException x = assertThrows(ExecutionException.class, () -> + { client.newRequest("localhost", connector.getLocalPort()) - .scheme(scenario.getScheme()) - .listener(new Request.Listener.Adapter() + .scheme(scenario.getScheme()) + .listener(new Request.Listener.Adapter() + { + @Override + public void onQueued(Request request) { - @Override - public void onQueued(Request request) - { - aborted.set(request.abort(cause)); - latch.countDown(); - } + aborted.set(request.abort(cause)); + latch.countDown(); + } - @Override - public void onBegin(Request request) - { - begin.set(true); - } - }) - .timeout(5, TimeUnit.SECONDS) - .send(); + @Override + public void onBegin(Request request) + { + begin.set(true); + } + }) + .timeout(5, TimeUnit.SECONDS) + .send(); }); assertTrue(latch.await(5, TimeUnit.SECONDS)); @@ -129,26 +130,27 @@ public class HttpRequestAbortTest extends AbstractHttpClientServerTest final CountDownLatch latch = new CountDownLatch(1); final CountDownLatch committed = new CountDownLatch(1); - ExecutionException x = assertThrows(ExecutionException.class, ()->{ + ExecutionException x = assertThrows(ExecutionException.class, () -> + { client.newRequest("localhost", connector.getLocalPort()) - .scheme(scenario.getScheme()) - .listener(new Request.Listener.Adapter() + .scheme(scenario.getScheme()) + .listener(new Request.Listener.Adapter() + { + @Override + public void onBegin(Request request) { - @Override - public void onBegin(Request request) - { - aborted.set(request.abort(cause)); - latch.countDown(); - } + aborted.set(request.abort(cause)); + latch.countDown(); + } - @Override - public void onCommit(Request request) - { - committed.countDown(); - } - }) - .timeout(5, TimeUnit.SECONDS) - .send(); + @Override + public void onCommit(Request request) + { + committed.countDown(); + } + }) + .timeout(5, TimeUnit.SECONDS) + .send(); }); assertTrue(latch.await(5, TimeUnit.SECONDS)); if (aborted.get()) @@ -173,26 +175,27 @@ public class HttpRequestAbortTest extends AbstractHttpClientServerTest final CountDownLatch latch = new CountDownLatch(1); final CountDownLatch committed = new CountDownLatch(1); - ExecutionException x = assertThrows(ExecutionException.class, ()->{ + ExecutionException x = assertThrows(ExecutionException.class, () -> + { client.newRequest("localhost", connector.getLocalPort()) - .scheme(scenario.getScheme()) - .listener(new Request.Listener.Adapter() + .scheme(scenario.getScheme()) + .listener(new Request.Listener.Adapter() + { + @Override + public void onHeaders(Request request) { - @Override - public void onHeaders(Request request) - { - aborted.set(request.abort(cause)); - latch.countDown(); - } + aborted.set(request.abort(cause)); + latch.countDown(); + } - @Override - public void onCommit(Request request) - { - committed.countDown(); - } - }) - .timeout(5, TimeUnit.SECONDS) - .send(); + @Override + public void onCommit(Request request) + { + committed.countDown(); + } + }) + .timeout(5, TimeUnit.SECONDS) + .send(); }); assertTrue(latch.await(5, TimeUnit.SECONDS)); if (aborted.get()) @@ -219,16 +222,17 @@ public class HttpRequestAbortTest extends AbstractHttpClientServerTest final Throwable cause = new Exception(); final AtomicBoolean aborted = new AtomicBoolean(); final CountDownLatch latch = new CountDownLatch(1); - ExecutionException x = assertThrows(ExecutionException.class, ()->{ + ExecutionException x = assertThrows(ExecutionException.class, () -> + { client.newRequest("localhost", connector.getLocalPort()) - .scheme(scenario.getScheme()) - .onRequestCommit(request -> - { - aborted.set(request.abort(cause)); - latch.countDown(); - }) - .timeout(5, TimeUnit.SECONDS) - .send(); + .scheme(scenario.getScheme()) + .onRequestCommit(request -> + { + aborted.set(request.abort(cause)); + latch.countDown(); + }) + .timeout(5, TimeUnit.SECONDS) + .send(); }); assertTrue(latch.await(5, TimeUnit.SECONDS)); if (aborted.get()) @@ -269,24 +273,25 @@ public class HttpRequestAbortTest extends AbstractHttpClientServerTest final AtomicBoolean aborted = new AtomicBoolean(); final CountDownLatch latch = new CountDownLatch(1); - ExecutionException x = assertThrows(ExecutionException.class, ()->{ + ExecutionException x = assertThrows(ExecutionException.class, () -> + { client.newRequest("localhost", connector.getLocalPort()) - .scheme(scenario.getScheme()) - .onRequestCommit(request -> - { - aborted.set(request.abort(cause)); - latch.countDown(); - }) - .content(new ByteBufferContentProvider(ByteBuffer.wrap(new byte[]{0}), ByteBuffer.wrap(new byte[]{1})) - { - @Override - public long getLength() + .scheme(scenario.getScheme()) + .onRequestCommit(request -> { - return -1; - } - }) - .timeout(5, TimeUnit.SECONDS) - .send(); + aborted.set(request.abort(cause)); + latch.countDown(); + }) + .content(new ByteBufferContentProvider(ByteBuffer.wrap(new byte[]{0}), ByteBuffer.wrap(new byte[]{1})) + { + @Override + public long getLength() + { + return -1; + } + }) + .timeout(5, TimeUnit.SECONDS) + .send(); }); assertTrue(latch.await(5, TimeUnit.SECONDS)); if (aborted.get()) @@ -297,7 +302,6 @@ public class HttpRequestAbortTest extends AbstractHttpClientServerTest assertEquals(0, connectionPool.getConnectionCount()); assertEquals(0, connectionPool.getActiveConnections().size()); assertEquals(0, connectionPool.getIdleConnections().size()); - } @ParameterizedTest @@ -327,24 +331,25 @@ public class HttpRequestAbortTest extends AbstractHttpClientServerTest final Throwable cause = new Exception(); final AtomicBoolean aborted = new AtomicBoolean(); final CountDownLatch latch = new CountDownLatch(1); - ExecutionException x = assertThrows(ExecutionException.class, ()->{ + ExecutionException x = assertThrows(ExecutionException.class, () -> + { client.newRequest("localhost", connector.getLocalPort()) - .scheme(scenario.getScheme()) - .onRequestContent((request, content) -> + .scheme(scenario.getScheme()) + .onRequestContent((request, content) -> + { + aborted.set(request.abort(cause)); + latch.countDown(); + }) + .content(new ByteBufferContentProvider(ByteBuffer.wrap(new byte[]{0}), ByteBuffer.wrap(new byte[]{1})) + { + @Override + public long getLength() { - aborted.set(request.abort(cause)); - latch.countDown(); - }) - .content(new ByteBufferContentProvider(ByteBuffer.wrap(new byte[]{0}), ByteBuffer.wrap(new byte[]{1})) - { - @Override - public long getLength() - { - return -1; - } - }) - .timeout(5, TimeUnit.SECONDS) - .send(); + return -1; + } + }) + .timeout(5, TimeUnit.SECONDS) + .send(); }); assertTrue(latch.await(5, TimeUnit.SECONDS)); if (aborted.get()) @@ -384,8 +389,8 @@ public class HttpRequestAbortTest extends AbstractHttpClientServerTest }); Request request = client.newRequest("localhost", connector.getLocalPort()) - .timeout(3 * delay, TimeUnit.MILLISECONDS) - .scheme(scenario.getScheme()); + .timeout(3 * delay, TimeUnit.MILLISECONDS) + .scheme(scenario.getScheme()); final Thread thread = Thread.currentThread(); new Thread(() -> @@ -401,7 +406,7 @@ public class HttpRequestAbortTest extends AbstractHttpClientServerTest } }).start(); - assertThrows(InterruptedException.class, ()->request.send()); + assertThrows(InterruptedException.class, () -> request.send()); } @ParameterizedTest @@ -428,8 +433,8 @@ public class HttpRequestAbortTest extends AbstractHttpClientServerTest }); final Request request = client.newRequest("localhost", connector.getLocalPort()) - .timeout(3 * delay, TimeUnit.MILLISECONDS) - .scheme(scenario.getScheme()); + .timeout(3 * delay, TimeUnit.MILLISECONDS) + .scheme(scenario.getScheme()); final Throwable cause = new Exception(); final AtomicBoolean aborted = new AtomicBoolean(); @@ -492,8 +497,8 @@ public class HttpRequestAbortTest extends AbstractHttpClientServerTest final Throwable cause = new Exception(); final CountDownLatch latch = new CountDownLatch(1); Request request = client.newRequest("localhost", connector.getLocalPort()) - .scheme(scenario.getScheme()) - .timeout(3 * delay, TimeUnit.MILLISECONDS); + .scheme(scenario.getScheme()) + .timeout(3 * delay, TimeUnit.MILLISECONDS); request.send(result -> { assertTrue(result.isFailed()); @@ -547,12 +552,13 @@ public class HttpRequestAbortTest extends AbstractHttpClientServerTest } }); - ExecutionException e = assertThrows(ExecutionException.class,()->{ + ExecutionException e = assertThrows(ExecutionException.class, () -> + { client.newRequest("localhost", connector.getLocalPort()) - .scheme(scenario.getScheme()) - .path("/redirect") - .timeout(5, TimeUnit.SECONDS) - .send(); + .scheme(scenario.getScheme()) + .path("/redirect") + .timeout(5, TimeUnit.SECONDS) + .send(); }); assertTrue(latch.await(5, TimeUnit.SECONDS)); if (aborted.get()) diff --git a/jetty-client/src/test/java/org/eclipse/jetty/client/HttpResponseAbortTest.java b/jetty-client/src/test/java/org/eclipse/jetty/client/HttpResponseAbortTest.java index 1b47b763127..9689576f38c 100644 --- a/jetty-client/src/test/java/org/eclipse/jetty/client/HttpResponseAbortTest.java +++ b/jetty-client/src/test/java/org/eclipse/jetty/client/HttpResponseAbortTest.java @@ -18,16 +18,12 @@ package org.eclipse.jetty.client; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertTrue; - import java.io.IOException; import java.io.OutputStream; import java.nio.ByteBuffer; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; - import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; @@ -38,6 +34,9 @@ import org.eclipse.jetty.server.handler.AbstractHandler; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.ArgumentsSource; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + public class HttpResponseAbortTest extends AbstractHttpClientServerTest { @ParameterizedTest @@ -48,13 +47,13 @@ public class HttpResponseAbortTest extends AbstractHttpClientServerTest final CountDownLatch latch = new CountDownLatch(1); client.newRequest("localhost", connector.getLocalPort()) - .scheme(scenario.getScheme()) - .onResponseBegin(response -> response.abort(new Exception())) - .send(result -> - { - assertTrue(result.isFailed()); - latch.countDown(); - }); + .scheme(scenario.getScheme()) + .onResponseBegin(response -> response.abort(new Exception())) + .send(result -> + { + assertTrue(result.isFailed()); + latch.countDown(); + }); assertTrue(latch.await(5, TimeUnit.SECONDS)); } @@ -66,17 +65,17 @@ public class HttpResponseAbortTest extends AbstractHttpClientServerTest final CountDownLatch latch = new CountDownLatch(1); client.newRequest("localhost", connector.getLocalPort()) - .scheme(scenario.getScheme()) - .onResponseHeader((response, field) -> - { - response.abort(new Exception()); - return true; - }) - .send(result -> - { - assertTrue(result.isFailed()); - latch.countDown(); - }); + .scheme(scenario.getScheme()) + .onResponseHeader((response, field) -> + { + response.abort(new Exception()); + return true; + }) + .send(result -> + { + assertTrue(result.isFailed()); + latch.countDown(); + }); assertTrue(latch.await(5, TimeUnit.SECONDS)); } @@ -88,13 +87,13 @@ public class HttpResponseAbortTest extends AbstractHttpClientServerTest final CountDownLatch latch = new CountDownLatch(1); client.newRequest("localhost", connector.getLocalPort()) - .scheme(scenario.getScheme()) - .onResponseHeaders(response -> response.abort(new Exception())) - .send(result -> - { - assertTrue(result.isFailed()); - latch.countDown(); - }); + .scheme(scenario.getScheme()) + .onResponseHeaders(response -> response.abort(new Exception())) + .send(result -> + { + assertTrue(result.isFailed()); + latch.countDown(); + }); assertTrue(latch.await(5, TimeUnit.SECONDS)); } @@ -125,13 +124,13 @@ public class HttpResponseAbortTest extends AbstractHttpClientServerTest final CountDownLatch latch = new CountDownLatch(1); client.newRequest("localhost", connector.getLocalPort()) - .scheme(scenario.getScheme()) - .onResponseContent((response, content) -> response.abort(new Exception())) - .send(result -> - { - assertTrue(result.isFailed()); - latch.countDown(); - }); + .scheme(scenario.getScheme()) + .onResponseContent((response, content) -> response.abort(new Exception())) + .send(result -> + { + assertTrue(result.isFailed()); + latch.countDown(); + }); assertTrue(latch.await(5, TimeUnit.SECONDS)); } @@ -164,28 +163,28 @@ public class HttpResponseAbortTest extends AbstractHttpClientServerTest final AtomicInteger completes = new AtomicInteger(); final CountDownLatch completeLatch = new CountDownLatch(1); client.newRequest("localhost", connector.getLocalPort()) - .scheme(scenario.getScheme()) - .content(contentProvider) - .onResponseContent((response, content) -> + .scheme(scenario.getScheme()) + .content(contentProvider) + .onResponseContent((response, content) -> + { + try { - try - { - response.abort(new Exception()); - contentProvider.close(); - // Delay to let the request side to finish its processing. - Thread.sleep(1000); - } - catch (InterruptedException x) - { - x.printStackTrace(); - } - }) - .send(result -> + response.abort(new Exception()); + contentProvider.close(); + // Delay to let the request side to finish its processing. + Thread.sleep(1000); + } + catch (InterruptedException x) { - completes.incrementAndGet(); - assertTrue(result.isFailed()); - completeLatch.countDown(); - }); + x.printStackTrace(); + } + }) + .send(result -> + { + completes.incrementAndGet(); + assertTrue(result.isFailed()); + completeLatch.countDown(); + }); assertTrue(completeLatch.await(5, TimeUnit.SECONDS)); // Wait to be sure that the complete event is only notified once. diff --git a/jetty-client/src/test/java/org/eclipse/jetty/client/HttpResponseConcurrentAbortTest.java b/jetty-client/src/test/java/org/eclipse/jetty/client/HttpResponseConcurrentAbortTest.java index 8df01c6715e..d74f919ae83 100644 --- a/jetty-client/src/test/java/org/eclipse/jetty/client/HttpResponseConcurrentAbortTest.java +++ b/jetty-client/src/test/java/org/eclipse/jetty/client/HttpResponseConcurrentAbortTest.java @@ -18,15 +18,12 @@ package org.eclipse.jetty.client; -import static org.junit.jupiter.api.Assertions.assertTrue; - import java.io.IOException; import java.io.OutputStream; import java.nio.ByteBuffer; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; - import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; @@ -39,6 +36,8 @@ import org.eclipse.jetty.server.handler.AbstractHandler; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.ArgumentsSource; +import static org.junit.jupiter.api.Assertions.assertTrue; + public class HttpResponseConcurrentAbortTest extends AbstractHttpClientServerTest { private final CountDownLatch callbackLatch = new CountDownLatch(1); @@ -54,16 +53,16 @@ public class HttpResponseConcurrentAbortTest extends AbstractHttpClientServerTes start(scenario, new EmptyServerHandler()); client.newRequest("localhost", connector.getLocalPort()) - .scheme(scenario.getScheme()) - .onResponseBegin(new Response.BeginListener() + .scheme(scenario.getScheme()) + .onResponseBegin(new Response.BeginListener() + { + @Override + public void onBegin(Response response) { - @Override - public void onBegin(Response response) - { - abort(response); - } - }) - .send(new TestResponseListener()); + abort(response); + } + }) + .send(new TestResponseListener()); assertTrue(callbackLatch.await(5, TimeUnit.SECONDS)); assertTrue(completeLatch.await(5, TimeUnit.SECONDS)); assertTrue(failureWasAsync.get()); @@ -77,17 +76,17 @@ public class HttpResponseConcurrentAbortTest extends AbstractHttpClientServerTes start(scenario, new EmptyServerHandler()); client.newRequest("localhost", connector.getLocalPort()) - .scheme(scenario.getScheme()) - .onResponseHeader(new Response.HeaderListener() + .scheme(scenario.getScheme()) + .onResponseHeader(new Response.HeaderListener() + { + @Override + public boolean onHeader(Response response, HttpField field) { - @Override - public boolean onHeader(Response response, HttpField field) - { - abort(response); - return true; - } - }) - .send(new TestResponseListener()); + abort(response); + return true; + } + }) + .send(new TestResponseListener()); assertTrue(callbackLatch.await(5, TimeUnit.SECONDS)); assertTrue(completeLatch.await(5, TimeUnit.SECONDS)); assertTrue(failureWasAsync.get()); @@ -101,16 +100,16 @@ public class HttpResponseConcurrentAbortTest extends AbstractHttpClientServerTes start(scenario, new EmptyServerHandler()); client.newRequest("localhost", connector.getLocalPort()) - .scheme(scenario.getScheme()) - .onResponseHeaders(new Response.HeadersListener() + .scheme(scenario.getScheme()) + .onResponseHeaders(new Response.HeadersListener() + { + @Override + public void onHeaders(Response response) { - @Override - public void onHeaders(Response response) - { - abort(response); - } - }) - .send(new TestResponseListener()); + abort(response); + } + }) + .send(new TestResponseListener()); assertTrue(callbackLatch.await(5, TimeUnit.SECONDS)); assertTrue(completeLatch.await(5, TimeUnit.SECONDS)); assertTrue(failureWasAsync.get()); @@ -134,16 +133,16 @@ public class HttpResponseConcurrentAbortTest extends AbstractHttpClientServerTes }); client.newRequest("localhost", connector.getLocalPort()) - .scheme(scenario.getScheme()) - .onResponseContent(new Response.ContentListener() + .scheme(scenario.getScheme()) + .onResponseContent(new Response.ContentListener() + { + @Override + public void onContent(Response response, ByteBuffer content) { - @Override - public void onContent(Response response, ByteBuffer content) - { - abort(response); - } - }) - .send(new TestResponseListener()); + abort(response); + } + }) + .send(new TestResponseListener()); assertTrue(callbackLatch.await(5, TimeUnit.SECONDS)); assertTrue(completeLatch.await(5, TimeUnit.SECONDS)); assertTrue(failureWasAsync.get()); diff --git a/jetty-client/src/test/java/org/eclipse/jetty/client/LivelockTest.java b/jetty-client/src/test/java/org/eclipse/jetty/client/LivelockTest.java index 1440e975427..ff4caaa6fc1 100644 --- a/jetty-client/src/test/java/org/eclipse/jetty/client/LivelockTest.java +++ b/jetty-client/src/test/java/org/eclipse/jetty/client/LivelockTest.java @@ -18,8 +18,6 @@ package org.eclipse.jetty.client; -import static org.junit.jupiter.api.Assertions.assertTrue; - import java.nio.channels.Selector; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; @@ -42,6 +40,8 @@ import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.Arguments; import org.junit.jupiter.params.provider.MethodSource; +import static org.junit.jupiter.api.Assertions.assertTrue; + public class LivelockTest { public static Stream modes() @@ -71,7 +71,7 @@ public class LivelockTest server.setHandler(handler); server.start(); } - + @AfterEach public void after() throws Exception { @@ -90,7 +90,7 @@ public class LivelockTest // NonBlocking actions are submitted to both the client and server // ManagedSelectors that submit themselves in an attempt to cause a live lock // as there will always be an action available to run. - + int count = 5; HttpClientTransport transport = new HttpClientTransportOverHTTP(1); client = new HttpClient(transport); @@ -103,7 +103,7 @@ public class LivelockTest clientThreads.setName("client"); client.setExecutor(clientThreads); client.start(); - + AtomicBoolean busy = new AtomicBoolean(true); if (clientLiveLock) @@ -125,19 +125,19 @@ public class LivelockTest for (int i = 0; i < count; ++i) { client.newRequest("localhost", connector.getLocalPort()) - .path("/" + i) - .send(result -> + .path("/" + i) + .send(result -> + { + if (result.isSucceeded() && result.getResponse().getStatus() == HttpStatus.OK_200) + latch.countDown(); + else { - if (result.isSucceeded() && result.getResponse().getStatus() == HttpStatus.OK_200) - latch.countDown(); - else - { - if(result.getRequestFailure() != null) - clientLog.warn(result.getRequestFailure()); - if(result.getResponseFailure() != null) - clientLog.warn(result.getResponseFailure()); - } - }); + if (result.getRequestFailure() != null) + clientLog.warn(result.getRequestFailure()); + if (result.getResponseFailure() != null) + clientLog.warn(result.getResponseFailure()); + } + }); sleep(pause); } assertTrue(latch.await(2 * pause * count, TimeUnit.MILLISECONDS)); diff --git a/jetty-client/src/test/java/org/eclipse/jetty/client/ServerConnectionCloseTest.java b/jetty-client/src/test/java/org/eclipse/jetty/client/ServerConnectionCloseTest.java index 2869e72b293..7a4b646fc4e 100644 --- a/jetty-client/src/test/java/org/eclipse/jetty/client/ServerConnectionCloseTest.java +++ b/jetty-client/src/test/java/org/eclipse/jetty/client/ServerConnectionCloseTest.java @@ -110,22 +110,22 @@ public class ServerConnectionCloseTest consumeRequest(input); OutputStream output = socket.getOutputStream(); - String serverResponse = "" + - "HTTP/1.1 200 OK\r\n" + + String serverResponse = + "HTTP/1.1 200 OK\r\n" + "Connection: close\r\n"; if (chunked) { - serverResponse += "" + - "Transfer-Encoding: chunked\r\n" + + serverResponse += + "Transfer-Encoding: chunked\r\n" + "\r\n"; for (int i = 0; i < 2; ++i) { serverResponse += - Integer.toHexString(content.length()) + "\r\n" + - content + "\r\n"; + Integer.toHexString(content.length()) + "\r\n" + + content + "\r\n"; } - serverResponse += "" + - "0\r\n" + + serverResponse += + "0\r\n" + "\r\n"; } else diff --git a/jetty-client/src/test/java/org/eclipse/jetty/client/Socks4ProxyTest.java b/jetty-client/src/test/java/org/eclipse/jetty/client/Socks4ProxyTest.java index c405029f675..df56547514c 100644 --- a/jetty-client/src/test/java/org/eclipse/jetty/client/Socks4ProxyTest.java +++ b/jetty-client/src/test/java/org/eclipse/jetty/client/Socks4ProxyTest.java @@ -18,9 +18,6 @@ package org.eclipse.jetty.client; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertTrue; - import java.net.InetSocketAddress; import java.nio.ByteBuffer; import java.nio.channels.ServerSocketChannel; @@ -30,10 +27,12 @@ import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; import org.junit.jupiter.api.AfterEach; - import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + public class Socks4ProxyTest { private ServerSocketChannel server; @@ -73,14 +72,14 @@ public class Socks4ProxyTest String method = "GET"; String path = "/path"; client.newRequest(serverHost, serverPort) - .method(method) - .path(path) - .timeout(5, TimeUnit.SECONDS) - .send(result -> - { - if (result.isSucceeded()) - latch.countDown(); - }); + .method(method) + .path(path) + .timeout(5, TimeUnit.SECONDS) + .send(result -> + { + if (result.isSucceeded()) + latch.countDown(); + }); try (SocketChannel channel = server.accept()) { @@ -107,8 +106,8 @@ public class Socks4ProxyTest assertEquals(method + " " + path, StandardCharsets.UTF_8.decode(buffer).toString()); // Response - String response = "" + - "HTTP/1.1 200 OK\r\n" + + String response = + "HTTP/1.1 200 OK\r\n" + "Content-Length: 0\r\n" + "Connection: close\r\n" + "\r\n"; @@ -130,16 +129,16 @@ public class Socks4ProxyTest int serverPort = proxyPort + 1; // Any port will do String method = "GET"; client.newRequest(serverHost, serverPort) - .method(method) - .path("/path") - .timeout(5, TimeUnit.SECONDS) - .send(result -> - { - if (result.isSucceeded()) - latch.countDown(); - else - result.getFailure().printStackTrace(); - }); + .method(method) + .path("/path") + .timeout(5, TimeUnit.SECONDS) + .send(result -> + { + if (result.isSucceeded()) + latch.countDown(); + else + result.getFailure().printStackTrace(); + }); try (SocketChannel channel = server.accept()) { @@ -165,8 +164,8 @@ public class Socks4ProxyTest assertEquals(method, StandardCharsets.UTF_8.decode(buffer).toString()); // Response - String response = "" + - "HTTP/1.1 200 OK\r\n" + + String response = + "HTTP/1.1 200 OK\r\n" + "Content-Length: 0\r\n" + "Connection: close\r\n" + "\r\n"; diff --git a/jetty-client/src/test/java/org/eclipse/jetty/client/TLSServerConnectionCloseTest.java b/jetty-client/src/test/java/org/eclipse/jetty/client/TLSServerConnectionCloseTest.java index 9568b69eb28..18cfa42cf07 100644 --- a/jetty-client/src/test/java/org/eclipse/jetty/client/TLSServerConnectionCloseTest.java +++ b/jetty-client/src/test/java/org/eclipse/jetty/client/TLSServerConnectionCloseTest.java @@ -24,7 +24,6 @@ import java.io.OutputStream; import java.net.ServerSocket; import java.net.Socket; import java.util.concurrent.TimeUnit; - import javax.net.ssl.SSLContext; import javax.net.ssl.SSLSocket; @@ -116,22 +115,22 @@ public class TLSServerConnectionCloseTest consumeRequest(input); OutputStream output = sslSocket.getOutputStream(); - String serverResponse = "" + - "HTTP/1.1 200 OK\r\n" + + String serverResponse = + "HTTP/1.1 200 OK\r\n" + "Connection: close\r\n"; if (chunked) { - serverResponse += "" + - "Transfer-Encoding: chunked\r\n" + + serverResponse += + "Transfer-Encoding: chunked\r\n" + "\r\n"; for (int i = 0; i < 2; ++i) { serverResponse += - Integer.toHexString(content.length()) + "\r\n" + - content + "\r\n"; + Integer.toHexString(content.length()) + "\r\n" + + content + "\r\n"; } - serverResponse += "" + - "0\r\n" + + serverResponse += + "0\r\n" + "\r\n"; } else diff --git a/jetty-client/src/test/java/org/eclipse/jetty/client/ValidatingConnectionPoolTest.java b/jetty-client/src/test/java/org/eclipse/jetty/client/ValidatingConnectionPoolTest.java index 8df67a63849..d187de8a521 100644 --- a/jetty-client/src/test/java/org/eclipse/jetty/client/ValidatingConnectionPoolTest.java +++ b/jetty-client/src/test/java/org/eclipse/jetty/client/ValidatingConnectionPoolTest.java @@ -18,12 +18,9 @@ package org.eclipse.jetty.client; -import static org.junit.jupiter.api.Assertions.assertEquals; - import java.io.IOException; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; - import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; @@ -39,6 +36,8 @@ import org.eclipse.jetty.server.handler.AbstractHandler; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.ArgumentsSource; +import static org.junit.jupiter.api.Assertions.assertEquals; + public class ValidatingConnectionPoolTest extends AbstractHttpClientServerTest { @Override @@ -46,7 +45,7 @@ public class ValidatingConnectionPoolTest extends AbstractHttpClientServerTest { long timeout = 1000; transport.setConnectionPoolFactory(destination -> - new ValidatingConnectionPool(destination, destination.getHttpClient().getMaxConnectionsPerDestination(), destination, destination.getHttpClient().getScheduler(), timeout)); + new ValidatingConnectionPool(destination, destination.getHttpClient().getMaxConnectionsPerDestination(), destination, destination.getHttpClient().getScheduler(), timeout)); return super.newHttpClient(transport); } @@ -60,14 +59,14 @@ public class ValidatingConnectionPoolTest extends AbstractHttpClientServerTest client.setMaxConnectionsPerDestination(1); ContentResponse response = client.newRequest("localhost", connector.getLocalPort()) - .scheme(scenario.getScheme()) - .send(); + .scheme(scenario.getScheme()) + .send(); assertEquals(200, response.getStatus()); // The second request should be sent after the validating timeout. response = client.newRequest("localhost", connector.getLocalPort()) - .scheme(scenario.getScheme()) - .send(); + .scheme(scenario.getScheme()) + .send(); assertEquals(200, response.getStatus()); } @@ -99,9 +98,9 @@ public class ValidatingConnectionPoolTest extends AbstractHttpClientServerTest }); ContentResponse response = client.newRequest("localhost", connector.getLocalPort()) - .scheme(scenario.getScheme()) - .path("/redirect") - .send(); + .scheme(scenario.getScheme()) + .path("/redirect") + .send(); assertEquals(200, response.getStatus()); } @@ -147,25 +146,25 @@ public class ValidatingConnectionPoolTest extends AbstractHttpClientServerTest final CountDownLatch latch = new CountDownLatch(1); Request request1 = client.newRequest("localhost", connector.getLocalPort()) - .scheme(scenario.getScheme()) - .path("/one") - .onRequestBegin(r -> + .scheme(scenario.getScheme()) + .path("/one") + .onRequestBegin(r -> + { + try { - try - { - latch.await(); - } - catch (InterruptedException x) - { - r.abort(x); - } - }); + latch.await(); + } + catch (InterruptedException x) + { + r.abort(x); + } + }); FutureResponseListener listener1 = new FutureResponseListener(request1); request1.send(listener1); Request request2 = client.newRequest("localhost", connector.getLocalPort()) - .scheme(scenario.getScheme()) - .path("/two"); + .scheme(scenario.getScheme()) + .path("/two"); FutureResponseListener listener2 = new FutureResponseListener(request2); request2.send(listener2); diff --git a/jetty-client/src/test/java/org/eclipse/jetty/client/api/Usage.java b/jetty-client/src/test/java/org/eclipse/jetty/client/api/Usage.java index a567a2cb2f6..30030887a32 100644 --- a/jetty-client/src/test/java/org/eclipse/jetty/client/api/Usage.java +++ b/jetty-client/src/test/java/org/eclipse/jetty/client/api/Usage.java @@ -18,10 +18,6 @@ package org.eclipse.jetty.client.api; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertNotNull; -import static org.junit.jupiter.api.Assertions.assertTrue; - import java.io.ByteArrayInputStream; import java.io.InputStream; import java.io.OutputStream; @@ -45,10 +41,13 @@ import org.eclipse.jetty.client.util.OutputStreamContentProvider; import org.eclipse.jetty.http.HttpMethod; import org.eclipse.jetty.http.HttpVersion; import org.eclipse.jetty.util.FuturePromise; - import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.Test; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertTrue; + @Disabled public class Usage { @@ -76,15 +75,15 @@ public class Usage // Address must be provided, it's the only thing non defaultable Request request = client.newRequest("localhost", 8080) - .scheme("https") - .method(HttpMethod.GET) - .path("/uri") - .version(HttpVersion.HTTP_1_1) - .param("a", "b") - .header("X-Header", "Y-value") - .agent("Jetty HTTP Client") - .idleTimeout(5000, TimeUnit.MILLISECONDS) - .timeout(20, TimeUnit.SECONDS); + .scheme("https") + .method(HttpMethod.GET) + .path("/uri") + .version(HttpVersion.HTTP_1_1) + .param("a", "b") + .header("X-Header", "Y-value") + .agent("Jetty HTTP Client") + .idleTimeout(5000, TimeUnit.MILLISECONDS) + .timeout(20, TimeUnit.SECONDS); ContentResponse response = request.send(); assertEquals(200, response.getStatus()); @@ -100,19 +99,19 @@ public class Usage final CountDownLatch latch = new CountDownLatch(1); client.newRequest("localhost", 8080) - // Send asynchronously - .send(new Response.CompleteListener() - { - @Override - public void onComplete(Result result) + // Send asynchronously + .send(new Response.CompleteListener() { - if (result.isSucceeded()) + @Override + public void onComplete(Result result) { - responseRef.set(result.getResponse()); - latch.countDown(); + if (result.isSucceeded()) + { + responseRef.set(result.getResponse()); + latch.countDown(); + } } - } - }); + }); assertTrue(latch.await(5, TimeUnit.SECONDS)); Response response = responseRef.get(); @@ -137,14 +136,14 @@ public class Usage client.start(); Response response = client.newRequest("localhost", 8080) - // Add a request listener - .listener(new Request.Listener.Adapter() + // Add a request listener + .listener(new Request.Listener.Adapter() + { + @Override + public void onSuccess(Request request) { - @Override - public void onSuccess(Request request) - { - } - }).send(); + } + }).send(); assertEquals(200, response.getStatus()); } @@ -226,10 +225,10 @@ public class Usage client.setFollowRedirects(false); ContentResponse response = client.newRequest("localhost", 8080) - // Follow redirects for this request only - .followRedirects(true) - .timeout(5, TimeUnit.SECONDS) - .send(); + // Follow redirects for this request only + .followRedirects(true) + .timeout(5, TimeUnit.SECONDS) + .send(); assertEquals(200, response.getStatus()); } @@ -277,9 +276,9 @@ public class Usage InputStream input = new ByteArrayInputStream("content".getBytes(StandardCharsets.UTF_8)); ContentResponse response = client.newRequest("localhost", 8080) - // Provide the content as InputStream - .content(new InputStreamContentProvider(input)) - .send(); + // Provide the content as InputStream + .content(new InputStreamContentProvider(input)) + .send(); assertEquals(200, response.getStatus()); } @@ -294,15 +293,15 @@ public class Usage try (OutputStream output = content.getOutputStream()) { client.newRequest("localhost", 8080) - .content(content) - .send(new Response.CompleteListener() + .content(content) + .send(new Response.CompleteListener() + { + @Override + public void onComplete(Result result) { - @Override - public void onComplete(Result result) - { - assertEquals(200, result.getResponse().getStatus()); - } - }); + assertEquals(200, result.getResponse().getStatus()); + } + }); output.write(new byte[1024]); output.write(new byte[512]); @@ -323,16 +322,16 @@ public class Usage final AtomicBoolean sendContent = new AtomicBoolean(true); DeferredContentProvider async = new DeferredContentProvider(ByteBuffer.wrap(new byte[]{0, 1, 2})); client.newRequest("localhost", 8080) - .content(async) - .send(new Response.Listener.Adapter() + .content(async) + .send(new Response.Listener.Adapter() + { + @Override + public void onBegin(Response response) { - @Override - public void onBegin(Response response) - { - if (response.getStatus() == 404) - sendContent.set(false); - } - }); + if (response.getStatus() == 404) + sendContent.set(false); + } + }); Thread.sleep(100); diff --git a/jetty-client/src/test/java/org/eclipse/jetty/client/http/HttpDestinationOverHTTPTest.java b/jetty-client/src/test/java/org/eclipse/jetty/client/http/HttpDestinationOverHTTPTest.java index d2ecbe95d57..e146ea90056 100644 --- a/jetty-client/src/test/java/org/eclipse/jetty/client/http/HttpDestinationOverHTTPTest.java +++ b/jetty-client/src/test/java/org/eclipse/jetty/client/http/HttpDestinationOverHTTPTest.java @@ -58,7 +58,7 @@ public class HttpDestinationOverHTTPTest extends AbstractHttpClientServerTest { start(scenario, new EmptyServerHandler()); - try(HttpDestination destination = new DuplexHttpDestination(client, new Origin("http", "localhost", connector.getLocalPort()))) + try (HttpDestination destination = new DuplexHttpDestination(client, new Origin("http", "localhost", connector.getLocalPort()))) { destination.start(); DuplexConnectionPool connectionPool = (DuplexConnectionPool)destination.getConnectionPool(); @@ -78,7 +78,7 @@ public class HttpDestinationOverHTTPTest extends AbstractHttpClientServerTest { start(scenario, new EmptyServerHandler()); - try(HttpDestination destination = new DuplexHttpDestination(client, new Origin("http", "localhost", connector.getLocalPort()))) + try (HttpDestination destination = new DuplexHttpDestination(client, new Origin("http", "localhost", connector.getLocalPort()))) { destination.start(); @@ -159,7 +159,7 @@ public class HttpDestinationOverHTTPTest extends AbstractHttpClientServerTest { start(scenario, new EmptyServerHandler()); - try(HttpDestination destination = new DuplexHttpDestination(client, new Origin("http", "localhost", connector.getLocalPort()))) + try (HttpDestination destination = new DuplexHttpDestination(client, new Origin("http", "localhost", connector.getLocalPort()))) { destination.start(); DuplexConnectionPool connectionPool = (DuplexConnectionPool)destination.getConnectionPool(); @@ -169,14 +169,14 @@ public class HttpDestinationOverHTTPTest extends AbstractHttpClientServerTest connection1 = peekIdleConnection(connectionPool, 5, TimeUnit.SECONDS); assertNotNull(connection1); // Acquire the connection to make it active. - assertSame(connection1, connectionPool.acquire(),"From idle"); + assertSame(connection1, connectionPool.acquire(), "From idle"); } destination.process(connection1); destination.release(connection1); Connection connection2 = connectionPool.acquire(); - assertSame(connection1, connection2,"After release"); + assertSame(connection1, connection2, "After release"); } } @@ -188,7 +188,7 @@ public class HttpDestinationOverHTTPTest extends AbstractHttpClientServerTest long idleTimeout = 1000; startClient(scenario, httpClient -> httpClient.setIdleTimeout(idleTimeout)); - try(HttpDestination destination = new DuplexHttpDestination(client, new Origin("http", "localhost", connector.getLocalPort()))) + try (HttpDestination destination = new DuplexHttpDestination(client, new Origin("http", "localhost", connector.getLocalPort()))) { destination.start(); DuplexConnectionPool connectionPool = (DuplexConnectionPool)destination.getConnectionPool(); @@ -219,34 +219,34 @@ public class HttpDestinationOverHTTPTest extends AbstractHttpClientServerTest // Make one request to open the connection and be sure everything is setup properly ContentResponse response = client.newRequest("localhost", connector.getLocalPort()) - .scheme(scheme) - .send(); + .scheme(scheme) + .send(); assertEquals(200, response.getStatus()); // Send another request that is sent immediately CountDownLatch successLatch = new CountDownLatch(1); CountDownLatch failureLatch = new CountDownLatch(1); client.newRequest("localhost", connector.getLocalPort()) - .scheme(scheme) - .path("/one") - .onRequestQueued(request -> - { - // This request exceeds the maximum queued, should fail - client.newRequest("localhost", connector.getLocalPort()) - .scheme(scheme) - .path("/two") - .send(result -> - { - assertTrue(result.isFailed()); - assertThat(result.getRequestFailure(), Matchers.instanceOf(RejectedExecutionException.class)); - failureLatch.countDown(); - }); - }) - .send(result -> - { - if (result.isSucceeded()) - successLatch.countDown(); - }); + .scheme(scheme) + .path("/one") + .onRequestQueued(request -> + { + // This request exceeds the maximum queued, should fail + client.newRequest("localhost", connector.getLocalPort()) + .scheme(scheme) + .path("/two") + .send(result -> + { + assertTrue(result.isFailed()); + assertThat(result.getRequestFailure(), Matchers.instanceOf(RejectedExecutionException.class)); + failureLatch.countDown(); + }); + }) + .send(result -> + { + if (result.isSucceeded()) + successLatch.countDown(); + }); assertTrue(failureLatch.await(5, TimeUnit.SECONDS)); assertTrue(successLatch.await(5, TimeUnit.SECONDS)); @@ -263,9 +263,9 @@ public class HttpDestinationOverHTTPTest extends AbstractHttpClientServerTest Destination destinationBefore = client.getDestination(scenario.getScheme(), host, port); ContentResponse response = client.newRequest(host, port) - .scheme(scenario.getScheme()) - .header(HttpHeader.CONNECTION, HttpHeaderValue.CLOSE.asString()) - .send(); + .scheme(scenario.getScheme()) + .header(HttpHeader.CONNECTION, HttpHeaderValue.CLOSE.asString()) + .send(); assertEquals(200, response.getStatus()); @@ -275,9 +275,9 @@ public class HttpDestinationOverHTTPTest extends AbstractHttpClientServerTest client.setRemoveIdleDestinations(true); response = client.newRequest(host, port) - .scheme(scenario.getScheme()) - .header(HttpHeader.CONNECTION, HttpHeaderValue.CLOSE.asString()) - .send(); + .scheme(scenario.getScheme()) + .header(HttpHeader.CONNECTION, HttpHeaderValue.CLOSE.asString()) + .send(); assertEquals(200, response.getStatus()); diff --git a/jetty-client/src/test/java/org/eclipse/jetty/client/http/HttpReceiverOverHTTPTest.java b/jetty-client/src/test/java/org/eclipse/jetty/client/http/HttpReceiverOverHTTPTest.java index 739e1bde451..60f788e0482 100644 --- a/jetty-client/src/test/java/org/eclipse/jetty/client/http/HttpReceiverOverHTTPTest.java +++ b/jetty-client/src/test/java/org/eclipse/jetty/client/http/HttpReceiverOverHTTPTest.java @@ -57,23 +57,23 @@ import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; public class HttpReceiverOverHTTPTest -{ +{ private HttpClient client; private HttpDestination destination; private ByteArrayEndPoint endPoint; private HttpConnectionOverHTTP connection; - + public static Stream complianceModes() throws Exception { return Stream.of( - HttpCompliance.RFC7230, - HttpCompliance.RFC2616, - HttpCompliance.LEGACY, - HttpCompliance.RFC2616_LEGACY, - HttpCompliance.RFC7230_LEGACY + HttpCompliance.RFC7230, + HttpCompliance.RFC2616, + HttpCompliance.LEGACY, + HttpCompliance.RFC2616_LEGACY, + HttpCompliance.RFC7230_LEGACY ).map(Arguments::of); } - + public void init(HttpCompliance compliance) throws Exception { client = new HttpClient(); @@ -109,8 +109,8 @@ public class HttpReceiverOverHTTPTest public void test_Receive_NoResponseContent(HttpCompliance compliance) throws Exception { init(compliance); - endPoint.addInput("" + - "HTTP/1.1 200 OK\r\n" + + endPoint.addInput( + "HTTP/1.1 200 OK\r\n" + "Content-length: 0\r\n" + "\r\n"); HttpExchange exchange = newExchange(); @@ -134,8 +134,8 @@ public class HttpReceiverOverHTTPTest { init(compliance); String content = "0123456789ABCDEF"; - endPoint.addInput("" + - "HTTP/1.1 200 OK\r\n" + + endPoint.addInput( + "HTTP/1.1 200 OK\r\n" + "Content-length: " + content.length() + "\r\n" + "\r\n" + content); @@ -163,8 +163,8 @@ public class HttpReceiverOverHTTPTest init(compliance); String content1 = "0123456789"; String content2 = "ABCDEF"; - endPoint.addInput("" + - "HTTP/1.1 200 OK\r\n" + + endPoint.addInput( + "HTTP/1.1 200 OK\r\n" + "Content-length: " + (content1.length() + content2.length()) + "\r\n" + "\r\n" + content1); @@ -174,7 +174,7 @@ public class HttpReceiverOverHTTPTest endPoint.addInputEOF(); connection.getHttpChannel().receive(); - ExecutionException e = assertThrows(ExecutionException.class, ()->listener.get(5, TimeUnit.SECONDS)); + ExecutionException e = assertThrows(ExecutionException.class, () -> listener.get(5, TimeUnit.SECONDS)); assertThat(e.getCause(), instanceOf(EOFException.class)); } @@ -183,8 +183,8 @@ public class HttpReceiverOverHTTPTest public void test_Receive_ResponseContent_IdleTimeout(HttpCompliance compliance) throws Exception { init(compliance); - endPoint.addInput("" + - "HTTP/1.1 200 OK\r\n" + + endPoint.addInput( + "HTTP/1.1 200 OK\r\n" + "Content-length: 1\r\n" + "\r\n"); HttpExchange exchange = newExchange(); @@ -195,7 +195,7 @@ public class HttpReceiverOverHTTPTest Thread.sleep(100); connection.onIdleExpired(); - ExecutionException e = assertThrows(ExecutionException.class, ()->listener.get(5, TimeUnit.SECONDS)); + ExecutionException e = assertThrows(ExecutionException.class, () -> listener.get(5, TimeUnit.SECONDS)); assertThat(e.getCause(), instanceOf(TimeoutException.class)); } @@ -204,18 +204,18 @@ public class HttpReceiverOverHTTPTest public void test_Receive_BadResponse(HttpCompliance compliance) throws Exception { init(compliance); - endPoint.addInput("" + - "HTTP/1.1 200 OK\r\n" + + endPoint.addInput( + "HTTP/1.1 200 OK\r\n" + "Content-length: A\r\n" + "\r\n"); HttpExchange exchange = newExchange(); FutureResponseListener listener = (FutureResponseListener)exchange.getResponseListeners().get(0); connection.getHttpChannel().receive(); - ExecutionException e = assertThrows(ExecutionException.class, ()->listener.get(5, TimeUnit.SECONDS)); + ExecutionException e = assertThrows(ExecutionException.class, () -> listener.get(5, TimeUnit.SECONDS)); assertThat(e.getCause(), instanceOf(HttpResponseException.class)); - assertThat(e.getCause().getCause(),instanceOf(BadMessageException.class)); - assertThat(e.getCause().getCause().getCause(),instanceOf(NumberFormatException.class)); + assertThat(e.getCause().getCause(), instanceOf(BadMessageException.class)); + assertThat(e.getCause().getCause().getCause(), instanceOf(NumberFormatException.class)); } @ParameterizedTest @@ -251,10 +251,10 @@ public class HttpReceiverOverHTTPTest } }; endPoint.setConnection(connection); - + // Partial response to trigger the call to fillInterested(). - endPoint.addInput("" + - "HTTP/1.1 200 OK\r\n" + + endPoint.addInput( + "HTTP/1.1 200 OK\r\n" + "Content-Length: 1\r\n" + "\r\n"); diff --git a/jetty-client/src/test/java/org/eclipse/jetty/client/http/HttpSenderOverHTTPTest.java b/jetty-client/src/test/java/org/eclipse/jetty/client/http/HttpSenderOverHTTPTest.java index 0e79a5820af..3707264edc4 100644 --- a/jetty-client/src/test/java/org/eclipse/jetty/client/http/HttpSenderOverHTTPTest.java +++ b/jetty-client/src/test/java/org/eclipse/jetty/client/http/HttpSenderOverHTTPTest.java @@ -258,7 +258,7 @@ public class HttpSenderOverHTTPTest String requestString = endPoint.takeOutputString(); assertTrue(requestString.startsWith("GET ")); - assertThat(requestString,Matchers.endsWith("\r\n\r\n" + content1 + content2)); + assertThat(requestString, Matchers.endsWith("\r\n\r\n" + content1 + content2)); assertTrue(headersLatch.await(5, TimeUnit.SECONDS)); assertTrue(successLatch.await(5, TimeUnit.SECONDS)); } diff --git a/jetty-client/src/test/java/org/eclipse/jetty/client/jmx/HttpClientJMXTest.java b/jetty-client/src/test/java/org/eclipse/jetty/client/jmx/HttpClientJMXTest.java index d799ad4c1a5..c5d254cc3c3 100644 --- a/jetty-client/src/test/java/org/eclipse/jetty/client/jmx/HttpClientJMXTest.java +++ b/jetty-client/src/test/java/org/eclipse/jetty/client/jmx/HttpClientJMXTest.java @@ -18,21 +18,19 @@ package org.eclipse.jetty.client.jmx; -import static org.junit.jupiter.api.Assertions.assertEquals; - import java.lang.management.ManagementFactory; import java.util.Locale; import java.util.Set; - import javax.management.MBeanServer; import javax.management.ObjectName; import org.eclipse.jetty.client.HttpClient; import org.eclipse.jetty.io.SelectorManager; import org.eclipse.jetty.jmx.MBeanContainer; - import org.junit.jupiter.api.Test; +import static org.junit.jupiter.api.Assertions.assertEquals; + public class HttpClientJMXTest { @Test @@ -62,7 +60,9 @@ public class HttpClientJMXTest pattern = new ObjectName(domain + ":*"); objectNames = mbeanServer.queryNames(pattern, null); for (ObjectName oName : objectNames) + { assertEquals(name, oName.getKeyProperty("context")); + } } finally { diff --git a/jetty-client/src/test/java/org/eclipse/jetty/client/ssl/NeedWantClientAuthTest.java b/jetty-client/src/test/java/org/eclipse/jetty/client/ssl/NeedWantClientAuthTest.java index ab32beb6b9f..d65f030d581 100644 --- a/jetty-client/src/test/java/org/eclipse/jetty/client/ssl/NeedWantClientAuthTest.java +++ b/jetty-client/src/test/java/org/eclipse/jetty/client/ssl/NeedWantClientAuthTest.java @@ -21,7 +21,6 @@ package org.eclipse.jetty.client.ssl; import java.security.cert.Certificate; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; - import javax.net.ssl.SSLException; import javax.net.ssl.SSLHandshakeException; import javax.net.ssl.SSLSession; @@ -113,8 +112,8 @@ public class NeedWantClientAuthTest startClient(clientSSL); ContentResponse response = client.newRequest("https://localhost:" + connector.getLocalPort()) - .timeout(10, TimeUnit.SECONDS) - .send(); + .timeout(10, TimeUnit.SECONDS) + .send(); assertEquals(HttpStatus.OK_200, response.getStatus()); } @@ -152,8 +151,8 @@ public class NeedWantClientAuthTest startClient(clientSSL); ContentResponse response = client.newRequest("https://localhost:" + connector.getLocalPort()) - .timeout(10, TimeUnit.SECONDS) - .send(); + .timeout(10, TimeUnit.SECONDS) + .send(); assertEquals(HttpStatus.OK_200, response.getStatus()); assertTrue(handshakeLatch.await(10, TimeUnit.SECONDS)); @@ -195,16 +194,16 @@ public class NeedWantClientAuthTest CountDownLatch latch = new CountDownLatch(1); client.newRequest("https://localhost:" + connector.getLocalPort()) - .timeout(10, TimeUnit.SECONDS) - .send(result -> + .timeout(10, TimeUnit.SECONDS) + .send(result -> + { + if (result.isFailed()) { - if (result.isFailed()) - { - Throwable failure = result.getFailure(); - if (failure instanceof SSLException) - latch.countDown(); - } - }); + Throwable failure = result.getFailure(); + if (failure instanceof SSLException) + latch.countDown(); + } + }); assertTrue(handshakeLatch.await(10, TimeUnit.SECONDS)); assertTrue(latch.await(10, TimeUnit.SECONDS)); @@ -243,8 +242,8 @@ public class NeedWantClientAuthTest startClient(clientSSL); ContentResponse response = client.newRequest("https://localhost:" + connector.getLocalPort()) - .timeout(10, TimeUnit.SECONDS) - .send(); + .timeout(10, TimeUnit.SECONDS) + .send(); assertEquals(HttpStatus.OK_200, response.getStatus()); assertTrue(handshakeLatch.await(10, TimeUnit.SECONDS)); diff --git a/jetty-client/src/test/java/org/eclipse/jetty/client/ssl/SslBytesClientTest.java b/jetty-client/src/test/java/org/eclipse/jetty/client/ssl/SslBytesClientTest.java index 9bcdedbd375..f055df1e0e3 100644 --- a/jetty-client/src/test/java/org/eclipse/jetty/client/ssl/SslBytesClientTest.java +++ b/jetty-client/src/test/java/org/eclipse/jetty/client/ssl/SslBytesClientTest.java @@ -30,7 +30,6 @@ import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; - import javax.net.ssl.SSLContext; import javax.net.ssl.SSLServerSocket; import javax.net.ssl.SSLSocket; @@ -168,13 +167,15 @@ public class SslBytesClientTest extends SslBytesTest String line = reader.readLine(); assertTrue(line.startsWith("GET")); while (line.length() > 0) + { line = reader.readLine(); + } // Write response OutputStream output = server.getOutputStream(); output.write(("HTTP/1.1 200 OK\r\n" + - "Content-Length: 0\r\n" + - "\r\n").getBytes(StandardCharsets.UTF_8)); + "Content-Length: 0\r\n" + + "\r\n").getBytes(StandardCharsets.UTF_8)); output.flush(); assertTrue(automaticProxyFlow.stop(5, TimeUnit.SECONDS)); @@ -211,7 +212,9 @@ public class SslBytesClientTest extends SslBytesTest String line = reader.readLine(); assertTrue(line.startsWith("GET")); while (line.length() > 0) + { line = reader.readLine(); + } OutputStream serverOutput = server.getOutputStream(); byte[] data1 = new byte[1024]; @@ -222,10 +225,10 @@ public class SslBytesClientTest extends SslBytesTest final String content2 = new String(data2, StandardCharsets.UTF_8); // Write first part of the response serverOutput.write(("HTTP/1.1 200 OK\r\n" + - "Content-Type: text/plain\r\n" + - "Content-Length: " + (content1.length() + content2.length()) + "\r\n" + - "\r\n" + - content1).getBytes(StandardCharsets.UTF_8)); + "Content-Type: text/plain\r\n" + + "Content-Length: " + (content1.length() + content2.length()) + "\r\n" + + "\r\n" + + content1).getBytes(StandardCharsets.UTF_8)); serverOutput.flush(); assertTrue(automaticProxyFlow.stop(5, TimeUnit.SECONDS)); @@ -319,7 +322,9 @@ public class SslBytesClientTest extends SslBytesTest String line = reader.readLine(); assertTrue(line.startsWith("GET")); while (line.length() > 0) + { line = reader.readLine(); + } OutputStream serverOutput = server.getOutputStream(); byte[] data1 = new byte[1024]; @@ -330,10 +335,10 @@ public class SslBytesClientTest extends SslBytesTest final String content2 = new String(data2, StandardCharsets.UTF_8); // Write first part of the response serverOutput.write(("HTTP/1.1 200 OK\r\n" + - "Content-Type: text/plain\r\n" + - "Content-Length: " + (content1.length() + content2.length()) + "\r\n" + - "\r\n" + - content1).getBytes(StandardCharsets.UTF_8)); + "Content-Type: text/plain\r\n" + + "Content-Length: " + (content1.length() + content2.length()) + "\r\n" + + "\r\n" + + content1).getBytes(StandardCharsets.UTF_8)); serverOutput.flush(); assertTrue(automaticProxyFlow.stop(5, TimeUnit.SECONDS)); diff --git a/jetty-client/src/test/java/org/eclipse/jetty/client/ssl/SslBytesServerTest.java b/jetty-client/src/test/java/org/eclipse/jetty/client/ssl/SslBytesServerTest.java index 874718cb8c9..01b4c7b801a 100644 --- a/jetty-client/src/test/java/org/eclipse/jetty/client/ssl/SslBytesServerTest.java +++ b/jetty-client/src/test/java/org/eclipse/jetty/client/ssl/SslBytesServerTest.java @@ -39,7 +39,6 @@ import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicReference; import java.util.regex.Matcher; import java.util.regex.Pattern; - import javax.net.ssl.SSLContext; import javax.net.ssl.SSLEngine; import javax.net.ssl.SSLSocket; @@ -117,7 +116,7 @@ public class SslBytesServerTest extends SslBytesTest sslFlushes.set(0); httpParses.set(0); serverEndPoint.set(null); - + File keyStore = MavenTestingUtils.getTestResourceFile("keystore.jks"); sslContextFactory = new SslContextFactory.Server(); sslContextFactory.setKeyStorePath(keyStore.getAbsolutePath()); @@ -133,7 +132,7 @@ public class SslBytesServerTest extends SslBytesTest @Override protected HttpParser newHttpParser(HttpCompliance compliance) { - return new HttpParser(newRequestHandler(), getHttpConfiguration().getRequestHeaderSize(),compliance) + return new HttpParser(newRequestHandler(), getHttpConfiguration().getRequestHeaderSize(), compliance) { @Override public boolean parseNext(ByteBuffer buffer) @@ -187,12 +186,12 @@ public class SslBytesServerTest extends SslBytesTest } }; - ServerConnector connector = new ServerConnector(server, null,null,null,1,1,sslFactory, httpFactory) + ServerConnector connector = new ServerConnector(server, null, null, null, 1, 1, sslFactory, httpFactory) { @Override protected ChannelEndPoint newEndPoint(SocketChannel channel, ManagedSelector selectSet, SelectionKey key) throws IOException { - ChannelEndPoint endp = super.newEndPoint(channel,selectSet,key); + ChannelEndPoint endp = super.newEndPoint(channel, selectSet, key); serverEndPoint.set(endp); return endp; } @@ -484,10 +483,10 @@ public class SslBytesServerTest extends SslBytesTest // Socket close record = proxy.readFromServer(); - if (record!=null) + if (record != null) { - assertEquals(record.getType(),Type.ALERT); - + assertEquals(record.getType(), Type.ALERT); + // Now should be a raw close record = proxy.readFromServer(); assertNull(record, String.valueOf(record)); @@ -582,8 +581,8 @@ public class SslBytesServerTest extends SslBytesTest threadPool.submit(() -> { OutputStream clientOutput = client.getOutputStream(); - clientOutput.write(("" + - "GET / HTTP/1.1\r\n" + + clientOutput.write(( + "GET / HTTP/1.1\r\n" + "Host: localhost\r\n" + "\r\n").getBytes(StandardCharsets.UTF_8)); clientOutput.flush(); @@ -620,8 +619,8 @@ public class SslBytesServerTest extends SslBytesTest Future request = threadPool.submit(() -> { OutputStream clientOutput = client.getOutputStream(); - clientOutput.write(("" + - "GET / HTTP/1.1\r\n" + + clientOutput.write(( + "GET / HTTP/1.1\r\n" + "Host: localhost\r\n" + "\r\n").getBytes(StandardCharsets.UTF_8)); clientOutput.flush(); @@ -671,7 +670,9 @@ public class SslBytesServerTest extends SslBytesTest // Client Hello TLSRecord record = proxy.readFromClient(); for (byte b : record.getBytes()) + { proxy.flushToServer(5, b); + } // Server Hello + Certificate + Server Done record = proxy.readFromServer(); @@ -680,17 +681,23 @@ public class SslBytesServerTest extends SslBytesTest // Client Key Exchange record = proxy.readFromClient(); for (byte b : record.getBytes()) - proxy.flushToServer(5,b); + { + proxy.flushToServer(5, b); + } // Change Cipher Spec record = proxy.readFromClient(); for (byte b : record.getBytes()) + { proxy.flushToServer(5, b); + } // Client Done record = proxy.readFromClient(); for (byte b : record.getBytes()) + { proxy.flushToServer(5, b); + } // Change Cipher Spec record = proxy.readFromServer(); @@ -705,8 +712,8 @@ public class SslBytesServerTest extends SslBytesTest Future request = threadPool.submit(() -> { OutputStream clientOutput = client.getOutputStream(); - clientOutput.write(("" + - "GET / HTTP/1.1\r\n" + + clientOutput.write(( + "GET / HTTP/1.1\r\n" + "Host: localhost\r\n" + "\r\n").getBytes(StandardCharsets.UTF_8)); clientOutput.flush(); @@ -716,7 +723,9 @@ public class SslBytesServerTest extends SslBytesTest // Application data record = proxy.readFromClient(); for (byte b : record.getBytes()) + { proxy.flushToServer(5, b); + } assertNull(request.get(1, TimeUnit.SECONDS)); // Application data @@ -747,7 +756,9 @@ public class SslBytesServerTest extends SslBytesTest // Close Alert record = proxy.readFromClient(); for (byte b : record.getBytes()) + { proxy.flushToServer(5, b); + } // Socket close record = proxy.readFromClient(); assertNull(record, String.valueOf(record)); @@ -756,10 +767,10 @@ public class SslBytesServerTest extends SslBytesTest // Socket close record = proxy.readFromServer(); // Raw close or alert - if (record!=null) + if (record != null) { - assertEquals(record.getType(),Type.ALERT); - + assertEquals(record.getType(), Type.ALERT); + // Now should be a raw close record = proxy.readFromServer(); assertNull(record, String.valueOf(record)); @@ -779,8 +790,8 @@ public class SslBytesServerTest extends SslBytesTest Future request = threadPool.submit(() -> { OutputStream clientOutput = client.getOutputStream(); - clientOutput.write(("" + - "GET / HTTP/1.1\r\n" + + clientOutput.write(( + "GET / HTTP/1.1\r\n" + "Host: localhost\r\n" + "\r\n").getBytes(StandardCharsets.UTF_8)); clientOutput.flush(); @@ -812,10 +823,10 @@ public class SslBytesServerTest extends SslBytesTest // Socket close record = proxy.readFromServer(); - if (record!=null) + if (record != null) { - assertEquals(record.getType(),Type.ALERT); - + assertEquals(record.getType(), Type.ALERT); + // Now should be a raw close record = proxy.readFromServer(); assertNull(record, String.valueOf(record)); @@ -850,8 +861,8 @@ public class SslBytesServerTest extends SslBytesTest Future request = threadPool.submit(() -> { OutputStream clientOutput = client.getOutputStream(); - clientOutput.write(("" + - "GET / HTTP/1.1\r\n" + + clientOutput.write(( + "GET / HTTP/1.1\r\n" + "Host: localhost\r\n" + "\r\n").getBytes(StandardCharsets.UTF_8)); clientOutput.flush(); @@ -883,10 +894,10 @@ public class SslBytesServerTest extends SslBytesTest // Socket close record = proxy.readFromServer(); - if (record!=null) + if (record != null) { - assertEquals(record.getType(),Type.ALERT); - + assertEquals(record.getType(), Type.ALERT); + // Now should be a raw close record = proxy.readFromServer(); assertNull(record, String.valueOf(record)); @@ -916,8 +927,8 @@ public class SslBytesServerTest extends SslBytesTest Future request = threadPool.submit(() -> { OutputStream clientOutput = client.getOutputStream(); - clientOutput.write(("" + - "GET / HTTP/1.1\r\n" + + clientOutput.write(( + "GET / HTTP/1.1\r\n" + "Host: localhost\r\n" + "\r\n").getBytes(StandardCharsets.UTF_8)); clientOutput.flush(); @@ -941,10 +952,10 @@ public class SslBytesServerTest extends SslBytesTest // Expect raw close from server OR ALERT record = proxy.readFromServer(); // TODO check that this is OK? - if (record!=null) + if (record != null) { - assertEquals(record.getType(),Type.ALERT); - + assertEquals(record.getType(), Type.ALERT); + // Now should be a raw close record = proxy.readFromServer(); assertNull(record, String.valueOf(record)); @@ -971,8 +982,8 @@ public class SslBytesServerTest extends SslBytesTest Future request = threadPool.submit(() -> { OutputStream clientOutput = client.getOutputStream(); - clientOutput.write(("" + - "GET / HTTP/1.1\r\n" + + clientOutput.write(( + "GET / HTTP/1.1\r\n" + "Host: localhost\r\n" + "\r\n").getBytes(StandardCharsets.UTF_8)); clientOutput.flush(); @@ -994,10 +1005,10 @@ public class SslBytesServerTest extends SslBytesTest // Expect raw close from server record = proxy.readFromServer(); - if (record!=null) + if (record != null) { - assertEquals(record.getType(),Type.ALERT); - + assertEquals(record.getType(), Type.ALERT); + // Now should be a raw close record = proxy.readFromServer(); assertNull(record, String.valueOf(record)); @@ -1028,8 +1039,8 @@ public class SslBytesServerTest extends SslBytesTest Future request = threadPool.submit(() -> { OutputStream clientOutput = client.getOutputStream(); - clientOutput.write(("" + - "GET /echo HTTP/1.1\r\n" + + clientOutput.write(( + "GET /echo HTTP/1.1\r\n" + "Host: localhost\r\n" + "Content-Length: " + content.length() + "\r\n" + "\r\n" + @@ -1083,8 +1094,8 @@ public class SslBytesServerTest extends SslBytesTest Future request = threadPool.submit(() -> { OutputStream clientOutput = client.getOutputStream(); - clientOutput.write(("" + - "GET /echo_suppress_exception HTTP/1.1\r\n" + + clientOutput.write(( + "GET /echo_suppress_exception HTTP/1.1\r\n" + "Host: localhost\r\n" + "Content-Length: " + content.length() + "\r\n" + "\r\n" + @@ -1140,8 +1151,8 @@ public class SslBytesServerTest extends SslBytesTest Future request = threadPool.submit(() -> { OutputStream clientOutput = client.getOutputStream(); - clientOutput.write(("" + - "GET / HTTP/1.1\r\n" + + clientOutput.write(( + "GET / HTTP/1.1\r\n" + "Host: localhost\r\n" + "\r\n").getBytes(StandardCharsets.UTF_8)); clientOutput.flush(); @@ -1182,10 +1193,10 @@ public class SslBytesServerTest extends SslBytesTest // Socket close record = proxy.readFromServer(); - if (record!=null) + if (record != null) { - assertEquals(record.getType(),Type.ALERT); - + assertEquals(record.getType(), Type.ALERT); + // Now should be a raw close record = proxy.readFromServer(); assertNull(record, String.valueOf(record)); @@ -1212,8 +1223,8 @@ public class SslBytesServerTest extends SslBytesTest Future request = threadPool.submit(() -> { OutputStream clientOutput = client.getOutputStream(); - clientOutput.write(("" + - "POST / HTTP/1.1\r\n" + + clientOutput.write(( + "POST / HTTP/1.1\r\n" + "Host: localhost\r\n" + "Content-Type: text/plain\r\n" + "Content-Length: " + content.length() + "\r\n" + @@ -1274,8 +1285,8 @@ public class SslBytesServerTest extends SslBytesTest Future request = threadPool.submit(() -> { OutputStream clientOutput = client.getOutputStream(); - clientOutput.write(("" + - "POST / HTTP/1.1\r\n" + + clientOutput.write(( + "POST / HTTP/1.1\r\n" + "Host: localhost\r\n" + "Content-Type: text/plain\r\n" + "Content-Length: " + content.length() + "\r\n" + @@ -1353,8 +1364,8 @@ public class SslBytesServerTest extends SslBytesTest // Write only part of the body automaticProxyFlow = proxy.startAutomaticFlow(); - clientOutput.write(("" + - "POST / HTTP/1.1\r\n" + + clientOutput.write(( + "POST / HTTP/1.1\r\n" + "Host: localhost\r\n" + "Content-Type: text/plain\r\n" + "Content-Length: " + (content1.length() + content2.length()) + "\r\n" + @@ -1376,12 +1387,13 @@ public class SslBytesServerTest extends SslBytesTest proxy.flushToServer(record); // Renegotiation not allowed, server has closed - loop: while(true) + loop: + while (true) { record = proxy.readFromServer(); - if (record==null) + if (record == null) break; - switch(record.getType()) + switch (record.getType()) { case APPLICATION: fail("application data not allows after renegotiate"); @@ -1428,8 +1440,8 @@ public class SslBytesServerTest extends SslBytesTest // Write only part of the body automaticProxyFlow = proxy.startAutomaticFlow(); - clientOutput.write(("" + - "POST / HTTP/1.1\r\n" + + clientOutput.write(( + "POST / HTTP/1.1\r\n" + "Host: localhost\r\n" + "Content-Type: text/plain\r\n" + "Content-Length: " + (content1.length() + content2.length()) + "\r\n" + @@ -1468,7 +1480,7 @@ public class SslBytesServerTest extends SslBytesTest // Trigger a read to have the client write the final renegotiation steps client.setSoTimeout(100); - assertThrows(SocketTimeoutException.class, ()->client.getInputStream().read()); + assertThrows(SocketTimeoutException.class, () -> client.getInputStream().read()); // Renegotiation Change Cipher record = proxy.readFromClient(); @@ -1547,8 +1559,8 @@ public class SslBytesServerTest extends SslBytesTest // Write only part of the body automaticProxyFlow = proxy.startAutomaticFlow(); - clientOutput.write(("" + - "POST / HTTP/1.1\r\n" + + clientOutput.write(( + "POST / HTTP/1.1\r\n" + "Host: localhost\r\n" + "Content-Type: text/plain\r\n" + "Content-Length: " + (content1.length() + content2.length()) + "\r\n" + @@ -1593,7 +1605,7 @@ public class SslBytesServerTest extends SslBytesTest // Trigger a read to have the client write the final renegotiation steps client.setSoTimeout(100); - assertThrows(SocketTimeoutException.class, ()->client.getInputStream().read()); + assertThrows(SocketTimeoutException.class, () -> client.getInputStream().read()); // Renegotiation Change Cipher record = proxy.readFromClient(); @@ -1686,8 +1698,8 @@ public class SslBytesServerTest extends SslBytesTest Arrays.fill(data, (byte)'Y'); String content = new String(data, StandardCharsets.UTF_8); automaticProxyFlow = proxy.startAutomaticFlow(); - clientOutput.write(("" + - "POST / HTTP/1.1\r\n" + + clientOutput.write(( + "POST / HTTP/1.1\r\n" + "Host: localhost\r\n" + "Content-Type: text/plain\r\n" + "Content-Length: " + content.length() + "\r\n" + @@ -1765,13 +1777,13 @@ public class SslBytesServerTest extends SslBytesTest idleHook = () -> { - if (latch.getCount()==0) + if (latch.getCount() == 0) return; try { // Send request - clientOutput.write(("" + - "GET / HTTP/1.1\r\n" + + clientOutput.write(( + "GET / HTTP/1.1\r\n" + "Host: localhost\r\n" + "\r\n").getBytes(StandardCharsets.UTF_8)); clientOutput.flush(); @@ -1856,9 +1868,9 @@ public class SslBytesServerTest extends SslBytesTest // Socket close record = proxy.readFromServer(); - if (record!=null) + if (record != null) { - assertEquals(record.getType(),Type.ALERT); + assertEquals(record.getType(), Type.ALERT); record = proxy.readFromServer(); } assertNull(record); diff --git a/jetty-client/src/test/java/org/eclipse/jetty/client/ssl/SslBytesTest.java b/jetty-client/src/test/java/org/eclipse/jetty/client/ssl/SslBytesTest.java index d326afb71b3..d3c94429527 100644 --- a/jetty-client/src/test/java/org/eclipse/jetty/client/ssl/SslBytesTest.java +++ b/jetty-client/src/test/java/org/eclipse/jetty/client/ssl/SslBytesTest.java @@ -18,8 +18,6 @@ package org.eclipse.jetty.client.ssl; -import static org.junit.jupiter.api.Assertions.assertTrue; - import java.io.EOFException; import java.io.IOException; import java.io.InputStream; @@ -38,6 +36,7 @@ import java.util.concurrent.TimeUnit; import org.eclipse.jetty.util.log.Log; import org.eclipse.jetty.util.log.Logger; +import static org.junit.jupiter.api.Assertions.assertTrue; public abstract class SslBytesTest { @@ -149,7 +148,7 @@ public abstract class SslBytesTest { logger.info(x.getClass() + ": " + x.getMessage()); - if(logger.isDebugEnabled()) + if (logger.isDebugEnabled()) logger.debug(x); } } diff --git a/jetty-client/src/test/java/org/eclipse/jetty/client/ssl/SslConnectionTest.java b/jetty-client/src/test/java/org/eclipse/jetty/client/ssl/SslConnectionTest.java index c0952cebf60..9fa25956d48 100644 --- a/jetty-client/src/test/java/org/eclipse/jetty/client/ssl/SslConnectionTest.java +++ b/jetty-client/src/test/java/org/eclipse/jetty/client/ssl/SslConnectionTest.java @@ -20,7 +20,6 @@ package org.eclipse.jetty.client.ssl; import java.io.File; import java.nio.ByteBuffer; - import javax.net.ssl.SSLEngine; import javax.net.ssl.SSLHandshakeException; @@ -82,6 +81,6 @@ public class SslConnectionTest // We want SSLHandshakeException to be thrown instead, because it is // handled better (it is an IOException) by the Connection code that // reads from the EndPoint. - assertThrows(SSLHandshakeException.class, ()->sslEndPoint.fill(BufferUtil.EMPTY_BUFFER)); + assertThrows(SSLHandshakeException.class, () -> sslEndPoint.fill(BufferUtil.EMPTY_BUFFER)); } } diff --git a/jetty-client/src/test/java/org/eclipse/jetty/client/util/DeferredContentProviderTest.java b/jetty-client/src/test/java/org/eclipse/jetty/client/util/DeferredContentProviderTest.java index d3b638d70a1..b8e26dd99b9 100644 --- a/jetty-client/src/test/java/org/eclipse/jetty/client/util/DeferredContentProviderTest.java +++ b/jetty-client/src/test/java/org/eclipse/jetty/client/util/DeferredContentProviderTest.java @@ -18,10 +18,6 @@ package org.eclipse.jetty.client.util; -import static org.junit.jupiter.api.Assertions.assertFalse; -import static org.junit.jupiter.api.Assertions.assertThrows; -import static org.junit.jupiter.api.Assertions.assertTrue; - import java.nio.ByteBuffer; import java.util.Iterator; import java.util.NoSuchElementException; @@ -37,6 +33,10 @@ import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + public class DeferredContentProviderTest { private ExecutorService executor; @@ -131,7 +131,7 @@ public class DeferredContentProviderTest assertFalse(iterator.hasNext()); - assertThrows(NoSuchElementException.class, ()->iterator.next()); + assertThrows(NoSuchElementException.class, () -> iterator.next()); assertFalse(iterator.hasNext()); } diff --git a/jetty-client/src/test/java/org/eclipse/jetty/client/util/InputStreamContentProviderTest.java b/jetty-client/src/test/java/org/eclipse/jetty/client/util/InputStreamContentProviderTest.java index 3388358bd0b..727edc85687 100644 --- a/jetty-client/src/test/java/org/eclipse/jetty/client/util/InputStreamContentProviderTest.java +++ b/jetty-client/src/test/java/org/eclipse/jetty/client/util/InputStreamContentProviderTest.java @@ -18,11 +18,6 @@ package org.eclipse.jetty.client.util; -import static org.junit.jupiter.api.Assertions.assertFalse; -import static org.junit.jupiter.api.Assertions.assertNotNull; -import static org.junit.jupiter.api.Assertions.assertThrows; -import static org.junit.jupiter.api.Assertions.assertTrue; - import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; @@ -31,9 +26,13 @@ import java.util.Iterator; import java.util.NoSuchElementException; import java.util.concurrent.atomic.AtomicBoolean; - import org.junit.jupiter.api.Test; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + public class InputStreamContentProviderTest { @Test @@ -91,7 +90,7 @@ public class InputStreamContentProviderTest assertNotNull(buffer); - assertThrows(NoSuchElementException.class, ()->iterator.next()); + assertThrows(NoSuchElementException.class, () -> iterator.next()); assertFalse(iterator.hasNext()); assertTrue(closed.get()); @@ -122,7 +121,7 @@ public class InputStreamContentProviderTest assertNotNull(iterator); - assertThrows(NoSuchElementException.class, ()->iterator.next()); + assertThrows(NoSuchElementException.class, () -> iterator.next()); assertFalse(iterator.hasNext()); assertTrue(closed.get()); @@ -154,7 +153,7 @@ public class InputStreamContentProviderTest assertNotNull(iterator); assertTrue(iterator.hasNext()); - assertThrows(NoSuchElementException.class, ()->iterator.next()); + assertThrows(NoSuchElementException.class, () -> iterator.next()); assertFalse(iterator.hasNext()); assertTrue(closed.get()); diff --git a/jetty-client/src/test/java/org/eclipse/jetty/client/util/MultiPartContentProviderTest.java b/jetty-client/src/test/java/org/eclipse/jetty/client/util/MultiPartContentProviderTest.java index 0a2be22490a..e2c34af15ef 100644 --- a/jetty-client/src/test/java/org/eclipse/jetty/client/util/MultiPartContentProviderTest.java +++ b/jetty-client/src/test/java/org/eclipse/jetty/client/util/MultiPartContentProviderTest.java @@ -18,12 +18,6 @@ package org.eclipse.jetty.client.util; -import static org.eclipse.jetty.toolchain.test.StackUtils.supply; -import static org.junit.jupiter.api.Assertions.assertArrayEquals; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertNotNull; -import static org.junit.jupiter.api.Assertions.assertTrue; - import java.io.BufferedWriter; import java.io.ByteArrayInputStream; import java.io.File; @@ -41,7 +35,6 @@ import java.util.List; import java.util.Random; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; - import javax.servlet.MultipartConfigElement; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; @@ -60,6 +53,12 @@ import org.eclipse.jetty.util.IO; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.ArgumentsSource; +import static org.eclipse.jetty.toolchain.test.StackUtils.supply; +import static org.junit.jupiter.api.Assertions.assertArrayEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertTrue; + public class MultiPartContentProviderTest extends AbstractHttpClientServerTest { @ParameterizedTest @@ -79,10 +78,10 @@ public class MultiPartContentProviderTest extends AbstractHttpClientServerTest MultiPartContentProvider multiPart = new MultiPartContentProvider(); multiPart.close(); ContentResponse response = client.newRequest("localhost", connector.getLocalPort()) - .scheme(scenario.getScheme()) - .method(HttpMethod.POST) - .content(multiPart) - .send(); + .scheme(scenario.getScheme()) + .method(HttpMethod.POST) + .content(multiPart) + .send(); assertEquals(200, response.getStatus()); } @@ -110,10 +109,10 @@ public class MultiPartContentProviderTest extends AbstractHttpClientServerTest multiPart.addFieldPart(name, new StringContentProvider(value), null); multiPart.close(); ContentResponse response = client.newRequest("localhost", connector.getLocalPort()) - .scheme(scenario.getScheme()) - .method(HttpMethod.POST) - .content(multiPart) - .send(); + .scheme(scenario.getScheme()) + .method(HttpMethod.POST) + .content(multiPart) + .send(); assertEquals(200, response.getStatus()); } @@ -150,10 +149,10 @@ public class MultiPartContentProviderTest extends AbstractHttpClientServerTest multiPart.addFieldPart(name, content, fields); multiPart.close(); ContentResponse response = client.newRequest("localhost", connector.getLocalPort()) - .scheme(scenario.getScheme()) - .method(HttpMethod.POST) - .content(multiPart) - .send(); + .scheme(scenario.getScheme()) + .method(HttpMethod.POST) + .content(multiPart) + .send(); assertEquals(200, response.getStatus()); } @@ -184,15 +183,15 @@ public class MultiPartContentProviderTest extends AbstractHttpClientServerTest multiPart.close(); CountDownLatch responseLatch = new CountDownLatch(1); client.newRequest("localhost", connector.getLocalPort()) - .scheme(scenario.getScheme()) - .method(HttpMethod.POST) - .content(multiPart) - .send(result -> - { - assertTrue(result.isSucceeded(),supply(result.getFailure())); - assertEquals(200, result.getResponse().getStatus()); - responseLatch.countDown(); - }); + .scheme(scenario.getScheme()) + .method(HttpMethod.POST) + .content(multiPart) + .send(result -> + { + assertTrue(result.isSucceeded(), supply(result.getFailure())); + assertEquals(200, result.getResponse().getStatus()); + responseLatch.countDown(); + }); // Wait until the request has been sent. Thread.sleep(1000); @@ -245,10 +244,10 @@ public class MultiPartContentProviderTest extends AbstractHttpClientServerTest multiPart.addFilePart(name, fileName, content, fields); multiPart.close(); ContentResponse response = client.newRequest("localhost", connector.getLocalPort()) - .scheme(scenario.getScheme()) - .method(HttpMethod.POST) - .content(multiPart) - .send(); + .scheme(scenario.getScheme()) + .method(HttpMethod.POST) + .content(multiPart) + .send(); assertTrue(closeLatch.await(5, TimeUnit.SECONDS)); assertEquals(200, response.getStatus()); @@ -292,10 +291,10 @@ public class MultiPartContentProviderTest extends AbstractHttpClientServerTest multiPart.addFilePart(name, tmpPath.getFileName().toString(), content, null); multiPart.close(); ContentResponse response = client.newRequest("localhost", connector.getLocalPort()) - .scheme(scenario.getScheme()) - .method(HttpMethod.POST) - .content(multiPart) - .send(); + .scheme(scenario.getScheme()) + .method(HttpMethod.POST) + .content(multiPart) + .send(); assertEquals(200, response.getStatus()); @@ -359,10 +358,10 @@ public class MultiPartContentProviderTest extends AbstractHttpClientServerTest multiPart.addFilePart(fileField, tmpPath.getFileName().toString(), new PathContentProvider(tmpPath), null); multiPart.close(); ContentResponse response = client.newRequest("localhost", connector.getLocalPort()) - .scheme(scenario.getScheme()) - .method(HttpMethod.POST) - .content(multiPart) - .send(); + .scheme(scenario.getScheme()) + .method(HttpMethod.POST) + .content(multiPart) + .send(); assertEquals(200, response.getStatus()); @@ -409,15 +408,15 @@ public class MultiPartContentProviderTest extends AbstractHttpClientServerTest multiPart.addFilePart("file", "fileName", fileContent, null); CountDownLatch responseLatch = new CountDownLatch(1); client.newRequest("localhost", connector.getLocalPort()) - .scheme(scenario.getScheme()) - .method(HttpMethod.POST) - .content(multiPart) - .send(result -> - { - assertTrue(result.isSucceeded(),supply(result.getFailure())); - assertEquals(200, result.getResponse().getStatus()); - responseLatch.countDown(); - }); + .scheme(scenario.getScheme()) + .method(HttpMethod.POST) + .content(multiPart) + .send(result -> + { + assertTrue(result.isSucceeded(), supply(result.getFailure())); + assertEquals(200, result.getResponse().getStatus()); + responseLatch.countDown(); + }); // Wait until the request has been sent. Thread.sleep(1000); @@ -436,7 +435,7 @@ public class MultiPartContentProviderTest extends AbstractHttpClientServerTest assertTrue(responseLatch.await(5, TimeUnit.SECONDS)); } - private static abstract class AbstractMultiPartHandler extends AbstractHandler + private abstract static class AbstractMultiPartHandler extends AbstractHandler { @Override public void handle(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException diff --git a/jetty-client/src/test/java/org/eclipse/jetty/client/util/SPNEGOAuthenticationTest.java b/jetty-client/src/test/java/org/eclipse/jetty/client/util/SPNEGOAuthenticationTest.java index ff61bb06a08..d4899900ba8 100644 --- a/jetty-client/src/test/java/org/eclipse/jetty/client/util/SPNEGOAuthenticationTest.java +++ b/jetty-client/src/test/java/org/eclipse/jetty/client/util/SPNEGOAuthenticationTest.java @@ -28,7 +28,6 @@ import java.time.Duration; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; import java.util.stream.Collectors; - import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; @@ -120,8 +119,8 @@ public class SPNEGOAuthenticationTest extends AbstractHttpClientServerTest { LOG.debug("KDC started on port {}", kdc.getKdcTcpPort()); String krb5 = Files.readAllLines(testDirPath.resolve("krb5.conf")).stream() - .filter(line -> !line.startsWith("#")) - .collect(Collectors.joining(System.lineSeparator())); + .filter(line -> !line.startsWith("#")) + .collect(Collectors.joining(System.lineSeparator())); LOG.debug("krb5.conf{}{}", System.lineSeparator(), krb5); } } diff --git a/jetty-client/src/test/java/org/eclipse/jetty/client/util/TypedContentProviderTest.java b/jetty-client/src/test/java/org/eclipse/jetty/client/util/TypedContentProviderTest.java index 519d72403a7..f25ba5fdc00 100644 --- a/jetty-client/src/test/java/org/eclipse/jetty/client/util/TypedContentProviderTest.java +++ b/jetty-client/src/test/java/org/eclipse/jetty/client/util/TypedContentProviderTest.java @@ -18,13 +18,8 @@ package org.eclipse.jetty.client.util; -import static org.hamcrest.MatcherAssert.assertThat; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertNotNull; - import java.io.IOException; import java.nio.charset.StandardCharsets; - import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; @@ -42,6 +37,10 @@ import org.hamcrest.Matchers; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.ArgumentsSource; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; + public class TypedContentProviderTest extends AbstractHttpClientServerTest { @ParameterizedTest @@ -106,11 +105,11 @@ public class TypedContentProviderTest extends AbstractHttpClientServerTest }); ContentResponse response = client.newRequest("localhost", connector.getLocalPort()) - .scheme(scenario.getScheme()) - .method(HttpMethod.POST) - .content(new FormContentProvider(fields)) - .header(HttpHeader.CONTENT_TYPE, contentType) - .send(); + .scheme(scenario.getScheme()) + .method(HttpMethod.POST) + .content(new FormContentProvider(fields)) + .header(HttpHeader.CONTENT_TYPE, contentType) + .send(); assertEquals(200, response.getStatus()); } @@ -134,9 +133,9 @@ public class TypedContentProviderTest extends AbstractHttpClientServerTest }); ContentResponse response = client.newRequest("localhost", connector.getLocalPort()) - .scheme(scenario.getScheme()) - .content(new StringContentProvider(null, content, StandardCharsets.UTF_8)) - .send(); + .scheme(scenario.getScheme()) + .content(new StringContentProvider(null, content, StandardCharsets.UTF_8)) + .send(); assertEquals(200, response.getStatus()); } diff --git a/jetty-deploy/pom.xml b/jetty-deploy/pom.xml index 0bc5232e344..45376093155 100644 --- a/jetty-deploy/pom.xml +++ b/jetty-deploy/pom.xml @@ -1,5 +1,4 @@ - + org.eclipse.jetty jetty-project @@ -21,9 +20,7 @@ maven-surefire-plugin - @{argLine} ${jetty.surefire.argLine} - --add-modules org.eclipse.jetty.jmx - --add-reads org.eclipse.jetty.deploy=org.eclipse.jetty.http,jetty.servlet.api + @{argLine} ${jetty.surefire.argLine} --add-modules org.eclipse.jetty.jmx --add-reads org.eclipse.jetty.deploy=org.eclipse.jetty.http,jetty.servlet.api diff --git a/jetty-deploy/src/main/java/org/eclipse/jetty/deploy/App.java b/jetty-deploy/src/main/java/org/eclipse/jetty/deploy/App.java index 365f5e8ecf5..186c1100ce8 100644 --- a/jetty-deploy/src/main/java/org/eclipse/jetty/deploy/App.java +++ b/jetty-deploy/src/main/java/org/eclipse/jetty/deploy/App.java @@ -33,12 +33,11 @@ public class App /** * Create an App with specified Origin ID and archivePath - * - * @param manager the deployment manager + * + * @param manager the deployment manager * @param provider the app provider - * @param originId - * the origin ID (The ID that the {@link AppProvider} knows - * about) + * @param originId the origin ID (The ID that the {@link AppProvider} knows + * about) * @see App#getOriginId() * @see App#getContextPath() */ @@ -51,21 +50,19 @@ public class App /** * Create an App with specified Origin ID and archivePath - * - * @param manager the deployment manager + * + * @param manager the deployment manager * @param provider the app provider - * @param originId - * the origin ID (The ID that the {@link AppProvider} knows - * about) + * @param originId the origin ID (The ID that the {@link AppProvider} knows + * about) + * @param context Some implementations of AppProvider might have to use an + * already created ContextHandler. * @see App#getOriginId() * @see App#getContextPath() - * @param context - * Some implementations of AppProvider might have to use an - * already created ContextHandler. */ public App(DeploymentManager manager, AppProvider provider, String originId, ContextHandler context) { - this(manager,provider,originId); + this(manager, provider, originId); _context = context; } @@ -87,12 +84,12 @@ public class App /** * Get ContextHandler for the App. - * + * * Create it if needed. - * + * * @return the {@link ContextHandler} to use for the App when fully started. - * (Portions of which might be ignored when App is not yet - * {@link AppLifeCycle#DEPLOYED} or {@link AppLifeCycle#STARTED}) + * (Portions of which might be ignored when App is not yet + * {@link AppLifeCycle#DEPLOYED} or {@link AppLifeCycle#STARTED}) * @throws Exception if unable to get the context handler */ public ContextHandler getContextHandler() throws Exception @@ -100,9 +97,9 @@ public class App if (_context == null) { _context = getAppProvider().createContextHandler(this); - + AttributesMap attributes = _manager.getContextAttributes(); - if (attributes!=null && attributes.size()>0) + if (attributes != null && attributes.size() > 0) { // Merge the manager attributes under the existing attributes attributes = new AttributesMap(attributes); @@ -113,28 +110,26 @@ public class App return _context; } - /** * The context path {@link App} relating to how it is installed on the * jetty server side. - * + * * NOTE that although the method name indicates that this is a unique * identifier, it is not, as many contexts may have the same contextPath, * yet different virtual hosts. - * - * @deprecated Use getContextPath instead. + * * @return the context path for the App + * @deprecated Use getContextPath instead. */ public String getContextId() { return getContextPath(); } - - + /** * The context path {@link App} relating to how it is installed on the * jetty server side. - * + * * @return the contextPath for the App */ public String getContextPath() @@ -148,7 +143,7 @@ public class App /** * The origin of this {@link App} as specified by the {@link AppProvider} - * + * * @return String representing the origin of this app. */ public String getOriginId() diff --git a/jetty-deploy/src/main/java/org/eclipse/jetty/deploy/AppLifeCycle.java b/jetty-deploy/src/main/java/org/eclipse/jetty/deploy/AppLifeCycle.java index 02325c1eb26..0b93aceaf21 100644 --- a/jetty-deploy/src/main/java/org/eclipse/jetty/deploy/AppLifeCycle.java +++ b/jetty-deploy/src/main/java/org/eclipse/jetty/deploy/AppLifeCycle.java @@ -48,20 +48,17 @@ public class AppLifeCycle extends Graph { /** * Get a list of targets that this implementation should bind to. - * + * * @return the array of String node names to bind to. (use "*" to bind to all known node names) */ String[] getBindingTargets(); /** * Event called to process a {@link AppLifeCycle} binding. - * - * @param node - * the node being processed - * @param app - * the app being processed - * @throws Exception - * if any problem severe enough to halt the AppLifeCycle processing + * + * @param node the node being processed + * @param app the app being processed + * @throws Exception if any problem severe enough to halt the AppLifeCycle processing */ void processBinding(Node node, App app) throws Exception; } @@ -75,8 +72,7 @@ public class AppLifeCycle extends Graph public static final String STOPPING = "stopping"; public static final String UNDEPLOYING = "undeploying"; public static final String FAILED = "failed"; - - + private Map> lifecyclebindings = new HashMap>(); public AppLifeCycle() @@ -84,20 +80,20 @@ public class AppLifeCycle extends Graph // Define Default Graph // undeployed -> deployed - addEdge(UNDEPLOYED,DEPLOYING); - addEdge(DEPLOYING,DEPLOYED); + addEdge(UNDEPLOYED, DEPLOYING); + addEdge(DEPLOYING, DEPLOYED); // deployed -> started - addEdge(DEPLOYED,STARTING); - addEdge(STARTING,STARTED); + addEdge(DEPLOYED, STARTING); + addEdge(STARTING, STARTED); // started -> deployed - addEdge(STARTED,STOPPING); - addEdge(STOPPING,DEPLOYED); + addEdge(STARTED, STOPPING); + addEdge(STOPPING, DEPLOYED); // deployed -> undeployed - addEdge(DEPLOYED,UNDEPLOYING); - addEdge(UNDEPLOYING,UNDEPLOYED); + addEdge(DEPLOYED, UNDEPLOYING); + addEdge(UNDEPLOYING, UNDEPLOYED); // failed (unconnected) addNode(new Node(FAILED)); @@ -114,10 +110,10 @@ public class AppLifeCycle extends Graph } bindings.add(binding); - lifecyclebindings.put(nodeName,bindings); + lifecyclebindings.put(nodeName, bindings); } } - + public void removeBinding(AppLifeCycle.Binding binding) { for (String nodeName : binding.getBindingTargets()) @@ -130,7 +126,7 @@ public class AppLifeCycle extends Graph /** * Get all {@link Node} bound objects. - * + * * @return Set of Object(s) for all lifecycle bindings. never null. */ public Set getBindings() @@ -147,8 +143,8 @@ public class AppLifeCycle extends Graph /** * Get all objects bound to a specific {@link Node} - * - * @param node the deployment graph node + * + * @param node the deployment graph node * @return Set of Object(s) for specific lifecycle bindings. never null. */ public Set getBindings(Node node) @@ -158,8 +154,8 @@ public class AppLifeCycle extends Graph /** * Get all objects bound to a specific {@link Node} - * - * @param nodeName the node name + * + * @param nodeName the node name * @return Set of Object(s) for specific lifecycle bindings. never null. */ public Set getBindings(String nodeName) @@ -188,8 +184,8 @@ public class AppLifeCycle extends Graph for (Binding binding : getBindings(node)) { if (LOG.isDebugEnabled()) - LOG.debug("Calling " + binding.getClass().getName()+" for "+app); - binding.processBinding(node,app); + LOG.debug("Calling " + binding.getClass().getName() + " for " + app); + binding.processBinding(node, app); } } } diff --git a/jetty-deploy/src/main/java/org/eclipse/jetty/deploy/AppProvider.java b/jetty-deploy/src/main/java/org/eclipse/jetty/deploy/AppProvider.java index 1daa58c5a2c..2f186c29579 100644 --- a/jetty-deploy/src/main/java/org/eclipse/jetty/deploy/AppProvider.java +++ b/jetty-deploy/src/main/java/org/eclipse/jetty/deploy/AppProvider.java @@ -30,14 +30,15 @@ public interface AppProvider extends LifeCycle { /** * Set the Deployment Manager - * + * * @param deploymentManager the deployment manager - * @throws IllegalStateException - * if the provider {@link #isRunning()}. + * @throws IllegalStateException if the provider {@link #isRunning()}. */ void setDeploymentManager(DeploymentManager deploymentManager); - /** Create a ContextHandler for an App + /** + * Create a ContextHandler for an App + * * @param app The App * @return A ContextHandler * @throws IOException if unable to create context diff --git a/jetty-deploy/src/main/java/org/eclipse/jetty/deploy/ConfigurationManager.java b/jetty-deploy/src/main/java/org/eclipse/jetty/deploy/ConfigurationManager.java index 78859ba5d98..758e6f66f2a 100644 --- a/jetty-deploy/src/main/java/org/eclipse/jetty/deploy/ConfigurationManager.java +++ b/jetty-deploy/src/main/java/org/eclipse/jetty/deploy/ConfigurationManager.java @@ -22,7 +22,7 @@ import java.util.Map; /** * ConfigurationManager - * + * * Type for allow injection of property values for replacement in jetty xml files during deployment. */ public interface ConfigurationManager diff --git a/jetty-deploy/src/main/java/org/eclipse/jetty/deploy/DeploymentManager.java b/jetty-deploy/src/main/java/org/eclipse/jetty/deploy/DeploymentManager.java index e15eccaf561..360ecf6a133 100644 --- a/jetty-deploy/src/main/java/org/eclipse/jetty/deploy/DeploymentManager.java +++ b/jetty-deploy/src/main/java/org/eclipse/jetty/deploy/DeploymentManager.java @@ -78,7 +78,7 @@ public class DeploymentManager extends ContainerLifeCycle { /** * Version of the app. - * + * * Note: Auto-increments on each {@link DeploymentManager#addApp(App)} */ private int version; @@ -135,13 +135,14 @@ public class DeploymentManager extends ContainerLifeCycle /** * Receive an app for processing. - * + * * Most commonly used by the various {@link AppProvider} implementations. + * * @param app the app */ public void addApp(App app) { - LOG.debug("Deployable added: {}",app.getOriginId()); + LOG.debug("Deployable added: {}", app.getOriginId()); AppEntry entry = new AppEntry(); entry.app = app; entry.setLifeCycleNode(_lifecycle.getNodeByName("undeployed")); @@ -150,32 +151,36 @@ public class DeploymentManager extends ContainerLifeCycle if (isRunning() && _defaultLifeCycleGoal != null) { // Immediately attempt to go to default lifecycle state - this.requestAppGoal(entry,_defaultLifeCycleGoal); + this.requestAppGoal(entry, _defaultLifeCycleGoal); } } - /** Set the AppProviders. - * The providers passed are added via {@link #addBean(Object)} so that + /** + * Set the AppProviders. + * The providers passed are added via {@link #addBean(Object)} so that * their lifecycles may be managed as a {@link ContainerLifeCycle}. + * * @param providers the app provider list */ public void setAppProviders(Collection providers) { if (isRunning()) throw new IllegalStateException(); - + _providers.clear(); removeBeans(); - for (AppProvider provider:providers) + for (AppProvider provider : providers) + { if (_providers.add(provider)) addBean(provider); + } } public Collection getAppProviders() { return Collections.unmodifiableList(_providers); } - + public void addAppProvider(AppProvider provider) { if (isRunning()) @@ -189,16 +194,20 @@ public class DeploymentManager extends ContainerLifeCycle if (isRunning()) throw new IllegalStateException(); for (AppLifeCycle.Binding b : _lifecycle.getBindings()) + { _lifecycle.removeBinding(b); + } for (AppLifeCycle.Binding b : bindings) + { _lifecycle.addBinding(b); + } } public Collection getLifeCycleBindings() { return Collections.unmodifiableSet(_lifecycle.getBindings()); } - + public void addLifeCycleBinding(AppLifeCycle.Binding binding) { _lifecycle.addBinding(binding); @@ -206,7 +215,7 @@ public class DeploymentManager extends ContainerLifeCycle /** * Convenience method to allow for insertion of nodes into the lifecycle. - * + * * @param existingFromNodeName the existing node start * @param existingToNodeName the existing node end * @param insertedNodeName the new node to create between the existing nodes @@ -215,16 +224,16 @@ public class DeploymentManager extends ContainerLifeCycle { Node fromNode = _lifecycle.getNodeByName(existingFromNodeName); Node toNode = _lifecycle.getNodeByName(existingToNodeName); - Edge edge = new Edge(fromNode,toNode); - _lifecycle.insertNode(edge,insertedNodeName); + Edge edge = new Edge(fromNode, toNode); + _lifecycle.insertNode(edge, insertedNodeName); } @Override protected void doStart() throws Exception { - if (getContexts()==null) + if (getContexts() == null) throw new IllegalStateException("No Contexts"); - + if (_useStandardBindings) { LOG.debug("DeploymentManager using standard bindings"); @@ -260,7 +269,7 @@ public class DeploymentManager extends ContainerLifeCycle } catch (Exception e) { - LOG.warn("Unable to start AppProvider",e); + LOG.warn("Unable to start AppProvider", e); } } super.doStop(); @@ -282,7 +291,7 @@ public class DeploymentManager extends ContainerLifeCycle } return null; } - + public App getAppByOriginId(String originId) { AppEntry entry = findAppByOriginId(originId); @@ -300,7 +309,7 @@ public class DeploymentManager extends ContainerLifeCycle public Collection getApps() { - List ret = new ArrayList< >(); + List ret = new ArrayList<>(); for (AppEntry entry : _apps) { ret.add(entry.app); @@ -310,15 +319,14 @@ public class DeploymentManager extends ContainerLifeCycle /** * Get Set of {@link App}s by {@link Node} - * - * @param node - * the node to look for. + * + * @param node the node to look for. * @return the collection of apps for the node */ public Collection getApps(Node node) { Objects.requireNonNull(node); - + List ret = new ArrayList<>(); for (AppEntry entry : _apps) { @@ -364,7 +372,7 @@ public class DeploymentManager extends ContainerLifeCycle /** * Get a contextAttribute that will be set for every Context deployed by this provider. - * + * * @param name context attribute name * @return the context attribute value */ @@ -405,9 +413,8 @@ public class DeploymentManager extends ContainerLifeCycle /** * Remove the app from the tracking of the DeploymentManager - * - * @param app - * if the app is Unavailable remove it from the deployment manager. + * + * @param app if the app is Unavailable remove it from the deployment manager. */ public void removeApp(App app) { @@ -417,32 +424,32 @@ public class DeploymentManager extends ContainerLifeCycle AppEntry entry = it.next(); if (entry.app.equals(app)) { - if (! AppLifeCycle.UNDEPLOYED.equals(entry.lifecyleNode.getName())) - requestAppGoal(entry.app,AppLifeCycle.UNDEPLOYED); + if (!AppLifeCycle.UNDEPLOYED.equals(entry.lifecyleNode.getName())) + requestAppGoal(entry.app, AppLifeCycle.UNDEPLOYED); it.remove(); - LOG.debug("Deployable removed: {}",entry.app); + LOG.debug("Deployable removed: {}", entry.app); } } } public void removeAppProvider(AppProvider provider) { - if(_providers.remove(provider)) + if (_providers.remove(provider)) removeBean(provider); - + try { provider.stop(); } catch (Exception e) { - LOG.warn("Unable to stop Provider",e); + LOG.warn("Unable to stop Provider", e); } } /** * Remove a contextAttribute that will be set for every Context deployed by this provider. - * + * * @param name the context attribute name */ public void removeContextAttribute(String name) @@ -453,11 +460,9 @@ public class DeploymentManager extends ContainerLifeCycle /** * Move an {@link App} through the {@link AppLifeCycle} to the desired {@link Node}, executing each lifecycle step * in the process to reach the desired state. - * - * @param app - * the app to move through the process - * @param nodeName - * the name of the node to attain + * + * @param app the app to move through the process + * @param nodeName the name of the node to attain */ public void requestAppGoal(App app, String nodeName) { @@ -466,18 +471,16 @@ public class DeploymentManager extends ContainerLifeCycle { throw new IllegalStateException("App not being tracked by Deployment Manager: " + app); } - - requestAppGoal(appentry,nodeName); + + requestAppGoal(appentry, nodeName); } /** * Move an {@link App} through the {@link AppLifeCycle} to the desired {@link Node}, executing each lifecycle step * in the process to reach the desired state. - * - * @param appentry - * the internal appentry to move through the process - * @param nodeName - * the name of the node to attain + * + * @param appentry the internal appentry to move through the process + * @param nodeName the name of the node to attain */ private void requestAppGoal(AppEntry appentry, String nodeName) { @@ -487,7 +490,7 @@ public class DeploymentManager extends ContainerLifeCycle throw new IllegalStateException("Node not present in Deployment Manager: " + nodeName); } // Compute lifecycle steps - Path path = _lifecycle.getPath(appentry.lifecyleNode,destinationNode); + Path path = _lifecycle.getPath(appentry.lifecyleNode, destinationNode); if (path.isEmpty()) { // nothing to do. already there. @@ -506,15 +509,15 @@ public class DeploymentManager extends ContainerLifeCycle while (it.hasNext()) { Node node = it.next(); - LOG.debug("Executing Node {}",node); - _lifecycle.runBindings(node,appentry.app,this); + LOG.debug("Executing Node {}", node); + _lifecycle.runBindings(node, appentry.app, this); appentry.setLifeCycleNode(node); } } } catch (Throwable t) { - LOG.warn("Unable to reach node goal: " + nodeName,t); + LOG.warn("Unable to reach node goal: " + nodeName, t); // migrate to FAILED node Node failed = _lifecycle.getNodeByName(AppLifeCycle.FAILED); appentry.setLifeCycleNode(failed); @@ -537,7 +540,7 @@ public class DeploymentManager extends ContainerLifeCycle private synchronized void addOnStartupError(Throwable cause) { - if(onStartupErrors == null) + if (onStartupErrors == null) { onStartupErrors = new MultiException(); } @@ -547,13 +550,11 @@ public class DeploymentManager extends ContainerLifeCycle /** * Move an {@link App} through the {@link AppLifeCycle} to the desired {@link Node}, executing each lifecycle step * in the process to reach the desired state. - * - * @param appId - * the id of the app to move through the process - * @param nodeName - * the name of the node to attain + * + * @param appId the id of the app to move through the process + * @param nodeName the name of the node to attain */ - @ManagedOperation(value="request the app to be moved to the specified lifecycle node", impact="ACTION") + @ManagedOperation(value = "request the app to be moved to the specified lifecycle node", impact = "ACTION") public void requestAppGoal(@Name("appId") String appId, @Name("nodeName") String nodeName) { AppEntry appentry = findAppByOriginId(appId); @@ -561,18 +562,18 @@ public class DeploymentManager extends ContainerLifeCycle { throw new IllegalStateException("App not being tracked by Deployment Manager: " + appId); } - requestAppGoal(appentry,nodeName); + requestAppGoal(appentry, nodeName); } /** * Set a contextAttribute that will be set for every Context deployed by this provider. - * + * * @param name the context attribute name * @param value the context attribute value */ public void setContextAttribute(String name, Object value) { - _contextAttributes.setAttribute(name,value); + _contextAttributes.setAttribute(name, value); } public void setContextAttributes(AttributesMap contextAttributes) @@ -599,7 +600,7 @@ public class DeploymentManager extends ContainerLifeCycle } catch (Exception e) { - LOG.warn("Unable to start AppProvider",e); + LOG.warn("Unable to start AppProvider", e); } } @@ -608,7 +609,7 @@ public class DeploymentManager extends ContainerLifeCycle LOG.debug("Undeploy All"); for (AppEntry appentry : _apps) { - requestAppGoal(appentry,"undeployed"); + requestAppGoal(appentry, "undeployed"); } } @@ -632,10 +633,9 @@ public class DeploymentManager extends ContainerLifeCycle return getApps(_lifecycle.getNodeByName(nodeName)); } - public void scope(XmlConfiguration xmlc, Resource webapp) throws IOException { - xmlc.setJettyStandardIdsAndProperties(getServer(),webapp); + xmlc.setJettyStandardIdsAndProperties(getServer(), webapp); } } diff --git a/jetty-deploy/src/main/java/org/eclipse/jetty/deploy/PropertiesConfigurationManager.java b/jetty-deploy/src/main/java/org/eclipse/jetty/deploy/PropertiesConfigurationManager.java index 244cfbf4ab7..e7708db5b08 100644 --- a/jetty-deploy/src/main/java/org/eclipse/jetty/deploy/PropertiesConfigurationManager.java +++ b/jetty-deploy/src/main/java/org/eclipse/jetty/deploy/PropertiesConfigurationManager.java @@ -33,19 +33,19 @@ import org.eclipse.jetty.util.resource.Resource; /** * FileConfigurationManager - * + * * Supplies properties defined in a file. */ @ManagedObject("Configure deployed webapps via properties") public class PropertiesConfigurationManager implements ConfigurationManager { private String _properties; - private final Map _map = new HashMap(); + private final Map _map = new HashMap(); public PropertiesConfigurationManager(String properties) { } - + public PropertiesConfigurationManager() { } @@ -53,7 +53,7 @@ public class PropertiesConfigurationManager implements ConfigurationManager @ManagedAttribute("A file or URL of properties") public void setFile(String resource) throws MalformedURLException, IOException { - _properties=resource; + _properties = resource; _map.clear(); loadProperties(_properties); } @@ -62,13 +62,13 @@ public class PropertiesConfigurationManager implements ConfigurationManager { return _properties; } - + @ManagedOperation("Set a property") - public void put(@Name("name")String name, @Name("value")String value) + public void put(@Name("name") String name, @Name("value") String value) { - _map.put(name,value); + _map.put(name, value); } - + /** * @see org.eclipse.jetty.deploy.ConfigurationManager#getProperties() */ @@ -79,14 +79,16 @@ public class PropertiesConfigurationManager implements ConfigurationManager } private void loadProperties(String resource) throws FileNotFoundException, IOException - { - Resource file=Resource.newResource(resource); - if (file!=null && file.exists()) + { + Resource file = Resource.newResource(resource); + if (file != null && file.exists()) { Properties properties = new Properties(); properties.load(file.getInputStream()); for (Map.Entry entry : properties.entrySet()) - _map.put(entry.getKey().toString(),String.valueOf(entry.getValue())); + { + _map.put(entry.getKey().toString(), String.valueOf(entry.getValue())); + } } } } diff --git a/jetty-deploy/src/main/java/org/eclipse/jetty/deploy/bindings/DebugBinding.java b/jetty-deploy/src/main/java/org/eclipse/jetty/deploy/bindings/DebugBinding.java index db325ed63c0..8f29bc38f65 100644 --- a/jetty-deploy/src/main/java/org/eclipse/jetty/deploy/bindings/DebugBinding.java +++ b/jetty-deploy/src/main/java/org/eclipse/jetty/deploy/bindings/DebugBinding.java @@ -29,17 +29,17 @@ public class DebugBinding implements AppLifeCycle.Binding private static final Logger LOG = Log.getLogger(DebugBinding.class); final String[] _targets; - + public DebugBinding(String target) { - _targets=new String[]{target}; + _targets = new String[]{target}; } - + public DebugBinding(final String... targets) { - _targets=targets; + _targets = targets; } - + @Override public String[] getBindingTargets() { @@ -49,6 +49,6 @@ public class DebugBinding implements AppLifeCycle.Binding @Override public void processBinding(Node node, App app) throws Exception { - LOG.info("processBinding {} {}",node,app.getContextHandler()); + LOG.info("processBinding {} {}", node, app.getContextHandler()); } } diff --git a/jetty-deploy/src/main/java/org/eclipse/jetty/deploy/bindings/DebugListenerBinding.java b/jetty-deploy/src/main/java/org/eclipse/jetty/deploy/bindings/DebugListenerBinding.java index 2ffc02aa9e7..1a6b237fa54 100644 --- a/jetty-deploy/src/main/java/org/eclipse/jetty/deploy/bindings/DebugListenerBinding.java +++ b/jetty-deploy/src/main/java/org/eclipse/jetty/deploy/bindings/DebugListenerBinding.java @@ -22,7 +22,8 @@ import org.eclipse.jetty.deploy.App; import org.eclipse.jetty.deploy.graph.Node; import org.eclipse.jetty.server.DebugListener; -/** A Deployment binding that installs a DebugListener in all deployed contexts +/** + * A Deployment binding that installs a DebugListener in all deployed contexts */ public class DebugListenerBinding extends DebugBinding { @@ -32,22 +33,21 @@ public class DebugListenerBinding extends DebugBinding { this(new DebugListener()); } - + public DebugListenerBinding(DebugListener debugListener) { super(new String[]{"deploying"}); - _debugListener=debugListener; + _debugListener = debugListener; } - + public DebugListener getDebugListener() { return _debugListener; } - + @Override public void processBinding(Node node, App app) throws Exception { app.getContextHandler().addEventListener(_debugListener); } - } diff --git a/jetty-deploy/src/main/java/org/eclipse/jetty/deploy/bindings/GlobalWebappConfigBinding.java b/jetty-deploy/src/main/java/org/eclipse/jetty/deploy/bindings/GlobalWebappConfigBinding.java index 5b80468eba2..17f8353a26a 100644 --- a/jetty-deploy/src/main/java/org/eclipse/jetty/deploy/bindings/GlobalWebappConfigBinding.java +++ b/jetty-deploy/src/main/java/org/eclipse/jetty/deploy/bindings/GlobalWebappConfigBinding.java @@ -41,7 +41,6 @@ import org.eclipse.jetty.xml.XmlConfiguration; * * Note: Currently properties from startup will not be available for * reference. - * */ public class GlobalWebappConfigBinding implements AppLifeCycle.Binding { @@ -62,7 +61,7 @@ public class GlobalWebappConfigBinding implements AppLifeCycle.Binding @Override public String[] getBindingTargets() { - return new String[] { "deploying" }; + return new String[]{"deploying"}; } @Override @@ -83,7 +82,7 @@ public class GlobalWebappConfigBinding implements AppLifeCycle.Binding LOG.debug("Binding: Configuring webapp context with global settings from: " + _jettyXml); } - if ( _jettyXml == null ) + if (_jettyXml == null) { LOG.warn("Binding: global context binding is enabled but no jetty-web.xml file has been registered"); } @@ -94,8 +93,12 @@ public class GlobalWebappConfigBinding implements AppLifeCycle.Binding { XmlConfiguration jettyXmlConfig = new XmlConfiguration(globalContextSettings); Resource resource = Resource.newResource(app.getOriginId()); - app.getDeploymentManager().scope(jettyXmlConfig,resource); - WebAppClassLoader.runWithServerClassAccess(()->{jettyXmlConfig.configure(context);return null;}); + app.getDeploymentManager().scope(jettyXmlConfig, resource); + WebAppClassLoader.runWithServerClassAccess(() -> + { + jettyXmlConfig.configure(context); + return null; + }); } else { @@ -103,5 +106,4 @@ public class GlobalWebappConfigBinding implements AppLifeCycle.Binding } } } - } diff --git a/jetty-deploy/src/main/java/org/eclipse/jetty/deploy/bindings/OrderedGroupBinding.java b/jetty-deploy/src/main/java/org/eclipse/jetty/deploy/bindings/OrderedGroupBinding.java index 196125fbfec..8881bb62fc9 100644 --- a/jetty-deploy/src/main/java/org/eclipse/jetty/deploy/bindings/OrderedGroupBinding.java +++ b/jetty-deploy/src/main/java/org/eclipse/jetty/deploy/bindings/OrderedGroupBinding.java @@ -25,44 +25,43 @@ import org.eclipse.jetty.deploy.AppLifeCycle; import org.eclipse.jetty.deploy.graph.Node; /** - * Provides a way of forcing the ordered execution of bindings within + * Provides a way of forcing the ordered execution of bindings within * a declared binding target. - * */ public class OrderedGroupBinding implements AppLifeCycle.Binding { private String[] _bindingTargets; - + private LinkedList _orderedBindings; - - public OrderedGroupBinding( String[] bindingTargets ) - { + + public OrderedGroupBinding(String[] bindingTargets) + { _bindingTargets = bindingTargets; } - + public void addBinding(AppLifeCycle.Binding binding) { - if ( _orderedBindings == null ) - { + if (_orderedBindings == null) + { _orderedBindings = new LinkedList(); - } - + } + _orderedBindings.add(binding); } - + public void addBindings(AppLifeCycle.Binding[] bindings) { - if ( _orderedBindings == null ) + if (_orderedBindings == null) { - _orderedBindings = new LinkedList(); + _orderedBindings = new LinkedList(); } - + for (AppLifeCycle.Binding binding : bindings) { _orderedBindings.add(binding); } } - + @Override public String[] getBindingTargets() { @@ -72,9 +71,9 @@ public class OrderedGroupBinding implements AppLifeCycle.Binding @Override public void processBinding(Node node, App app) throws Exception { - for ( AppLifeCycle.Binding binding : _orderedBindings ) + for (AppLifeCycle.Binding binding : _orderedBindings) { - binding.processBinding(node,app); + binding.processBinding(node, app); } } } diff --git a/jetty-deploy/src/main/java/org/eclipse/jetty/deploy/bindings/StandardDeployer.java b/jetty-deploy/src/main/java/org/eclipse/jetty/deploy/bindings/StandardDeployer.java index 5fa840a794a..c914dd275de 100644 --- a/jetty-deploy/src/main/java/org/eclipse/jetty/deploy/bindings/StandardDeployer.java +++ b/jetty-deploy/src/main/java/org/eclipse/jetty/deploy/bindings/StandardDeployer.java @@ -29,8 +29,7 @@ public class StandardDeployer implements AppLifeCycle.Binding @Override public String[] getBindingTargets() { - return new String[] - { "deploying" }; + return new String[]{"deploying"}; } @Override diff --git a/jetty-deploy/src/main/java/org/eclipse/jetty/deploy/bindings/StandardStarter.java b/jetty-deploy/src/main/java/org/eclipse/jetty/deploy/bindings/StandardStarter.java index 550ff11542f..9edf79a3aba 100644 --- a/jetty-deploy/src/main/java/org/eclipse/jetty/deploy/bindings/StandardStarter.java +++ b/jetty-deploy/src/main/java/org/eclipse/jetty/deploy/bindings/StandardStarter.java @@ -29,8 +29,7 @@ public class StandardStarter implements AppLifeCycle.Binding @Override public String[] getBindingTargets() { - return new String[] - { "starting" }; + return new String[]{"starting"}; } @Override diff --git a/jetty-deploy/src/main/java/org/eclipse/jetty/deploy/bindings/StandardStopper.java b/jetty-deploy/src/main/java/org/eclipse/jetty/deploy/bindings/StandardStopper.java index 046c3e78993..1d75b829907 100644 --- a/jetty-deploy/src/main/java/org/eclipse/jetty/deploy/bindings/StandardStopper.java +++ b/jetty-deploy/src/main/java/org/eclipse/jetty/deploy/bindings/StandardStopper.java @@ -28,18 +28,17 @@ public class StandardStopper implements AppLifeCycle.Binding @Override public String[] getBindingTargets() { - return new String[] - { "stopping" }; + return new String[]{"stopping"}; } @Override public void processBinding(Node node, App app) throws Exception { ContextHandler handler = app.getContextHandler(); - + // Before stopping, take back management from the context app.getDeploymentManager().getContexts().unmanage(handler); - + // Stop it handler.stop(); } diff --git a/jetty-deploy/src/main/java/org/eclipse/jetty/deploy/bindings/StandardUndeployer.java b/jetty-deploy/src/main/java/org/eclipse/jetty/deploy/bindings/StandardUndeployer.java index 6502381cbe0..2653d4b6f16 100644 --- a/jetty-deploy/src/main/java/org/eclipse/jetty/deploy/bindings/StandardUndeployer.java +++ b/jetty-deploy/src/main/java/org/eclipse/jetty/deploy/bindings/StandardUndeployer.java @@ -30,8 +30,7 @@ public class StandardUndeployer implements AppLifeCycle.Binding @Override public String[] getBindingTargets() { - return new String[] - { "undeploying" }; + return new String[]{"undeploying"}; } @Override diff --git a/jetty-deploy/src/main/java/org/eclipse/jetty/deploy/graph/Edge.java b/jetty-deploy/src/main/java/org/eclipse/jetty/deploy/graph/Edge.java index 6c5ddc42f42..f1ecb4267fe 100644 --- a/jetty-deploy/src/main/java/org/eclipse/jetty/deploy/graph/Edge.java +++ b/jetty-deploy/src/main/java/org/eclipse/jetty/deploy/graph/Edge.java @@ -29,9 +29,9 @@ public final class Edge public Edge(Node from, Node to) { @SuppressWarnings("ReferenceEquality") - boolean sameObject = (from==to); - if (from==null || to==null || sameObject) - throw new IllegalArgumentException("from "+from+" to "+to); + boolean sameObject = (from == to); + if (from == null || to == null || sameObject) + throw new IllegalArgumentException("from " + from + " to " + to); _from = from; _to = to; } @@ -73,15 +73,15 @@ public final class Edge { return _from; } - + public Node getTo() { return _to; } - + @Override public String toString() { - return _from+"->"+_to; + return _from + "->" + _to; } } diff --git a/jetty-deploy/src/main/java/org/eclipse/jetty/deploy/graph/Graph.java b/jetty-deploy/src/main/java/org/eclipse/jetty/deploy/graph/Graph.java index bfa30f68ef1..6c59f8a7b0e 100644 --- a/jetty-deploy/src/main/java/org/eclipse/jetty/deploy/graph/Graph.java +++ b/jetty-deploy/src/main/java/org/eclipse/jetty/deploy/graph/Graph.java @@ -33,41 +33,41 @@ public class Graph public void addEdge(Edge edge) { Node fromNode = getNodeByName(edge.getFrom().getName()); - if (fromNode==null) - addNode(fromNode=edge.getFrom()); + if (fromNode == null) + addNode(fromNode = edge.getFrom()); Node toNode = getNodeByName(edge.getTo().getName()); - if (toNode==null) - addNode(toNode=edge.getTo()); - + if (toNode == null) + addNode(toNode = edge.getTo()); + // replace edge with normalized edge if (!edge.getFrom().equals(fromNode) || !edge.getTo().equals(toNode)) - edge=new Edge(fromNode,toNode); - + edge = new Edge(fromNode, toNode); + this._edges.add(edge); } public void addEdge(String from, String to) { Node fromNode = getNodeByName(from); - if (fromNode==null) + if (fromNode == null) { fromNode = new Node(from); addNode(fromNode); } - + Node toNode = getNodeByName(to); - if (toNode==null) + if (toNode == null) { toNode = new Node(to); addNode(toNode); } - addEdge(fromNode,toNode); + addEdge(fromNode, toNode); } private void addEdge(Node fromNode, Node toNode) { - Edge edge = new Edge(fromNode,toNode); + Edge edge = new Edge(fromNode, toNode); addEdge(edge); } @@ -78,30 +78,26 @@ public class Graph /** * Convenience method for {@link #insertNode(Edge, Node)} - * - * @param edge - * the edge to split and insert a node into - * @param nodeName - * the name of the node to insert along the edge + * + * @param edge the edge to split and insert a node into + * @param nodeName the name of the node to insert along the edge */ public void insertNode(Edge edge, String nodeName) { Node node = getNodeByName(nodeName); - if (node==null) + if (node == null) { node = new Node(nodeName); } - insertNode(edge,node); + insertNode(edge, node); } /** * Insert an arbitrary node on an existing edge. - * - * @param edge - * the edge to split and insert a node into - * @param node - * the node to insert along the edge + * + * @param edge the edge to split and insert a node into + * @param node the node to insert along the edge */ public void insertNode(Edge edge, Node node) { @@ -110,17 +106,16 @@ public class Graph // Ensure node is added addNode(node); // Add start edge - addEdge(edge.getFrom(),node); + addEdge(edge.getFrom(), node); // Add second edge - addEdge(node,edge.getTo()); + addEdge(node, edge.getTo()); } /** * Find all edges that are connected to the specific node, both as an outgoing {@link Edge#getFrom()} or incoming * {@link Edge#getTo()} end point. - * - * @param node - * the node with potential end points + * + * @param node the node with potential end points * @return the set of edges connected to the node */ public Set findEdges(Node node) @@ -140,9 +135,8 @@ public class Graph /** * Find all edges that are connected {@link Edge#getFrom()} the specific node. - * - * @param from - * the node with potential edges from it + * + * @param from the node with potential edges from it * @return the set of edges from the node */ public Set findEdgesFrom(Node from) @@ -162,11 +156,9 @@ public class Graph /** * Convenience method for {@link #getPath(Node, Node)} - * - * @param nodeNameOrigin - * the name of the node to the path origin. - * @param nodeNameDest - * the name of the node to the path destination. + * + * @param nodeNameOrigin the name of the node to the path origin. + * @param nodeNameDest the name of the node to the path destination. * @return the path to take */ public Path getPath(String nodeNameOrigin, String nodeNameDest) @@ -178,29 +170,27 @@ public class Graph Node from = getNodeByName(nodeNameOrigin); Node to = getNodeByName(nodeNameDest); - return getPath(from,to); + return getPath(from, to); } /** * Using BFS (Breadth First Search) return the path from a any arbitrary node to any other. - * - * @param from - * the node from - * @param to - * the node to + * + * @param from the node from + * @param to the node to * @return the path to take or null if there is no path. */ public Path getPath(Node from, Node to) { @SuppressWarnings("ReferenceEquality") - boolean sameObject = (from==to); + boolean sameObject = (from == to); if (sameObject) { return new Path(); } // Perform a Breadth First Search (BFS) of the tree. - Path path = breadthFirst(from,to,new CopyOnWriteArrayList(),new HashSet()); + Path path = breadthFirst(from, to, new CopyOnWriteArrayList(), new HashSet()); return path; } @@ -208,40 +198,40 @@ public class Graph { // Add next unseen segments to paths. boolean edgesAdded = false; - if (paths.size()==0) + if (paths.size() == 0) paths.add(new Path()); for (Path path : paths) { - Set next = findEdgesFrom(path.nodes()==0?from:path.lastNode()); + Set next = findEdgesFrom(path.nodes() == 0 ? from : path.lastNode()); if (next.size() == 0) continue; // no new edges // Split path for other edges - int splits=0; - for (Edge edge:next) + int splits = 0; + for (Edge edge : next) { if (seen.contains(edge)) continue; seen.add(edge); - Path nextPath = (++splits==next.size())?path:path.forkPath(); + Path nextPath = (++splits == next.size()) ? path : path.forkPath(); // Add segment to split'd path nextPath.add(edge); - + // Are we there yet? if (destination.equals(edge.getTo())) return nextPath; edgesAdded = true; - + // Add to extra paths - if (nextPath!=path) + if (nextPath != path) paths.add(nextPath); } } if (edgesAdded) - return breadthFirst(from,destination,paths,seen); + return breadthFirst(from, destination, paths, seen); return null; } @@ -252,9 +242,8 @@ public class Graph /** * Get the Node by Name. - * - * @param name - * the name to lookup + * + * @param name the name to lookup * @return the node if found or null if not found. */ public Node getNodeByName(String name) @@ -283,7 +272,7 @@ public class Graph { Node fromNode = getNodeByName(fromNodeName); Node toNode = getNodeByName(toNodeName); - Edge edge = new Edge(fromNode,toNode); + Edge edge = new Edge(fromNode, toNode); removeEdge(edge); } diff --git a/jetty-deploy/src/main/java/org/eclipse/jetty/deploy/graph/GraphOutputDot.java b/jetty-deploy/src/main/java/org/eclipse/jetty/deploy/graph/GraphOutputDot.java index bcdae413fb6..f462d5b400f 100644 --- a/jetty-deploy/src/main/java/org/eclipse/jetty/deploy/graph/GraphOutputDot.java +++ b/jetty-deploy/src/main/java/org/eclipse/jetty/deploy/graph/GraphOutputDot.java @@ -43,7 +43,7 @@ public class GraphOutputDot /** * Comparator that makes the 'undeployed' node the first node in the sort list. - * + * * This makes the 'undeployed' node show up at the top of the generated graph. */ private static class TopNodeSort implements Comparator @@ -96,12 +96,12 @@ public class GraphOutputDot for (Node node : nodes) { - writeNode(out,node); + writeNode(out, node); } for (Edge edge : graph.getEdges()) { - writeEdge(out,edge); + writeEdge(out, edge); } out.println("}"); @@ -117,7 +117,7 @@ public class GraphOutputDot { out.println(); out.println(" // Edge"); - out.printf(" \"%s\" -> \"%s\" [%n",toId(edge.getFrom()),toId(edge.getTo())); + out.printf(" \"%s\" -> \"%s\" [%n", toId(edge.getFrom()), toId(edge.getTo())); out.println(" arrowtail=none,"); out.println(" arrowhead=normal"); out.println(" ];"); @@ -127,8 +127,8 @@ public class GraphOutputDot { out.println(); out.println(" // Node"); - out.printf(" \"%s\" [%n",toId(node)); - out.printf(" label=\"%s\",%n",node.getName()); + out.printf(" \"%s\" [%n", toId(node)); + out.printf(" label=\"%s\",%n", node.getName()); if (node.getName().endsWith("ed")) { out.println(" color=\"#ddddff\","); diff --git a/jetty-deploy/src/main/java/org/eclipse/jetty/deploy/graph/Node.java b/jetty-deploy/src/main/java/org/eclipse/jetty/deploy/graph/Node.java index 55131aa2ddd..ee214141086 100644 --- a/jetty-deploy/src/main/java/org/eclipse/jetty/deploy/graph/Node.java +++ b/jetty-deploy/src/main/java/org/eclipse/jetty/deploy/graph/Node.java @@ -27,7 +27,7 @@ public final class Node public Node(String name) { - assert name!=null; + assert name != null; this._name = name; } diff --git a/jetty-deploy/src/main/java/org/eclipse/jetty/deploy/jmx/DeploymentManagerMBean.java b/jetty-deploy/src/main/java/org/eclipse/jetty/deploy/jmx/DeploymentManagerMBean.java index fa532548737..42f076ed0a6 100644 --- a/jetty-deploy/src/main/java/org/eclipse/jetty/deploy/jmx/DeploymentManagerMBean.java +++ b/jetty-deploy/src/main/java/org/eclipse/jetty/deploy/jmx/DeploymentManagerMBean.java @@ -42,7 +42,7 @@ public class DeploymentManagerMBean extends ObjectMBean public DeploymentManagerMBean(Object managedObject) { super(managedObject); - _manager = (DeploymentManager) managedObject; + _manager = (DeploymentManager)managedObject; } @ManagedAttribute(value = "list apps being tracked") @@ -91,7 +91,9 @@ public class DeploymentManagerMBean extends ObjectMBean { List apps = new ArrayList(); for (App app : _manager.getApps()) + { apps.add(app.getContextHandler()); + } return apps; } diff --git a/jetty-deploy/src/main/java/org/eclipse/jetty/deploy/providers/ScanningAppProvider.java b/jetty-deploy/src/main/java/org/eclipse/jetty/deploy/providers/ScanningAppProvider.java index 85e39a3d9f3..0507816c76b 100644 --- a/jetty-deploy/src/main/java/org/eclipse/jetty/deploy/providers/ScanningAppProvider.java +++ b/jetty-deploy/src/main/java/org/eclipse/jetty/deploy/providers/ScanningAppProvider.java @@ -42,6 +42,7 @@ import org.eclipse.jetty.util.log.Logger; import org.eclipse.jetty.util.resource.Resource; /** + * */ @ManagedObject("Abstract Provider for loading webapps") public abstract class ScanningAppProvider extends AbstractLifeCycle implements AppProvider @@ -52,7 +53,7 @@ public abstract class ScanningAppProvider extends AbstractLifeCycle implements A private DeploymentManager _deploymentManager; protected FilenameFilter _filenameFilter; - private final List _monitored= new CopyOnWriteArrayList<>(); + private final List _monitored = new CopyOnWriteArrayList<>(); private boolean _recursive = false; private int _scanInterval = 10; private Scanner _scanner; @@ -106,35 +107,34 @@ public abstract class ScanningAppProvider extends AbstractLifeCycle implements A * Called by the Scanner.DiscreteListener to create a new App object. * Isolated in a method so that it is possible to override the default App * object for specialized implementations of the AppProvider. - * - * @param filename - * The file that is the context.xml. It is resolved by - * {@link Resource#newResource(String)} + * + * @param filename The file that is the context.xml. It is resolved by + * {@link Resource#newResource(String)} * @return The App object for this particular context definition file. */ protected App createApp(String filename) { - return new App(_deploymentManager,this,filename); + return new App(_deploymentManager, this, filename); } @Override protected void doStart() throws Exception { - if (LOG.isDebugEnabled()) + if (LOG.isDebugEnabled()) LOG.debug(this.getClass().getSimpleName() + ".doStart()"); - if (_monitored.size()==0) + if (_monitored.size() == 0) throw new IllegalStateException("No configuration dir specified"); LOG.info("Deployment monitor " + _monitored + " at interval " + _scanInterval); List files = new ArrayList<>(); - for (Resource resource:_monitored) + for (Resource resource : _monitored) { if (resource.exists() && resource.getFile().canRead()) files.add(resource.getFile()); else - LOG.warn("Does not exist: "+resource); + LOG.warn("Does not exist: " + resource); } - + _scanner = new Scanner(); _scanner.setScanDirs(files); _scanner.setScanInterval(_scanInterval); @@ -148,7 +148,7 @@ public abstract class ScanningAppProvider extends AbstractLifeCycle implements A @Override protected void doStop() throws Exception { - if (_scanner!=null) + if (_scanner != null) { _scanner.stop(); _scanner.removeListener(_scannerListener); @@ -163,20 +163,20 @@ public abstract class ScanningAppProvider extends AbstractLifeCycle implements A protected void fileAdded(String filename) throws Exception { - if (LOG.isDebugEnabled()) - LOG.debug("added {}",filename); + if (LOG.isDebugEnabled()) + LOG.debug("added {}", filename); App app = ScanningAppProvider.this.createApp(filename); if (app != null) { - _appMap.put(filename,app); + _appMap.put(filename, app); _deploymentManager.addApp(app); } } protected void fileChanged(String filename) throws Exception { - if (LOG.isDebugEnabled()) - LOG.debug("changed {}",filename); + if (LOG.isDebugEnabled()) + LOG.debug("changed {}", filename); App app = _appMap.remove(filename); if (app != null) { @@ -185,15 +185,15 @@ public abstract class ScanningAppProvider extends AbstractLifeCycle implements A app = ScanningAppProvider.this.createApp(filename); if (app != null) { - _appMap.put(filename,app); + _appMap.put(filename, app); _deploymentManager.addApp(app); } } protected void fileRemoved(String filename) throws Exception { - if (LOG.isDebugEnabled()) - LOG.debug("removed {}",filename); + if (LOG.isDebugEnabled()) + LOG.debug("removed {}", filename); App app = _appMap.remove(filename); if (app != null) _deploymentManager.removeApp(app); @@ -201,7 +201,7 @@ public abstract class ScanningAppProvider extends AbstractLifeCycle implements A /** * Get the deploymentManager. - * + * * @return the deploymentManager */ public DeploymentManager getDeploymentManager() @@ -211,17 +211,17 @@ public abstract class ScanningAppProvider extends AbstractLifeCycle implements A public Resource getMonitoredDirResource() { - if (_monitored.size()==0) + if (_monitored.size() == 0) return null; - if (_monitored.size()>1) + if (_monitored.size() > 1) throw new IllegalStateException(); return _monitored.get(0); } public String getMonitoredDirName() { - Resource resource=getMonitoredDirResource(); - return resource==null?null:resource.toString(); + Resource resource = getMonitoredDirResource(); + return resource == null ? null : resource.toString(); } @ManagedAttribute("scanning interval to detect changes which need reloaded") @@ -264,8 +264,7 @@ public abstract class ScanningAppProvider extends AbstractLifeCycle implements A } /** - * @param dir - * Directory to scan for context descriptors or war files + * @param dir Directory to scan for context descriptors or war files */ public void setMonitoredDirName(String dir) { @@ -277,8 +276,10 @@ public abstract class ScanningAppProvider extends AbstractLifeCycle implements A try { List resources = new ArrayList<>(); - for (String dir:directories) + for (String dir : directories) + { resources.add(Resource.newResource(dir)); + } setMonitoredResources(resources); } catch (Exception e) @@ -301,8 +302,8 @@ public abstract class ScanningAppProvider extends AbstractLifeCycle implements A public void scan() { LOG.info("Performing scan of monitored directories: {}", - getMonitoredResources().stream().map((r) -> r.getURI().toASCIIString()) - .collect(Collectors.joining(", ", "[", "]")) + getMonitoredResources().stream().map((r) -> r.getURI().toASCIIString()) + .collect(Collectors.joining(", ", "[", "]")) ); _scanner.scan(); } diff --git a/jetty-deploy/src/main/java/org/eclipse/jetty/deploy/providers/WebAppProvider.java b/jetty-deploy/src/main/java/org/eclipse/jetty/deploy/providers/WebAppProvider.java index 7805d2d6bad..5217e862ce9 100644 --- a/jetty-deploy/src/main/java/org/eclipse/jetty/deploy/providers/WebAppProvider.java +++ b/jetty-deploy/src/main/java/org/eclipse/jetty/deploy/providers/WebAppProvider.java @@ -34,7 +34,7 @@ import org.eclipse.jetty.util.resource.Resource; import org.eclipse.jetty.webapp.WebAppContext; import org.eclipse.jetty.xml.XmlConfiguration; -/** +/** * The webapps directory scanning provider. *

    * This provider scans one or more directories (typically "webapps") for contexts to @@ -80,7 +80,7 @@ public class WebAppProvider extends ScanningAppProvider } String lowername = name.toLowerCase(Locale.ENGLISH); - File file = new File(dir,name); + File file = new File(dir, name); // ignore hidden files if (lowername.startsWith(".")) @@ -94,11 +94,11 @@ public class WebAppProvider extends ScanningAppProvider return false; // is it an unpacked directory for an existing war file? - if (exists(name+".war")||exists(name+".WAR")) + if (exists(name + ".war") || exists(name + ".WAR")) return false; // is it a directory for an existing xml file? - if (exists(name+".xml")||exists(name+".XML")) + if (exists(name + ".xml") || exists(name + ".XML")) return false; //is it a sccs dir? @@ -131,7 +131,9 @@ public class WebAppProvider extends ScanningAppProvider setScanInterval(0); } - /** Get the extractWars. + /** + * Get the extractWars. + * * @return the extractWars */ @ManagedAttribute("extract war files") @@ -140,7 +142,9 @@ public class WebAppProvider extends ScanningAppProvider return _extractWars; } - /** Set the extractWars. + /** + * Set the extractWars. + * * @param extractWars the extractWars to set */ public void setExtractWars(boolean extractWars) @@ -148,7 +152,9 @@ public class WebAppProvider extends ScanningAppProvider _extractWars = extractWars; } - /** Get the parentLoaderPriority. + /** + * Get the parentLoaderPriority. + * * @return the parentLoaderPriority */ @ManagedAttribute("parent classloader has priority") @@ -157,7 +163,9 @@ public class WebAppProvider extends ScanningAppProvider return _parentLoaderPriority; } - /** Set the parentLoaderPriority. + /** + * Set the parentLoaderPriority. + * * @param parentLoaderPriority the parentLoaderPriority to set */ public void setParentLoaderPriority(boolean parentLoaderPriority) @@ -165,7 +173,9 @@ public class WebAppProvider extends ScanningAppProvider _parentLoaderPriority = parentLoaderPriority; } - /** Get the defaultsDescriptor. + /** + * Get the defaultsDescriptor. + * * @return the defaultsDescriptor */ @ManagedAttribute("default descriptor for webapps") @@ -174,7 +184,9 @@ public class WebAppProvider extends ScanningAppProvider return _defaultsDescriptor; } - /** Set the defaultsDescriptor. + /** + * Set the defaultsDescriptor. + * * @param defaultsDescriptor the defaultsDescriptor to set */ public void setDefaultsDescriptor(String defaultsDescriptor) @@ -187,7 +199,9 @@ public class WebAppProvider extends ScanningAppProvider return _configurationManager; } - /** Set the configurationManager. + /** + * Set the configurationManager. + * * @param configurationManager the configurationManager to set */ public void setConfigurationManager(ConfigurationManager configurationManager) @@ -200,8 +214,8 @@ public class WebAppProvider extends ScanningAppProvider */ public void setConfigurationClasses(String[] configurations) { - _configurationClasses = configurations==null?null:(String[])configurations.clone(); - } + _configurationClasses = configurations == null ? null : (String[])configurations.clone(); + } @ManagedAttribute("configuration classes for webapps to be processed through") public String[] getConfigurationClasses() @@ -245,7 +259,7 @@ public class WebAppProvider extends ScanningAppProvider { /* Since the Temp Dir is really a context base temp directory, * Lets set the Temp Directory in a way similar to how WebInfConfiguration does it, - * instead of setting the WebAppContext.setTempDirectory(File). + * instead of setting the WebAppContext.setTempDirectory(File). * If we used .setTempDirectory(File) all webapps will wind up in the * same temp / work directory, overwriting each others work. */ @@ -259,7 +273,7 @@ public class WebAppProvider extends ScanningAppProvider Resource resource = Resource.newResource(app.getOriginId()); File file = resource.getFile(); if (!resource.exists()) - throw new IllegalStateException("App resource does not exist "+resource); + throw new IllegalStateException("App resource does not exist " + resource); String context = file.getName(); @@ -279,8 +293,8 @@ public class WebAppProvider extends ScanningAppProvider } } }; - - getDeploymentManager().scope(xmlc,resource); + + getDeploymentManager().scope(xmlc, resource); if (getConfigurationManager() != null) xmlc.getProperties().putAll(getConfigurationManager().getProperties()); @@ -293,17 +307,17 @@ public class WebAppProvider extends ScanningAppProvider else if (FileID.isWebArchiveFile(file)) { // Context Path is the same as the archive. - context = context.substring(0,context.length() - 4); + context = context.substring(0, context.length() - 4); } else { - throw new IllegalStateException("unable to create ContextHandler for "+app); + throw new IllegalStateException("unable to create ContextHandler for " + app); } // Ensure "/" is Not Trailing in context paths. if (context.endsWith("/") && context.length() > 0) { - context = context.substring(0,context.length() - 1); + context = context.substring(0, context.length() - 1); } // Start building the webapplication @@ -317,8 +331,8 @@ public class WebAppProvider extends ScanningAppProvider } else if (context.toLowerCase(Locale.ENGLISH).startsWith("root-")) { - int dash=context.toLowerCase(Locale.ENGLISH).indexOf('-'); - String virtual = context.substring(dash+1); + int dash = context.toLowerCase(Locale.ENGLISH).indexOf('-'); + String virtual = context.substring(dash + 1); webAppContext.setVirtualHosts(new String[]{virtual}); context = URIUtil.SLASH; } @@ -338,45 +352,44 @@ public class WebAppProvider extends ScanningAppProvider @Override protected void fileChanged(String filename) throws Exception - { + { File file = new File(filename); if (!file.exists()) return; - + File parent = file.getParentFile(); - + //is the file that changed a directory? if (file.isDirectory()) { //is there a .xml file of the same name? - if (exists(file.getName()+".xml")||exists(file.getName()+".XML")) + if (exists(file.getName() + ".xml") || exists(file.getName() + ".XML")) return; //ignore it //is there .war file of the same name? - if (exists(file.getName()+".war")||exists(file.getName()+".WAR")) + if (exists(file.getName() + ".war") || exists(file.getName() + ".WAR")) return; //ignore it - super.fileChanged(filename); - return; + super.fileChanged(filename); + return; } - - + String lowname = file.getName().toLowerCase(Locale.ENGLISH); //is the file that changed a .war file? if (lowname.endsWith(".war")) { String name = file.getName(); - String base=name.substring(0,name.length()-4); - String xmlname = base+".xml"; + String base = name.substring(0, name.length() - 4); + String xmlname = base + ".xml"; if (exists(xmlname)) { //if a .xml file exists for it, then redeploy that instead - File xml = new File (parent, xmlname); + File xml = new File(parent, xmlname); super.fileChanged(xml.getCanonicalPath()); return; } - - xmlname = base+".XML"; + + xmlname = base + ".XML"; if (exists(xmlname)) { //if a .XML file exists for it, then redeploy that instead @@ -384,7 +397,7 @@ public class WebAppProvider extends ScanningAppProvider super.fileChanged(xml.getCanonicalPath()); return; } - + //redeploy the changed war super.fileChanged(filename); return; @@ -406,11 +419,11 @@ public class WebAppProvider extends ScanningAppProvider if (file.isDirectory()) { //is there a .xml file of the same name? - if (exists(file.getName()+".xml")||exists(file.getName()+".XML")) + if (exists(file.getName() + ".xml") || exists(file.getName() + ".XML")) return; //assume we will get added events for the xml file //is there .war file of the same name? - if (exists(file.getName()+".war")||exists(file.getName()+".WAR")) + if (exists(file.getName() + ".war") || exists(file.getName() + ".WAR")) return; //assume we will get added events for the war file super.fileAdded(filename); @@ -422,9 +435,9 @@ public class WebAppProvider extends ScanningAppProvider if (lowname.endsWith(".war")) { String name = file.getName(); - String base=name.substring(0,name.length()-4); + String base = name.substring(0, name.length() - 4); //is there a .xml file of the same name? - if (exists(base+".xml")||exists(base+".XML")) + if (exists(base + ".xml") || exists(base + ".XML")) return; //ignore it as we should get addition of the xml file super.fileAdded(filename); @@ -438,7 +451,7 @@ public class WebAppProvider extends ScanningAppProvider @Override protected void fileRemoved(String filename) throws Exception - { + { File file = new File(filename); //is the file that was removed a .war file? @@ -447,8 +460,8 @@ public class WebAppProvider extends ScanningAppProvider { //is there a .xml file of the same name? String name = file.getName(); - String base=name.substring(0,name.length()-4); - if (exists(base+".xml")||exists(base+".XML")) + String base = name.substring(0, name.length() - 4); + if (exists(base + ".xml") || exists(base + ".XML")) return; //ignore it as we should get removal of the xml file super.fileRemoved(filename); @@ -463,14 +476,13 @@ public class WebAppProvider extends ScanningAppProvider } //is there a .xml file of the same name? - if (exists(file.getName()+".xml")||exists(file.getName()+".XML")) + if (exists(file.getName() + ".xml") || exists(file.getName() + ".XML")) return; //assume we will get removed events for the xml file //is there .war file of the same name? - if (exists(file.getName()+".war")||exists(file.getName()+".WAR")) + if (exists(file.getName() + ".war") || exists(file.getName() + ".WAR")) return; //assume we will get removed events for the war file super.fileRemoved(filename); } - } diff --git a/jetty-deploy/src/main/java/org/eclipse/jetty/deploy/providers/jmx/WebAppProviderMBean.java b/jetty-deploy/src/main/java/org/eclipse/jetty/deploy/providers/jmx/WebAppProviderMBean.java index c771c2b64af..6200f1a8c4b 100644 --- a/jetty-deploy/src/main/java/org/eclipse/jetty/deploy/providers/jmx/WebAppProviderMBean.java +++ b/jetty-deploy/src/main/java/org/eclipse/jetty/deploy/providers/jmx/WebAppProviderMBean.java @@ -37,8 +37,8 @@ public class WebAppProviderMBean extends ObjectMBean @ManagedAttribute("List of monitored resources") public List getMonitoredResources() { - return ((WebAppProvider) _managed).getMonitoredResources().stream() - .map((r) -> r.getURI().toASCIIString()) - .collect(Collectors.toList()); + return ((WebAppProvider)_managed).getMonitoredResources().stream() + .map((r) -> r.getURI().toASCIIString()) + .collect(Collectors.toList()); } } diff --git a/jetty-deploy/src/main/java/org/eclipse/jetty/deploy/util/FileID.java b/jetty-deploy/src/main/java/org/eclipse/jetty/deploy/util/FileID.java index b939fa8dbf4..4bd620aba16 100644 --- a/jetty-deploy/src/main/java/org/eclipse/jetty/deploy/util/FileID.java +++ b/jetty-deploy/src/main/java/org/eclipse/jetty/deploy/util/FileID.java @@ -29,9 +29,8 @@ public class FileID { /** * Is the path a Web Archive? - * - * @param path - * the path to test. + * + * @param path the path to test. * @return True if a .war or .jar or exploded web directory * @see FileID#isWebArchiveFile(File) */ @@ -43,16 +42,15 @@ public class FileID return (name.endsWith(".war") || name.endsWith(".jar")); } - File webInf = new File(path,"WEB-INF"); - File webXml = new File(webInf,"web.xml"); + File webInf = new File(path, "WEB-INF"); + File webXml = new File(webInf, "web.xml"); return webXml.exists() && webXml.isFile(); } /** * Is the path a Web Archive File (not directory) - * - * @param path - * the path to test. + * + * @param path the path to test. * @return True if a .war or .jar file. * @see FileID#isWebArchive(File) */ diff --git a/jetty-deploy/src/test/java/org/eclipse/jetty/deploy/AppLifeCyclePathCollector.java b/jetty-deploy/src/test/java/org/eclipse/jetty/deploy/AppLifeCyclePathCollector.java index 22537f18f82..454a24296e3 100644 --- a/jetty-deploy/src/test/java/org/eclipse/jetty/deploy/AppLifeCyclePathCollector.java +++ b/jetty-deploy/src/test/java/org/eclipse/jetty/deploy/AppLifeCyclePathCollector.java @@ -18,13 +18,12 @@ package org.eclipse.jetty.deploy; -import static org.junit.jupiter.api.Assertions.assertEquals; - import java.util.ArrayList; import java.util.List; import org.eclipse.jetty.deploy.graph.Node; +import static org.junit.jupiter.api.Assertions.assertEquals; /** * Binds to all lifecycle nodes, and tracks the order of the lifecycle nodes for testing purposes. @@ -47,7 +46,7 @@ public class AppLifeCyclePathCollector implements AppLifeCycle.Binding public String[] getBindingTargets() { return new String[] - { "*" }; + {"*"}; } @Override @@ -71,12 +70,12 @@ public class AppLifeCyclePathCollector implements AppLifeCycle.Binding System.out.println(path.getName()); } - assertEquals(expectedOrder.size(),actualOrder.size(),msg + " / count"); + assertEquals(expectedOrder.size(), actualOrder.size(), msg + " / count"); } for (int i = 0, n = expectedOrder.size(); i < n; i++) { - assertEquals(expectedOrder.get(i),actualOrder.get(i).getName(),msg + "[" + i + "]"); + assertEquals(expectedOrder.get(i), actualOrder.get(i).getName(), msg + "[" + i + "]"); } } } diff --git a/jetty-deploy/src/test/java/org/eclipse/jetty/deploy/AppLifeCycleTest.java b/jetty-deploy/src/test/java/org/eclipse/jetty/deploy/AppLifeCycleTest.java index 9a0f5145fe3..8008425d5ae 100644 --- a/jetty-deploy/src/test/java/org/eclipse/jetty/deploy/AppLifeCycleTest.java +++ b/jetty-deploy/src/test/java/org/eclipse/jetty/deploy/AppLifeCycleTest.java @@ -18,9 +18,6 @@ package org.eclipse.jetty.deploy; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertNotNull; - import java.io.File; import java.io.IOException; import java.util.ArrayList; @@ -34,6 +31,9 @@ import org.eclipse.jetty.toolchain.test.jupiter.WorkDirExtension; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; + /** * Just an overly picky test case to validate the potential paths. */ @@ -44,21 +44,21 @@ public class AppLifeCycleTest private void assertNoPath(String from, String to) { - assertPath(from,to,new ArrayList()); + assertPath(from, to, new ArrayList()); } private void assertPath(AppLifeCycle lifecycle, String from, String to, List expected) { Node fromNode = lifecycle.getNodeByName(from); Node toNode = lifecycle.getNodeByName(to); - Path actual = lifecycle.getPath(fromNode,toNode); + Path actual = lifecycle.getPath(fromNode, toNode); String msg = "LifeCycle path from " + from + " to " + to; - assertNotNull(actual,msg + " should never be null"); + assertNotNull(actual, msg + " should never be null"); if (expected.size() != actual.nodes()) { System.out.println(); - System.out.printf("/* from '%s' -> '%s' */%n",from,to); + System.out.printf("/* from '%s' -> '%s' */%n", from, to); System.out.println("/* Expected Path */"); for (String path : expected) { @@ -70,25 +70,25 @@ public class AppLifeCycleTest System.out.println(path.getName()); } - assertEquals(expected.size(),actual.nodes(),msg + " / count"); + assertEquals(expected.size(), actual.nodes(), msg + " / count"); } for (int i = 0, n = expected.size(); i < n; i++) { - assertEquals(expected.get(i),actual.getNode(i).getName(),msg + "[" + i + "]"); + assertEquals(expected.get(i), actual.getNode(i).getName(), msg + "[" + i + "]"); } } private void assertPath(String from, String to, List expected) { AppLifeCycle lifecycle = new AppLifeCycle(); - assertPath(lifecycle,from,to,expected); + assertPath(lifecycle, from, to, expected); } @Test public void testFindPath_Deployed_Deployed() { - assertNoPath("deployed","deployed"); + assertNoPath("deployed", "deployed"); } @Test @@ -98,7 +98,7 @@ public class AppLifeCycleTest expected.add("deployed"); expected.add("starting"); expected.add("started"); - assertPath("deployed","started",expected); + assertPath("deployed", "started", expected); } @Test @@ -108,7 +108,7 @@ public class AppLifeCycleTest expected.add("deployed"); expected.add("undeploying"); expected.add("undeployed"); - assertPath("deployed","undeployed",expected); + assertPath("deployed", "undeployed", expected); } @Test @@ -118,13 +118,13 @@ public class AppLifeCycleTest expected.add("started"); expected.add("stopping"); expected.add("deployed"); - assertPath("started","deployed",expected); + assertPath("started", "deployed", expected); } @Test public void testFindPath_Started_Started() { - assertNoPath("started","started"); + assertNoPath("started", "started"); } @Test @@ -136,7 +136,7 @@ public class AppLifeCycleTest expected.add("deployed"); expected.add("undeploying"); expected.add("undeployed"); - assertPath("started","undeployed",expected); + assertPath("started", "undeployed", expected); } @Test @@ -146,7 +146,7 @@ public class AppLifeCycleTest expected.add("undeployed"); expected.add("deploying"); expected.add("deployed"); - assertPath("undeployed","deployed",expected); + assertPath("undeployed", "deployed", expected); } @Test @@ -158,19 +158,19 @@ public class AppLifeCycleTest expected.add("deployed"); expected.add("starting"); expected.add("started"); - assertPath("undeployed","started",expected); + assertPath("undeployed", "started", expected); } @Test public void testFindPath_Undeployed_Uavailable() { - assertNoPath("undeployed","undeployed"); + assertNoPath("undeployed", "undeployed"); } /** * Request multiple lifecycle paths with a single lifecycle instance. Just to ensure that there is no state * maintained between {@link AppLifeCycle#getPath(Node, Node)} requests. - * + * * @throws IOException on test failure */ @Test @@ -182,22 +182,22 @@ public class AppLifeCycleTest File outputDir = testdir.getEmptyPathDir().toFile(); // Modify graph to add new 'staging' -> 'staged' between 'deployed' and 'started' - GraphOutputDot.write(lifecycle,new File(outputDir,"multiple-1.dot")); // before change - lifecycle.insertNode(lifecycle.getPath("deployed","started").getEdge(0),"staging"); - GraphOutputDot.write(lifecycle,new File(outputDir,"multiple-2.dot")); // after first change - lifecycle.insertNode(lifecycle.getPath("staging","started").getEdge(0),"staged"); - GraphOutputDot.write(lifecycle,new File(outputDir,"multiple-3.dot")); // after second change + GraphOutputDot.write(lifecycle, new File(outputDir, "multiple-1.dot")); // before change + lifecycle.insertNode(lifecycle.getPath("deployed", "started").getEdge(0), "staging"); + GraphOutputDot.write(lifecycle, new File(outputDir, "multiple-2.dot")); // after first change + lifecycle.insertNode(lifecycle.getPath("staging", "started").getEdge(0), "staged"); + GraphOutputDot.write(lifecycle, new File(outputDir, "multiple-3.dot")); // after second change // Deployed -> Deployed expected.clear(); - assertPath(lifecycle,"deployed","deployed",expected); + assertPath(lifecycle, "deployed", "deployed", expected); // Deployed -> Staged expected.clear(); expected.add("deployed"); expected.add("staging"); expected.add("staged"); - assertPath(lifecycle,"deployed","staged",expected); + assertPath(lifecycle, "deployed", "staged", expected); // Staged -> Undeployed expected.clear(); @@ -208,7 +208,7 @@ public class AppLifeCycleTest expected.add("deployed"); expected.add("undeploying"); expected.add("undeployed"); - assertPath(lifecycle,"staged","undeployed",expected); + assertPath(lifecycle, "staged", "undeployed", expected); // Undeployed -> Started expected.clear(); @@ -219,7 +219,6 @@ public class AppLifeCycleTest expected.add("staged"); expected.add("starting"); expected.add("started"); - assertPath(lifecycle,"undeployed","started",expected); + assertPath(lifecycle, "undeployed", "started", expected); } - } diff --git a/jetty-deploy/src/test/java/org/eclipse/jetty/deploy/BadAppDeployTest.java b/jetty-deploy/src/test/java/org/eclipse/jetty/deploy/BadAppDeployTest.java index 132b5cbe5f1..b939781fdaa 100644 --- a/jetty-deploy/src/test/java/org/eclipse/jetty/deploy/BadAppDeployTest.java +++ b/jetty-deploy/src/test/java/org/eclipse/jetty/deploy/BadAppDeployTest.java @@ -101,11 +101,12 @@ public class BadAppDeployTest server.addBean(deploymentManager); // this should be done after setHandler(handlers) - assertTimeoutPreemptively(ofSeconds(10), () -> { + assertTimeoutPreemptively(ofSeconds(10), () -> + { try (StacklessLogging ignore = new StacklessLogging(Log.getLogger(WebAppContext.class), - Log.getLogger(DeploymentManager.class), - Log.getLogger("org.eclipse.jetty.server.handler.ContextHandler.badapp"))) + Log.getLogger(DeploymentManager.class), + Log.getLogger("org.eclipse.jetty.server.handler.ContextHandler.badapp"))) { ServletException cause = assertThrows(ServletException.class, () -> server.start()); assertThat(cause.getMessage(), containsString("intentionally")); @@ -153,11 +154,12 @@ public class BadAppDeployTest handlers.addHandler(new DefaultHandler()); server.setHandler(handlers); // this should be done after addBean(deploymentManager) - assertTimeoutPreemptively(ofSeconds(10), () -> { + assertTimeoutPreemptively(ofSeconds(10), () -> + { try (StacklessLogging ignore = new StacklessLogging(Log.getLogger(WebAppContext.class), - Log.getLogger(DeploymentManager.class), - Log.getLogger("org.eclipse.jetty.server.handler.ContextHandler.badapp"))) + Log.getLogger(DeploymentManager.class), + Log.getLogger("org.eclipse.jetty.server.handler.ContextHandler.badapp"))) { ServletException cause = assertThrows(ServletException.class, () -> server.start()); assertThat(cause.getMessage(), containsString("intentionally")); diff --git a/jetty-deploy/src/test/java/org/eclipse/jetty/deploy/DeploymentManagerLifeCyclePathTest.java b/jetty-deploy/src/test/java/org/eclipse/jetty/deploy/DeploymentManagerLifeCyclePathTest.java index 19dbf3846a8..ba920b73a1e 100644 --- a/jetty-deploy/src/test/java/org/eclipse/jetty/deploy/DeploymentManagerLifeCyclePathTest.java +++ b/jetty-deploy/src/test/java/org/eclipse/jetty/deploy/DeploymentManagerLifeCyclePathTest.java @@ -21,7 +21,6 @@ package org.eclipse.jetty.deploy; import java.lang.management.ManagementFactory; import java.util.ArrayList; import java.util.List; - import javax.management.MBeanServerConnection; import javax.management.ObjectName; @@ -53,7 +52,7 @@ public class DeploymentManagerLifeCyclePathTest App app = depman.getAppByOriginId("mock-foo-webapp-1.war"); // Request Deploy of App - depman.requestAppGoal(app,"deployed"); + depman.requestAppGoal(app, "deployed"); // Setup Expectations. List expected = new ArrayList(); @@ -61,7 +60,7 @@ public class DeploymentManagerLifeCyclePathTest expected.add("deploying"); expected.add("deployed"); - pathtracker.assertExpected("Test StateTransition / New -> Deployed",expected); + pathtracker.assertExpected("Test StateTransition / New -> Deployed", expected); } @Test @@ -87,7 +86,7 @@ public class DeploymentManagerLifeCyclePathTest // Setup Expectations. List expected = new ArrayList(); - pathtracker.assertExpected("Test StateTransition / New only",expected); + pathtracker.assertExpected("Test StateTransition / New only", expected); } @Test @@ -99,7 +98,7 @@ public class DeploymentManagerLifeCyclePathTest MockAppProvider mockProvider = new MockAppProvider(); // Setup JMX - MBeanContainer mbContainer=new MBeanContainer(ManagementFactory.getPlatformMBeanServer()); + MBeanContainer mbContainer = new MBeanContainer(ManagementFactory.getPlatformMBeanServer()); depman.addBean(mbContainer); depman.addLifeCycleBinding(pathtracker); @@ -115,15 +114,15 @@ public class DeploymentManagerLifeCyclePathTest App app = depman.getAppByOriginId("mock-foo-webapp-1.war"); // Request Deploy of App - depman.requestAppGoal(app,"deployed"); + depman.requestAppGoal(app, "deployed"); JmxServiceConnection jmxConnection = new JmxServiceConnection(); jmxConnection.connect(); MBeanServerConnection mbsConnection = jmxConnection.getConnection(); ObjectName dmObjName = new ObjectName("org.eclipse.jetty.deploy:type=deploymentmanager,id=0"); - String[] params = new String[] {"mock-foo-webapp-1.war", "undeployed"}; - String[] signature = new String[] {"java.lang.String", "java.lang.String"}; + String[] params = new String[]{"mock-foo-webapp-1.war", "undeployed"}; + String[] signature = new String[]{"java.lang.String", "java.lang.String"}; mbsConnection.invoke(dmObjName, "requestAppGoal", params, signature); // Setup Expectations. @@ -134,6 +133,6 @@ public class DeploymentManagerLifeCyclePathTest expected.add("undeploying"); expected.add("undeployed"); - pathtracker.assertExpected("Test JMX StateTransition / Deployed -> Undeployed",expected); + pathtracker.assertExpected("Test JMX StateTransition / Deployed -> Undeployed", expected); } } diff --git a/jetty-deploy/src/test/java/org/eclipse/jetty/deploy/DeploymentManagerTest.java b/jetty-deploy/src/test/java/org/eclipse/jetty/deploy/DeploymentManagerTest.java index 0eecf6aec3f..694fdb02a55 100644 --- a/jetty-deploy/src/test/java/org/eclipse/jetty/deploy/DeploymentManagerTest.java +++ b/jetty-deploy/src/test/java/org/eclipse/jetty/deploy/DeploymentManagerTest.java @@ -18,9 +18,6 @@ package org.eclipse.jetty.deploy; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertNotNull; - import java.util.Collection; import java.util.Set; @@ -31,6 +28,9 @@ import org.eclipse.jetty.toolchain.test.jupiter.WorkDirExtension; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; + @ExtendWith(WorkDirExtension.class) public class DeploymentManagerTest { diff --git a/jetty-deploy/src/test/java/org/eclipse/jetty/deploy/JmxServiceConnection.java b/jetty-deploy/src/test/java/org/eclipse/jetty/deploy/JmxServiceConnection.java index d112ed0f834..30c5cc67b47 100644 --- a/jetty-deploy/src/test/java/org/eclipse/jetty/deploy/JmxServiceConnection.java +++ b/jetty-deploy/src/test/java/org/eclipse/jetty/deploy/JmxServiceConnection.java @@ -32,7 +32,7 @@ import org.eclipse.jetty.toolchain.test.IO; /** * JmxServiceConnection - * + * * Provides ability to create a connection to either an external * JMX server, or a loopback connection to the internal one. */ @@ -54,9 +54,8 @@ public class JmxServiceConnection /** * Construct a connection to specified server - * - * @param url - * URL of JMX server + * + * @param url URL of JMX server */ public JmxServiceConnection(String url) { @@ -65,7 +64,7 @@ public class JmxServiceConnection /** * Retrieve an external URL for the JMX server - * + * * @return service URL */ public String getServiceUrl() @@ -75,7 +74,7 @@ public class JmxServiceConnection /** * Retrieve a connection to MBean server - * + * * @return connection to MBean server */ public MBeanServerConnection getConnection() @@ -100,15 +99,13 @@ public class JmxServiceConnection /** * Open a loopback connection to local JMX server - * - * @throws IOException */ private void openLoopbackConnection() throws IOException { server = ManagementFactory.getPlatformMBeanServer(); JMXServiceURL serviceUrl = new JMXServiceURL("service:jmx:rmi://"); - connectorServer = JMXConnectorServerFactory.newJMXConnectorServer(serviceUrl,null,server); + connectorServer = JMXConnectorServerFactory.newJMXConnectorServer(serviceUrl, null, server); connectorServer.start(); this.serviceUrl = connectorServer.getAddress().toString(); @@ -119,9 +116,6 @@ public class JmxServiceConnection /** * Open a connection to remote JMX server - * - * @param url - * @throws IOException */ private void openServerConnection(String url) throws IOException { diff --git a/jetty-deploy/src/test/java/org/eclipse/jetty/deploy/MockAppProvider.java b/jetty-deploy/src/test/java/org/eclipse/jetty/deploy/MockAppProvider.java index c8d4664e5a2..ac78211d2f9 100644 --- a/jetty-deploy/src/test/java/org/eclipse/jetty/deploy/MockAppProvider.java +++ b/jetty-deploy/src/test/java/org/eclipse/jetty/deploy/MockAppProvider.java @@ -47,7 +47,7 @@ public class MockAppProvider extends AbstractLifeCycle implements AppProvider public void findWebapp(String name) { - App app = new App(deployMan,this,"mock-" + name); + App app = new App(deployMan, this, "mock-" + name); this.deployMan.addApp(app); } @@ -56,17 +56,17 @@ public class MockAppProvider extends AbstractLifeCycle implements AppProvider { WebAppContext context = new WebAppContext(); - File war = new File(webappsDir,app.getOriginId().substring(5)); + File war = new File(webappsDir, app.getOriginId().substring(5)); context.setWar(Resource.newResource(Resource.toURL(war)).toString()); String path = war.getName(); - + if (FileID.isWebArchiveFile(war)) { // Context Path is the same as the archive. - path = path.substring(0,path.length() - 4); + path = path.substring(0, path.length() - 4); } - + // special case of archive (or dir) named "root" is / context if (path.equalsIgnoreCase("root") || path.equalsIgnoreCase("root/")) path = URIUtil.SLASH; @@ -77,10 +77,10 @@ public class MockAppProvider extends AbstractLifeCycle implements AppProvider // Ensure "/" is Not Trailing in context paths. if (path.endsWith("/") && path.length() > 0) - path = path.substring(0,path.length() - 1); + path = path.substring(0, path.length() - 1); context.setDefaultContextPath(path); - + return context; } } diff --git a/jetty-deploy/src/test/java/org/eclipse/jetty/deploy/bindings/GlobalWebappConfigBindingTest.java b/jetty-deploy/src/test/java/org/eclipse/jetty/deploy/bindings/GlobalWebappConfigBindingTest.java index 3e385dfdb7f..99c1d211201 100644 --- a/jetty-deploy/src/test/java/org/eclipse/jetty/deploy/bindings/GlobalWebappConfigBindingTest.java +++ b/jetty-deploy/src/test/java/org/eclipse/jetty/deploy/bindings/GlobalWebappConfigBindingTest.java @@ -58,9 +58,8 @@ public class GlobalWebappConfigBindingTest jetty.addConfiguration("jetty-http.xml"); // Setup initial context - jetty.copyWebapp("foo.xml","foo.xml"); - jetty.copyWebapp("foo-webapp-1.war","foo.war"); - + jetty.copyWebapp("foo.xml", "foo.xml"); + jetty.copyWebapp("foo-webapp-1.war", "foo.war"); } @AfterEach @@ -74,10 +73,10 @@ public class GlobalWebappConfigBindingTest public void testServerAndSystemClassesOverride() throws Exception { File srcXml = MavenTestingUtils.getTestResourceFile("context-binding-test-1.xml"); - File destXml = new File(jetty.getJettyHome(),"context-binding-test-1.xml"); - IO.copy(srcXml,destXml); + File destXml = new File(jetty.getJettyHome(), "context-binding-test-1.xml"); + IO.copy(srcXml, destXml); - PathAssert.assertFileExists("Context Binding XML",destXml); + PathAssert.assertFileExists("Context Binding XML", destXml); jetty.addConfiguration("binding-test-contexts-1.xml"); jetty.load(); @@ -92,7 +91,7 @@ public class GlobalWebappConfigBindingTest String currentClasses[] = context.getServerClasses(); String addedClass = "org.eclipse.foo."; // What was added by the binding - assertThat("Current Server Classes",addedClass,is(in(currentClasses))); + assertThat("Current Server Classes", addedClass, is(in(currentClasses))); // boolean jndiPackage = false; diff --git a/jetty-deploy/src/test/java/org/eclipse/jetty/deploy/graph/GraphTest.java b/jetty-deploy/src/test/java/org/eclipse/jetty/deploy/graph/GraphTest.java index 96ce050cae2..f8d4525857f 100644 --- a/jetty-deploy/src/test/java/org/eclipse/jetty/deploy/graph/GraphTest.java +++ b/jetty-deploy/src/test/java/org/eclipse/jetty/deploy/graph/GraphTest.java @@ -18,11 +18,10 @@ package org.eclipse.jetty.deploy.graph; +import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertEquals; -import org.junit.jupiter.api.Test; - public class GraphTest { final Node nodeA = new Node("A"); @@ -31,7 +30,6 @@ public class GraphTest final Node nodeD = new Node("D"); final Node nodeE = new Node("E"); - @Test public void testPath() { @@ -39,18 +37,18 @@ public class GraphTest Path path = new Path(); assertEquals(0, path.nodes()); - assertEquals(null,path.firstNode()); - assertEquals(null,path.lastNode()); + assertEquals(null, path.firstNode()); + assertEquals(null, path.lastNode()); - path.add(new Edge(nodeA ,nodeB)); - assertEquals(2,path.nodes()); - assertEquals(nodeA,path.firstNode()); - assertEquals(nodeB,path.lastNode()); + path.add(new Edge(nodeA, nodeB)); + assertEquals(2, path.nodes()); + assertEquals(nodeA, path.firstNode()); + assertEquals(nodeB, path.lastNode()); - path.add(new Edge(nodeB ,nodeC)); - assertEquals(3,path.nodes()); - assertEquals(nodeA,path.firstNode()); - assertEquals(nodeC,path.lastNode()); + path.add(new Edge(nodeB, nodeC)); + assertEquals(3, path.nodes()); + assertEquals(nodeA, path.firstNode()); + assertEquals(nodeC, path.lastNode()); } @Test @@ -58,81 +56,77 @@ public class GraphTest { Graph graph = new Graph(); graph.addNode(nodeA); - assertEquals(1,graph.getNodes().size()); - assertEquals(0,graph.getEdges().size()); - Path path = graph.getPath(nodeA,nodeA); - assertEquals(0,path.nodes()); + assertEquals(1, graph.getNodes().size()); + assertEquals(0, graph.getEdges().size()); + Path path = graph.getPath(nodeA, nodeA); + assertEquals(0, path.nodes()); } @Test public void testLine() { Graph graph = new Graph(); - graph.addEdge(new Edge(nodeA,nodeB)); - assertEquals(2,graph.getNodes().size()); - assertEquals(1,graph.getEdges().size()); - Path path = graph.getPath(nodeA,nodeB); - assertEquals(2,path.nodes()); + graph.addEdge(new Edge(nodeA, nodeB)); + assertEquals(2, graph.getNodes().size()); + assertEquals(1, graph.getEdges().size()); + Path path = graph.getPath(nodeA, nodeB); + assertEquals(2, path.nodes()); } @Test public void testTriangleDirected() { Graph graph = new Graph(); - graph.addEdge(new Edge(nodeA,nodeB)); - graph.addEdge(new Edge(nodeA,nodeC)); - graph.addEdge(new Edge(nodeB,nodeC)); - assertEquals(3,graph.getNodes().size()); - assertEquals(3,graph.getEdges().size()); - Path path = graph.getPath(nodeA,nodeB); - assertEquals(2,path.nodes()); - path = graph.getPath(nodeA,nodeC); - assertEquals(2,path.nodes()); - path = graph.getPath(nodeB,nodeC); - assertEquals(2,path.nodes()); - + graph.addEdge(new Edge(nodeA, nodeB)); + graph.addEdge(new Edge(nodeA, nodeC)); + graph.addEdge(new Edge(nodeB, nodeC)); + assertEquals(3, graph.getNodes().size()); + assertEquals(3, graph.getEdges().size()); + Path path = graph.getPath(nodeA, nodeB); + assertEquals(2, path.nodes()); + path = graph.getPath(nodeA, nodeC); + assertEquals(2, path.nodes()); + path = graph.getPath(nodeB, nodeC); + assertEquals(2, path.nodes()); } @Test public void testSquareDirected() { Graph graph = new Graph(); - graph.addEdge(new Edge(nodeA,nodeB)); - graph.addEdge(new Edge(nodeB,nodeC)); - graph.addEdge(new Edge(nodeA,nodeD)); - graph.addEdge(new Edge(nodeD,nodeC)); - assertEquals(4,graph.getNodes().size()); - assertEquals(4,graph.getEdges().size()); - Path path = graph.getPath(nodeA,nodeC); - assertEquals(3,path.nodes()); - - path = graph.getPath(nodeC,nodeA); - assertEquals(null,path); + graph.addEdge(new Edge(nodeA, nodeB)); + graph.addEdge(new Edge(nodeB, nodeC)); + graph.addEdge(new Edge(nodeA, nodeD)); + graph.addEdge(new Edge(nodeD, nodeC)); + assertEquals(4, graph.getNodes().size()); + assertEquals(4, graph.getEdges().size()); + Path path = graph.getPath(nodeA, nodeC); + assertEquals(3, path.nodes()); + path = graph.getPath(nodeC, nodeA); + assertEquals(null, path); } @Test public void testSquareCyclic() { Graph graph = new Graph(); - graph.addEdge(new Edge(nodeA,nodeB)); - graph.addEdge(new Edge(nodeB,nodeC)); - graph.addEdge(new Edge(nodeC,nodeD)); - graph.addEdge(new Edge(nodeD,nodeA)); - assertEquals(4,graph.getNodes().size()); - assertEquals(4,graph.getEdges().size()); - Path path = graph.getPath(nodeA,nodeB); - assertEquals(2,path.nodes()); + graph.addEdge(new Edge(nodeA, nodeB)); + graph.addEdge(new Edge(nodeB, nodeC)); + graph.addEdge(new Edge(nodeC, nodeD)); + graph.addEdge(new Edge(nodeD, nodeA)); + assertEquals(4, graph.getNodes().size()); + assertEquals(4, graph.getEdges().size()); + Path path = graph.getPath(nodeA, nodeB); + assertEquals(2, path.nodes()); - path = graph.getPath(nodeA,nodeC); - assertEquals(3,path.nodes()); - path = graph.getPath(nodeA,nodeD); - assertEquals(4,path.nodes()); + path = graph.getPath(nodeA, nodeC); + assertEquals(3, path.nodes()); + path = graph.getPath(nodeA, nodeD); + assertEquals(4, path.nodes()); graph.addNode(nodeE); - path = graph.getPath(nodeA,nodeE); - assertEquals(null,path); + path = graph.getPath(nodeA, nodeE); + assertEquals(null, path); } - - } diff --git a/jetty-deploy/src/test/java/org/eclipse/jetty/deploy/providers/ScanningAppProviderRuntimeUpdatesTest.java b/jetty-deploy/src/test/java/org/eclipse/jetty/deploy/providers/ScanningAppProviderRuntimeUpdatesTest.java index ce930a16387..82bd338ca45 100644 --- a/jetty-deploy/src/test/java/org/eclipse/jetty/deploy/providers/ScanningAppProviderRuntimeUpdatesTest.java +++ b/jetty-deploy/src/test/java/org/eclipse/jetty/deploy/providers/ScanningAppProviderRuntimeUpdatesTest.java @@ -18,8 +18,6 @@ package org.eclipse.jetty.deploy.providers; -import static org.junit.jupiter.api.condition.OS.WINDOWS; - import java.io.IOException; import java.util.concurrent.atomic.AtomicInteger; @@ -38,6 +36,8 @@ import org.junit.jupiter.api.Test; import org.junit.jupiter.api.condition.DisabledOnOs; import org.junit.jupiter.api.extension.ExtendWith; +import static org.junit.jupiter.api.condition.OS.WINDOWS; + /** * Similar in scope to {@link ScanningAppProviderStartupTest}, except is concerned with the modification of existing * deployed webapps due to incoming changes identified by the {@link ScanningAppProvider}. @@ -57,7 +57,7 @@ public class ScanningAppProviderRuntimeUpdatesTest { testdir.ensureEmpty(); Resource.setDefaultUseCaches(false); - + jetty = new XmlConfiguredJetty(testdir.getEmptyPathDir()); jetty.addConfiguration("jetty.xml"); jetty.addConfiguration("jetty-http.xml"); @@ -86,7 +86,6 @@ public class ScanningAppProviderRuntimeUpdatesTest }); } } - } @AfterEach @@ -98,30 +97,31 @@ public class ScanningAppProviderRuntimeUpdatesTest public void waitForDirectoryScan() { - int scan=_scans.get()+(2*_providers); + int scan = _scans.get() + (2 * _providers); do { try { Thread.sleep(200); } - catch(InterruptedException e) + catch (InterruptedException e) { LOG.warn(e); } } - while(_scans.get() _xmlConfigurations; - private Map _properties = new HashMap<>(); + private Map _properties = new HashMap<>(); private Server _server; private int _serverPort; private String _scheme = HttpScheme.HTTP.asString(); @@ -89,29 +88,29 @@ public class XmlConfiguredJetty // Prepare Jetty.Home (Test) dir _jettyHome.mkdirs(); - File logsDir = new File(_jettyHome,"logs"); + File logsDir = new File(_jettyHome, "logs"); logsDir.mkdirs(); - File etcDir = new File(_jettyHome,"etc"); + File etcDir = new File(_jettyHome, "etc"); etcDir.mkdirs(); - IO.copyFile(MavenTestingUtils.getTestResourceFile("etc/realm.properties"),new File(etcDir,"realm.properties")); - IO.copyFile(MavenTestingUtils.getTestResourceFile("etc/webdefault.xml"),new File(etcDir,"webdefault.xml")); + IO.copyFile(MavenTestingUtils.getTestResourceFile("etc/realm.properties"), new File(etcDir, "realm.properties")); + IO.copyFile(MavenTestingUtils.getTestResourceFile("etc/webdefault.xml"), new File(etcDir, "webdefault.xml")); - File webappsDir = new File(_jettyHome,"webapps"); + File webappsDir = new File(_jettyHome, "webapps"); if (webappsDir.exists()) { deleteContents(webappsDir); } webappsDir.mkdirs(); - File tmpDir = new File(_jettyHome,"tmp"); + File tmpDir = new File(_jettyHome, "tmp"); if (tmpDir.exists()) { deleteContents(tmpDir); } tmpDir.mkdirs(); - File workishDir = new File(_jettyHome,"workish"); + File workishDir = new File(_jettyHome, "workish"); if (workishDir.exists()) { deleteContents(workishDir); @@ -119,23 +118,25 @@ public class XmlConfiguredJetty workishDir.mkdirs(); // Setup properties - System.setProperty("java.io.tmpdir",tmpDir.getAbsolutePath()); - properties.setProperty("jetty.home",_jettyHome.getAbsolutePath()); - System.setProperty("jetty.home",_jettyHome.getAbsolutePath()); - properties.setProperty("test.basedir",MavenTestingUtils.getBaseDir().getAbsolutePath()); - properties.setProperty("test.resourcesdir",MavenTestingUtils.getTestResourcesDir().getAbsolutePath()); - properties.setProperty("test.webapps",webappsDir.getAbsolutePath()); - properties.setProperty("test.targetdir",MavenTestingUtils.getTargetDir().getAbsolutePath()); - properties.setProperty("test.workdir",workishDir.getAbsolutePath()); + System.setProperty("java.io.tmpdir", tmpDir.getAbsolutePath()); + properties.setProperty("jetty.home", _jettyHome.getAbsolutePath()); + System.setProperty("jetty.home", _jettyHome.getAbsolutePath()); + properties.setProperty("test.basedir", MavenTestingUtils.getBaseDir().getAbsolutePath()); + properties.setProperty("test.resourcesdir", MavenTestingUtils.getTestResourcesDir().getAbsolutePath()); + properties.setProperty("test.webapps", webappsDir.getAbsolutePath()); + properties.setProperty("test.targetdir", MavenTestingUtils.getTargetDir().getAbsolutePath()); + properties.setProperty("test.workdir", workishDir.getAbsolutePath()); // Write out configuration for use by ConfigurationManager. File testConfig = new File(_jettyHome, "xml-configured-jetty.properties"); try (OutputStream out = new FileOutputStream(testConfig)) { - properties.store(out,"Generated by " + XmlConfiguredJetty.class.getName()); + properties.store(out, "Generated by " + XmlConfiguredJetty.class.getName()); + } + for (Object key : properties.keySet()) + { + setProperty(String.valueOf(key), String.valueOf(properties.get(key))); } - for (Object key:properties.keySet()) - setProperty(String.valueOf(key),String.valueOf(properties.get(key))); } public void addConfiguration(File xmlConfigFile) @@ -204,7 +205,7 @@ public class XmlConfiguredJetty System.err.println("## Actual Contexts"); for (WebAppContext context : contexts) { - System.err.printf("%s ## %s%n",context.getContextPath(),context); + System.err.printf("%s ## %s%n", context.getContextPath(), context); } assertEquals(expectedContextPaths.length, contexts.size(), "Contexts.size"); } @@ -221,29 +222,29 @@ public class XmlConfiguredJetty break; } } - assertTrue(found,"Did not find Expected Context Path " + expectedPath); + assertTrue(found, "Did not find Expected Context Path " + expectedPath); } } private void copyFile(String type, File srcFile, File destFile) throws IOException { - PathAssert.assertFileExists(type + " File",srcFile); - IO.copyFile(srcFile,destFile); - PathAssert.assertFileExists(type + " File",destFile); - System.err.printf("Copy %s: %s%n To %s: %s%n",type,srcFile,type,destFile); - System.err.printf("Destination Exists: %s - %s%n",destFile.exists(),destFile); + PathAssert.assertFileExists(type + " File", srcFile); + IO.copyFile(srcFile, destFile); + PathAssert.assertFileExists(type + " File", destFile); + System.err.printf("Copy %s: %s%n To %s: %s%n", type, srcFile, type, destFile); + System.err.printf("Destination Exists: %s - %s%n", destFile.exists(), destFile); } public void copyWebapp(String srcName, String destName) throws IOException { - System.err.printf("Copying Webapp: %s -> %s%n",srcName,destName); + System.err.printf("Copying Webapp: %s -> %s%n", srcName, destName); File srcDir = MavenTestingUtils.getTestResourceDir("webapps"); - File destDir = new File(_jettyHome,"webapps"); + File destDir = new File(_jettyHome, "webapps"); - File srcFile = new File(srcDir,srcName); - File destFile = new File(destDir,destName); + File srcFile = new File(srcDir, srcName); + File destFile = new File(destDir, destName); - copyFile("Webapp",srcFile,destFile); + copyFile("Webapp", srcFile, destFile); } private void deleteContents(File dir) @@ -263,11 +264,11 @@ public class XmlConfiguredJetty if (file.isDirectory() && file.getAbsolutePath().contains("target" + File.separator)) { deleteContents(file); - assertTrue(file.delete(),"Delete failed: " + file.getAbsolutePath()); + assertTrue(file.delete(), "Delete failed: " + file.getAbsolutePath()); } else { - assertTrue(file.delete(),"Delete failed: " + file.getAbsolutePath()); + assertTrue(file.delete(), "Delete failed: " + file.getAbsolutePath()); } } } @@ -275,7 +276,7 @@ public class XmlConfiguredJetty public File getJettyDir(String name) { - return new File(_jettyHome,name); + return new File(_jettyHome, name); } public File getJettyHome() @@ -370,17 +371,17 @@ public class XmlConfiguredJetty public void removeWebapp(String name) { - File destDir = new File(_jettyHome,"webapps"); - File contextFile = new File(destDir,name); + File destDir = new File(_jettyHome, "webapps"); + File contextFile = new File(destDir, name); if (contextFile.exists()) { - assertTrue(contextFile.delete(),"Delete of Webapp file: " + contextFile.getAbsolutePath()); + assertTrue(contextFile.delete(), "Delete of Webapp file: " + contextFile.getAbsolutePath()); } } public void setProperty(String key, String value) { - _properties.put(key,value); + _properties.put(key, value); } public void setScheme(String scheme) @@ -397,17 +398,17 @@ public class XmlConfiguredJetty // Find the active server port. _serverPort = -1; Connector connectors[] = _server.getConnectors(); - for (int i = 0; _serverPort<0 && i < connectors.length; i++) + for (int i = 0; _serverPort < 0 && i < connectors.length; i++) { if (connectors[i] instanceof NetworkConnector) { int port = ((NetworkConnector)connectors[i]).getLocalPort(); - if (port>0) - _serverPort=port; + if (port > 0) + _serverPort = port; } } - assertTrue((1 <= this._serverPort) && (this._serverPort <= 65535),"Server Port is between 1 and 65535. Was actually <" + _serverPort + ">"); + assertTrue((1 <= this._serverPort) && (this._serverPort <= 65535), "Server Port is between 1 and 65535. Was actually <" + _serverPort + ">"); // Uncomment to have server start and continue to run (without exiting) // System.err.printf("Listening to port %d%n",this.serverPort); diff --git a/jetty-distribution/pom.xml b/jetty-distribution/pom.xml index 7952ef35fd6..24a1ae4f14c 100644 --- a/jetty-distribution/pom.xml +++ b/jetty-distribution/pom.xml @@ -1,6 +1,4 @@ - + org.eclipse.jetty jetty-project diff --git a/jetty-documentation/pom.xml b/jetty-documentation/pom.xml index d6d78df52eb..c7b394c2015 100644 --- a/jetty-documentation/pom.xml +++ b/jetty-documentation/pom.xml @@ -1,11 +1,11 @@ 4.0.0 - + org.eclipse.jetty jetty-project 10.0.0-SNAPSHOT - + jetty-documentation Jetty :: Documentation pom diff --git a/jetty-fcgi/fcgi-client/pom.xml b/jetty-fcgi/fcgi-client/pom.xml index 385f6732388..9d4ec739d53 100644 --- a/jetty-fcgi/fcgi-client/pom.xml +++ b/jetty-fcgi/fcgi-client/pom.xml @@ -1,6 +1,5 @@ - + org.eclipse.jetty.fcgi fcgi-parent diff --git a/jetty-fcgi/fcgi-client/src/main/java/org/eclipse/jetty/fcgi/client/http/HttpChannelOverFCGI.java b/jetty-fcgi/fcgi-client/src/main/java/org/eclipse/jetty/fcgi/client/http/HttpChannelOverFCGI.java index dda541f1e1e..d2d3370dead 100644 --- a/jetty-fcgi/fcgi-client/src/main/java/org/eclipse/jetty/fcgi/client/http/HttpChannelOverFCGI.java +++ b/jetty-fcgi/fcgi-client/src/main/java/org/eclipse/jetty/fcgi/client/http/HttpChannelOverFCGI.java @@ -113,7 +113,7 @@ public class HttpChannelOverFCGI extends HttpChannel protected boolean responseHeaders() { - idle.notIdle(); + idle.notIdle(); HttpExchange exchange = getHttpExchange(); return exchange != null && receiver.responseHeaders(exchange); } diff --git a/jetty-fcgi/fcgi-client/src/main/java/org/eclipse/jetty/fcgi/client/http/HttpConnectionOverFCGI.java b/jetty-fcgi/fcgi-client/src/main/java/org/eclipse/jetty/fcgi/client/http/HttpConnectionOverFCGI.java index 43aa56d6d6a..3934fd007f0 100644 --- a/jetty-fcgi/fcgi-client/src/main/java/org/eclipse/jetty/fcgi/client/http/HttpConnectionOverFCGI.java +++ b/jetty-fcgi/fcgi-client/src/main/java/org/eclipse/jetty/fcgi/client/http/HttpConnectionOverFCGI.java @@ -129,7 +129,7 @@ public class HttpConnectionOverFCGI extends AbstractConnection implements IConne { @SuppressWarnings("ReferenceEquality") boolean isCurrentBuffer = (this.buffer == buffer); - assert(isCurrentBuffer); + assert (isCurrentBuffer); HttpClient client = destination.getHttpClient(); ByteBufferPool bufferPool = client.getByteBufferPool(); bufferPool.release(buffer); @@ -271,9 +271,9 @@ public class HttpConnectionOverFCGI extends AbstractConnection implements IConne channel.destroy(); } activeChannels.clear(); - + HttpChannel channel = idleChannels.poll(); - while (channel!=null) + while (channel != null) { channel.destroy(); channel = idleChannels.poll(); @@ -288,7 +288,7 @@ public class HttpConnectionOverFCGI extends AbstractConnection implements IConne result |= channel.responseFailure(failure); channel.destroy(); } - + if (result) close(failure); } @@ -335,7 +335,7 @@ public class HttpConnectionOverFCGI extends AbstractConnection implements IConne getEndPoint().getLocalAddress(), getEndPoint().getRemoteAddress()); } - + private class Delegate extends HttpConnection { private Delegate(HttpDestination destination) diff --git a/jetty-fcgi/fcgi-client/src/main/java/org/eclipse/jetty/fcgi/client/http/HttpSenderOverFCGI.java b/jetty-fcgi/fcgi-client/src/main/java/org/eclipse/jetty/fcgi/client/http/HttpSenderOverFCGI.java index 8216c6576bc..e3e65d4e431 100644 --- a/jetty-fcgi/fcgi-client/src/main/java/org/eclipse/jetty/fcgi/client/http/HttpSenderOverFCGI.java +++ b/jetty-fcgi/fcgi-client/src/main/java/org/eclipse/jetty/fcgi/client/http/HttpSenderOverFCGI.java @@ -60,7 +60,9 @@ public class HttpSenderOverFCGI extends HttpSender // Copy the request headers to be able to convert them properly HttpFields headers = new HttpFields(); for (HttpField field : request.getHeaders()) + { headers.put(field); + } HttpFields fcgiHeaders = new HttpFields(); // FastCGI headers based on the URI @@ -100,7 +102,7 @@ public class HttpSenderOverFCGI extends HttpSender int id = getHttpChannel().getRequest(); boolean hasContent = content.hasContent(); Generator.Result headersResult = generator.generateRequestHeaders(id, fcgiHeaders, - hasContent ? callback : Callback.NOOP); + hasContent ? callback : Callback.NOOP); if (hasContent) { getHttpChannel().flush(headersResult); diff --git a/jetty-fcgi/fcgi-client/src/main/java/org/eclipse/jetty/fcgi/generator/ClientGenerator.java b/jetty-fcgi/fcgi-client/src/main/java/org/eclipse/jetty/fcgi/generator/ClientGenerator.java index 2094f46528f..4d79147d467 100644 --- a/jetty-fcgi/fcgi-client/src/main/java/org/eclipse/jetty/fcgi/generator/ClientGenerator.java +++ b/jetty-fcgi/fcgi-client/src/main/java/org/eclipse/jetty/fcgi/generator/ClientGenerator.java @@ -132,7 +132,6 @@ public class ClientGenerator extends Generator BufferUtil.flipToFlush(buffer, 0); } - ByteBuffer lastParamsBuffer = byteBufferPool.acquire(8, false); BufferUtil.clearToFill(lastParamsBuffer); result = result.append(lastParamsBuffer, true); diff --git a/jetty-fcgi/fcgi-client/src/main/java/org/eclipse/jetty/fcgi/generator/Flusher.java b/jetty-fcgi/fcgi-client/src/main/java/org/eclipse/jetty/fcgi/generator/Flusher.java index ea1b3f9d137..a8006a5df55 100644 --- a/jetty-fcgi/fcgi-client/src/main/java/org/eclipse/jetty/fcgi/generator/Flusher.java +++ b/jetty-fcgi/fcgi-client/src/main/java/org/eclipse/jetty/fcgi/generator/Flusher.java @@ -43,7 +43,9 @@ public class Flusher public void flush(Generator.Result... results) { for (Generator.Result result : results) + { offer(result); + } flushCallback.iterate(); } diff --git a/jetty-fcgi/fcgi-client/src/main/java/org/eclipse/jetty/fcgi/generator/ServerGenerator.java b/jetty-fcgi/fcgi-client/src/main/java/org/eclipse/jetty/fcgi/generator/ServerGenerator.java index 53e24d6c020..25f2138b455 100644 --- a/jetty-fcgi/fcgi-client/src/main/java/org/eclipse/jetty/fcgi/generator/ServerGenerator.java +++ b/jetty-fcgi/fcgi-client/src/main/java/org/eclipse/jetty/fcgi/generator/ServerGenerator.java @@ -92,7 +92,9 @@ public class ServerGenerator extends Generator BufferUtil.clearToFill(buffer); for (int i = 0; i < bytes.size(); i += 2) + { buffer.put(bytes.get(i)).put(COLON).put(bytes.get(i + 1)).put(EOL); + } buffer.put(EOL); BufferUtil.flipToFlush(buffer, 0); diff --git a/jetty-fcgi/fcgi-client/src/main/java/org/eclipse/jetty/fcgi/parser/ClientParser.java b/jetty-fcgi/fcgi-client/src/main/java/org/eclipse/jetty/fcgi/parser/ClientParser.java index 3d2bcdf001e..94dc7e43e19 100644 --- a/jetty-fcgi/fcgi-client/src/main/java/org/eclipse/jetty/fcgi/parser/ClientParser.java +++ b/jetty-fcgi/fcgi-client/src/main/java/org/eclipse/jetty/fcgi/parser/ClientParser.java @@ -96,7 +96,9 @@ public class ClientParser extends Parser { listener.onEnd(request); for (StreamContentParser streamParser : streamParsers) + { streamParser.end(request); + } } @Override @@ -104,7 +106,9 @@ public class ClientParser extends Parser { listener.onFailure(request, failure); for (StreamContentParser streamParser : streamParsers) + { streamParser.end(request); + } } } } diff --git a/jetty-fcgi/fcgi-client/src/main/java/org/eclipse/jetty/fcgi/parser/ResponseContentParser.java b/jetty-fcgi/fcgi-client/src/main/java/org/eclipse/jetty/fcgi/parser/ResponseContentParser.java index 7269318bcac..51742bde50b 100644 --- a/jetty-fcgi/fcgi-client/src/main/java/org/eclipse/jetty/fcgi/parser/ResponseContentParser.java +++ b/jetty-fcgi/fcgi-client/src/main/java/org/eclipse/jetty/fcgi/parser/ResponseContentParser.java @@ -122,8 +122,8 @@ public class ResponseContentParser extends StreamContentParser // and will not parse it even if it is provided, // so we have to parse it raw ourselves here. boolean rawContent = fields.size() == 0 || - (fields.get(HttpHeader.CONTENT_LENGTH) == null && - fields.get(HttpHeader.TRANSFER_ENCODING) == null); + (fields.get(HttpHeader.CONTENT_LENGTH) == null && + fields.get(HttpHeader.TRANSFER_ENCODING) == null); state = rawContent ? State.RAW_CONTENT : State.HTTP_CONTENT; break; } @@ -241,7 +241,9 @@ public class ResponseContentParser extends StreamContentParser if (fields != null) { for (HttpField field : fields) + { notifyHeader(field); + } } } @@ -297,7 +299,7 @@ public class ResponseContentParser extends StreamContentParser { return false; } - + @Override public boolean messageComplete() { diff --git a/jetty-fcgi/fcgi-client/src/test/java/org/eclipse/jetty/fcgi/generator/ClientGeneratorTest.java b/jetty-fcgi/fcgi-client/src/test/java/org/eclipse/jetty/fcgi/generator/ClientGeneratorTest.java index f4abdef6958..67e6fe9761b 100644 --- a/jetty-fcgi/fcgi-client/src/test/java/org/eclipse/jetty/fcgi/generator/ClientGeneratorTest.java +++ b/jetty-fcgi/fcgi-client/src/test/java/org/eclipse/jetty/fcgi/generator/ClientGeneratorTest.java @@ -18,9 +18,6 @@ package org.eclipse.jetty.fcgi.generator; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertFalse; - import java.nio.ByteBuffer; import java.util.Arrays; import java.util.concurrent.atomic.AtomicInteger; @@ -31,9 +28,11 @@ import org.eclipse.jetty.http.HttpField; import org.eclipse.jetty.http.HttpFields; import org.eclipse.jetty.io.ByteBufferPool; import org.eclipse.jetty.io.MappedByteBufferPool; - import org.junit.jupiter.api.Test; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; + public class ClientGeneratorTest { @Test @@ -76,7 +75,9 @@ public class ClientGeneratorTest final int[] primes = new int[]{2, 3, 5, 7, 11}; int value = 1; for (int prime : primes) + { value *= prime; + } final AtomicInteger params = new AtomicInteger(1); ServerParser parser = new ServerParser(new ServerParser.Listener.Adapter() @@ -129,7 +130,9 @@ public class ClientGeneratorTest { buffer.flip(); while (buffer.hasRemaining()) + { parser.parse(ByteBuffer.wrap(new byte[]{buffer.get()})); + } assertFalse(buffer.hasRemaining()); } @@ -187,7 +190,9 @@ public class ClientGeneratorTest { buffer.flip(); while (buffer.hasRemaining()) + { parser.parse(ByteBuffer.wrap(new byte[]{buffer.get()})); + } assertFalse(buffer.hasRemaining()); } } diff --git a/jetty-fcgi/fcgi-client/src/test/java/org/eclipse/jetty/fcgi/parser/ClientParserTest.java b/jetty-fcgi/fcgi-client/src/test/java/org/eclipse/jetty/fcgi/parser/ClientParserTest.java index cd50d41679d..7e9e9dbb2b6 100644 --- a/jetty-fcgi/fcgi-client/src/test/java/org/eclipse/jetty/fcgi/parser/ClientParserTest.java +++ b/jetty-fcgi/fcgi-client/src/test/java/org/eclipse/jetty/fcgi/parser/ClientParserTest.java @@ -60,7 +60,9 @@ public class ClientParserTest final int[] primes = new int[]{2, 3, 5}; int value = 1; for (int prime : primes) + { value *= prime; + } final AtomicInteger params = new AtomicInteger(1); ClientParser parser = new ClientParser(new ClientParser.Listener.Adapter() diff --git a/jetty-fcgi/fcgi-server/src/main/java/org/eclipse/jetty/fcgi/server/HttpChannelOverFCGI.java b/jetty-fcgi/fcgi-server/src/main/java/org/eclipse/jetty/fcgi/server/HttpChannelOverFCGI.java index 1e75f083490..1ba90e21ce2 100644 --- a/jetty-fcgi/fcgi-server/src/main/java/org/eclipse/jetty/fcgi/server/HttpChannelOverFCGI.java +++ b/jetty-fcgi/fcgi-server/src/main/java/org/eclipse/jetty/fcgi/server/HttpChannelOverFCGI.java @@ -91,7 +91,7 @@ public class HttpChannelOverFCGI extends HttpChannel if (!StringUtil.isEmpty(query)) uri += "?" + query; // TODO https? - onRequest(new MetaData.Request(method, HttpScheme.HTTP.asString(), hostPort, uri, HttpVersion.fromString(version), fields,Long.MIN_VALUE)); + onRequest(new MetaData.Request(method, HttpScheme.HTTP.asString(), hostPort, uri, HttpVersion.fromString(version), fields, Long.MIN_VALUE)); } private HttpField convertHeader(HttpField field) diff --git a/jetty-fcgi/fcgi-server/src/main/java/org/eclipse/jetty/fcgi/server/HttpTransportOverFCGI.java b/jetty-fcgi/fcgi-server/src/main/java/org/eclipse/jetty/fcgi/server/HttpTransportOverFCGI.java index 817a51aa6ea..09d9b2dbb51 100644 --- a/jetty-fcgi/fcgi-server/src/main/java/org/eclipse/jetty/fcgi/server/HttpTransportOverFCGI.java +++ b/jetty-fcgi/fcgi-server/src/main/java/org/eclipse/jetty/fcgi/server/HttpTransportOverFCGI.java @@ -58,8 +58,8 @@ public class HttpTransportOverFCGI implements HttpTransport @Override public void send(MetaData.Response info, boolean head, ByteBuffer content, boolean lastContent, Callback callback) { - if (info!=null) - commit(info,head,content,lastContent,callback); + if (info != null) + commit(info, head, content, lastContent, callback); else { if (head) @@ -101,7 +101,7 @@ public class HttpTransportOverFCGI implements HttpTransport private void commit(MetaData.Response info, boolean head, ByteBuffer content, boolean lastContent, Callback callback) { if (LOG.isDebugEnabled()) - LOG.debug("commit {} {} l={}",this,info,lastContent); + LOG.debug("commit {} {} l={}", this, info, lastContent); boolean shutdown = this.shutdown = info.getFields().contains(HttpHeader.CONNECTION, HttpHeaderValue.CLOSE.asString()); if (head) @@ -143,7 +143,7 @@ public class HttpTransportOverFCGI implements HttpTransport public void abort(Throwable failure) { if (LOG.isDebugEnabled()) - LOG.debug("abort {} {}",this,failure); + LOG.debug("abort {} {}", this, failure); aborted = true; flusher.shutdown(); } diff --git a/jetty-fcgi/fcgi-server/src/main/java/org/eclipse/jetty/fcgi/server/ServerFCGIConnection.java b/jetty-fcgi/fcgi-server/src/main/java/org/eclipse/jetty/fcgi/server/ServerFCGIConnection.java index 71cefd61f02..dc9547d7119 100644 --- a/jetty-fcgi/fcgi-server/src/main/java/org/eclipse/jetty/fcgi/server/ServerFCGIConnection.java +++ b/jetty-fcgi/fcgi-server/src/main/java/org/eclipse/jetty/fcgi/server/ServerFCGIConnection.java @@ -108,7 +108,9 @@ public class ServerFCGIConnection extends AbstractConnection private void parse(ByteBuffer buffer) { while (buffer.hasRemaining()) + { parser.parse(buffer); + } } private void shutdown() @@ -123,7 +125,7 @@ public class ServerFCGIConnection extends AbstractConnection { // TODO: handle flags HttpChannelOverFCGI channel = new HttpChannelOverFCGI(connector, configuration, getEndPoint(), - new HttpTransportOverFCGI(connector.getByteBufferPool(), flusher, request, sendStatus200)); + new HttpTransportOverFCGI(connector.getByteBufferPool(), flusher, request, sendStatus200)); HttpChannelOverFCGI existing = channels.putIfAbsent(request, channel); if (existing != null) throw new IllegalStateException(); diff --git a/jetty-fcgi/fcgi-server/src/main/java/org/eclipse/jetty/fcgi/server/proxy/FastCGIProxyServlet.java b/jetty-fcgi/fcgi-server/src/main/java/org/eclipse/jetty/fcgi/server/proxy/FastCGIProxyServlet.java index 2409759da8a..4d0614de153 100644 --- a/jetty-fcgi/fcgi-server/src/main/java/org/eclipse/jetty/fcgi/server/proxy/FastCGIProxyServlet.java +++ b/jetty-fcgi/fcgi-server/src/main/java/org/eclipse/jetty/fcgi/server/proxy/FastCGIProxyServlet.java @@ -24,7 +24,6 @@ import java.util.TreeMap; import java.util.regex.Matcher; import java.util.regex.Pattern; import java.util.stream.Collectors; - import javax.servlet.RequestDispatcher; import javax.servlet.ServletConfig; import javax.servlet.ServletException; @@ -51,18 +50,18 @@ import org.eclipse.jetty.util.ProcessorUtils; *

    * This servlet accepts two additional init-params: *

      - *
    • {@code scriptRoot}, mandatory, that must be set to the directory where - * the application that must be served via FastCGI is installed and corresponds to - * the FastCGI DOCUMENT_ROOT parameter
    • - *
    • {@code scriptPattern}, optional, defaults to {@code (.+?\.php)}, - * that specifies a regular expression with at least 1 and at most 2 groups that specify - * respectively: - *
        - *
      • the FastCGI SCRIPT_NAME parameter
      • - *
      • the FastCGI PATH_INFO parameter
      • - *
    • - *
    • {@code fastCGI.HTTPS}, optional, defaults to false, that specifies whether - * to force the FastCGI {@code HTTPS} parameter to the value {@code on}
    • + *
    • {@code scriptRoot}, mandatory, that must be set to the directory where + * the application that must be served via FastCGI is installed and corresponds to + * the FastCGI DOCUMENT_ROOT parameter
    • + *
    • {@code scriptPattern}, optional, defaults to {@code (.+?\.php)}, + * that specifies a regular expression with at least 1 and at most 2 groups that specify + * respectively: + *
        + *
      • the FastCGI SCRIPT_NAME parameter
      • + *
      • the FastCGI PATH_INFO parameter
      • + *
    • + *
    • {@code fastCGI.HTTPS}, optional, defaults to false, that specifies whether + * to force the FastCGI {@code HTTPS} parameter to the value {@code on}
    • *
    * * @see TryFilesFilter @@ -112,7 +111,7 @@ public class FastCGIProxyServlet extends AsyncProxyServlet.Transparent String scriptRoot = config.getInitParameter(SCRIPT_ROOT_INIT_PARAM); if (scriptRoot == null) throw new IllegalArgumentException("Mandatory parameter '" + SCRIPT_ROOT_INIT_PARAM + "' not configured"); - int selectors = Math.max( 1, ProcessorUtils.availableProcessors() / 2); + int selectors = Math.max(1, ProcessorUtils.availableProcessors() / 2); String value = config.getInitParameter("selectors"); if (value != null) selectors = Integer.parseInt(value); @@ -257,11 +256,13 @@ public class FastCGIProxyServlet extends AsyncProxyServlet.Transparent { TreeMap fcgi = new TreeMap<>(); for (HttpField field : fastCGIHeaders) + { fcgi.put(field.getName(), field.getValue()); + } String eol = System.lineSeparator(); _log.debug("FastCGI variables{}{}", eol, fcgi.entrySet().stream() - .map(entry -> String.format("%s: %s", entry.getKey(), entry.getValue())) - .collect(Collectors.joining(eol))); + .map(entry -> String.format("%s: %s", entry.getKey(), entry.getValue())) + .collect(Collectors.joining(eol))); } } } diff --git a/jetty-fcgi/fcgi-server/src/test/java/org/eclipse/jetty/fcgi/server/AbstractHttpClientServerTest.java b/jetty-fcgi/fcgi-server/src/test/java/org/eclipse/jetty/fcgi/server/AbstractHttpClientServerTest.java index 26fbf649cdb..3a95b768888 100644 --- a/jetty-fcgi/fcgi-server/src/test/java/org/eclipse/jetty/fcgi/server/AbstractHttpClientServerTest.java +++ b/jetty-fcgi/fcgi-server/src/test/java/org/eclipse/jetty/fcgi/server/AbstractHttpClientServerTest.java @@ -56,8 +56,8 @@ public abstract class AbstractHttpClientServerTest ServerFCGIConnectionFactory fcgiConnectionFactory = new ServerFCGIConnectionFactory(new HttpConfiguration()); serverBufferPool = new LeakTrackingByteBufferPool(new MappedByteBufferPool.Tagged()); - connector = new ServerConnector( server, null, null, serverBufferPool, - 1, Math.max( 1, ProcessorUtils.availableProcessors() / 2), fcgiConnectionFactory); + connector = new ServerConnector(server, null, null, serverBufferPool, + 1, Math.max(1, ProcessorUtils.availableProcessors() / 2), fcgiConnectionFactory); // connector.setPort(9000); server.addConnector(connector); diff --git a/jetty-fcgi/fcgi-server/src/test/java/org/eclipse/jetty/fcgi/server/EmptyServerHandler.java b/jetty-fcgi/fcgi-server/src/test/java/org/eclipse/jetty/fcgi/server/EmptyServerHandler.java index 955d2ef4b83..708231649b1 100644 --- a/jetty-fcgi/fcgi-server/src/test/java/org/eclipse/jetty/fcgi/server/EmptyServerHandler.java +++ b/jetty-fcgi/fcgi-server/src/test/java/org/eclipse/jetty/fcgi/server/EmptyServerHandler.java @@ -19,7 +19,6 @@ package org.eclipse.jetty.fcgi.server; import java.io.IOException; - import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; diff --git a/jetty-fcgi/fcgi-server/src/test/java/org/eclipse/jetty/fcgi/server/ExternalFastCGIServerTest.java b/jetty-fcgi/fcgi-server/src/test/java/org/eclipse/jetty/fcgi/server/ExternalFastCGIServerTest.java index 64e53da2d3d..1aade944611 100644 --- a/jetty-fcgi/fcgi-server/src/test/java/org/eclipse/jetty/fcgi/server/ExternalFastCGIServerTest.java +++ b/jetty-fcgi/fcgi-server/src/test/java/org/eclipse/jetty/fcgi/server/ExternalFastCGIServerTest.java @@ -18,8 +18,6 @@ package org.eclipse.jetty.fcgi.server; -import static org.junit.jupiter.api.Assertions.assertEquals; - import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; @@ -32,6 +30,8 @@ import org.eclipse.jetty.fcgi.client.http.HttpClientTransportOverFCGI; import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.Test; +import static org.junit.jupiter.api.Assertions.assertEquals; + public class ExternalFastCGIServerTest { @Test @@ -44,9 +44,9 @@ public class ExternalFastCGIServerTest client.start(); ContentResponse response = client.newRequest("localhost", 9000) - .path("/index.php") - .timeout(5, TimeUnit.SECONDS) - .send(); + .path("/index.php") + .timeout(5, TimeUnit.SECONDS) + .send(); assertEquals(200, response.getStatus()); diff --git a/jetty-fcgi/fcgi-server/src/test/java/org/eclipse/jetty/fcgi/server/HttpClientTest.java b/jetty-fcgi/fcgi-server/src/test/java/org/eclipse/jetty/fcgi/server/HttpClientTest.java index a8c803a7522..8a4b959b9d4 100644 --- a/jetty-fcgi/fcgi-server/src/test/java/org/eclipse/jetty/fcgi/server/HttpClientTest.java +++ b/jetty-fcgi/fcgi-server/src/test/java/org/eclipse/jetty/fcgi/server/HttpClientTest.java @@ -179,7 +179,9 @@ public class HttpClientTest extends AbstractHttpClientServerTest ServletOutputStream output = response.getOutputStream(); String[] paramValues1 = request.getParameterValues(paramName1); for (String paramValue : paramValues1) + { output.write(paramValue.getBytes("UTF-8")); + } String paramValue2 = request.getParameter(paramName2); output.write(paramValue2.getBytes("UTF-8")); baseRequest.setHandled(true); @@ -223,9 +225,9 @@ public class HttpClientTest extends AbstractHttpClientServerTest }); ContentResponse response = client.POST(scheme + "://localhost:" + connector.getLocalPort()) - .param(paramName, paramValue) - .timeout(5, TimeUnit.SECONDS) - .send(); + .param(paramName, paramValue) + .timeout(5, TimeUnit.SECONDS) + .send(); assertNotNull(response); assertEquals(200, response.getStatus()); @@ -254,10 +256,10 @@ public class HttpClientTest extends AbstractHttpClientServerTest }); String uri = scheme + "://localhost:" + connector.getLocalPort() + - "/?" + paramName + "=" + URLEncoder.encode(paramValue, "UTF-8"); + "/?" + paramName + "=" + URLEncoder.encode(paramValue, "UTF-8"); ContentResponse response = client.POST(uri) - .timeout(5, TimeUnit.SECONDS) - .send(); + .timeout(5, TimeUnit.SECONDS) + .send(); assertNotNull(response); assertEquals(200, response.getStatus()); @@ -287,9 +289,9 @@ public class HttpClientTest extends AbstractHttpClientServerTest URI uri = URI.create(scheme + "://localhost:" + connector.getLocalPort() + "/path?" + paramName + "=" + paramValue); ContentResponse response = client.newRequest(uri) - .method(HttpMethod.PUT) - .timeout(5, TimeUnit.SECONDS) - .send(); + .method(HttpMethod.PUT) + .timeout(5, TimeUnit.SECONDS) + .send(); assertNotNull(response); assertEquals(200, response.getStatus()); @@ -321,10 +323,10 @@ public class HttpClientTest extends AbstractHttpClientServerTest for (int i = 0; i < 256; ++i) { ContentResponse response = client.POST(scheme + "://localhost:" + connector.getLocalPort() + "/?b=1") - .param(paramName, paramValue) - .content(new BytesContentProvider(content)) - .timeout(5, TimeUnit.SECONDS) - .send(); + .param(paramName, paramValue) + .content(new BytesContentProvider(content)) + .timeout(5, TimeUnit.SECONDS) + .send(); assertNotNull(response); assertEquals(200, response.getStatus()); @@ -339,16 +341,16 @@ public class HttpClientTest extends AbstractHttpClientServerTest start(new EmptyServerHandler()); ContentResponse response = client.POST(scheme + "://localhost:" + connector.getLocalPort()) - .onRequestContent((request, buffer) -> - { - byte[] bytes = new byte[buffer.remaining()]; - buffer.get(bytes); - if (!Arrays.equals(content, bytes)) - request.abort(new Exception()); - }) - .content(new BytesContentProvider(content)) - .timeout(5, TimeUnit.SECONDS) - .send(); + .onRequestContent((request, buffer) -> + { + byte[] bytes = new byte[buffer.remaining()]; + buffer.get(bytes); + if (!Arrays.equals(content, bytes)) + request.abort(new Exception()); + }) + .content(new BytesContentProvider(content)) + .timeout(5, TimeUnit.SECONDS) + .send(); assertNotNull(response); assertEquals(200, response.getStatus()); @@ -361,16 +363,18 @@ public class HttpClientTest extends AbstractHttpClientServerTest final AtomicInteger progress = new AtomicInteger(); ContentResponse response = client.POST(scheme + "://localhost:" + connector.getLocalPort()) - .onRequestContent((request, buffer) -> - { - byte[] bytes = new byte[buffer.remaining()]; - assertEquals(1, bytes.length); - buffer.get(bytes); - assertEquals(bytes[0], progress.getAndIncrement()); - }) - .content(new BytesContentProvider(new byte[]{0}, new byte[]{1}, new byte[]{2}, new byte[]{3}, new byte[]{4})) - .timeout(5, TimeUnit.SECONDS) - .send(); + .onRequestContent((request, buffer) -> + { + byte[] bytes = new byte[buffer.remaining()]; + assertEquals(1, bytes.length); + buffer.get(bytes); + assertEquals(bytes[0], progress.getAndIncrement()); + }) + .content(new BytesContentProvider(new byte[]{0}, new byte[]{1}, new byte[]{ + 2 + }, new byte[]{3}, new byte[]{4})) + .timeout(5, TimeUnit.SECONDS) + .send(); assertNotNull(response); assertEquals(200, response.getStatus()); @@ -400,9 +404,9 @@ public class HttpClientTest extends AbstractHttpClientServerTest }); ContentResponse response = client.newRequest("localhost", connector.getLocalPort()) - .scheme(scheme) - .timeout(5, TimeUnit.SECONDS) - .send(); + .scheme(scheme) + .timeout(5, TimeUnit.SECONDS) + .send(); assertEquals(200, response.getStatus()); assertArrayEquals(data, response.getContent()); @@ -433,17 +437,17 @@ public class HttpClientTest extends AbstractHttpClientServerTest final String host = "localhost"; final int port = connector.getLocalPort(); assertThrows(TimeoutException.class, () -> - client.newRequest(host, port) - .scheme(scheme) - .idleTimeout(idleTimeout, TimeUnit.MILLISECONDS) - .timeout(3 * idleTimeout, TimeUnit.MILLISECONDS) - .send()); + client.newRequest(host, port) + .scheme(scheme) + .idleTimeout(idleTimeout, TimeUnit.MILLISECONDS) + .timeout(3 * idleTimeout, TimeUnit.MILLISECONDS) + .send()); // Make another request without specifying the idle timeout, should not fail ContentResponse response = client.newRequest(host, port) - .scheme(scheme) - .timeout(3 * idleTimeout, TimeUnit.MILLISECONDS) - .send(); + .scheme(scheme) + .timeout(3 * idleTimeout, TimeUnit.MILLISECONDS) + .send(); assertNotNull(response); assertEquals(200, response.getStatus()); @@ -473,21 +477,21 @@ public class HttpClientTest extends AbstractHttpClientServerTest connector.setIdleTimeout(idleTimeout); ExecutionException x = assertThrows(ExecutionException.class, () -> - client.newRequest("localhost", connector.getLocalPort()) - .scheme(scheme) - .idleTimeout(4 * idleTimeout, TimeUnit.MILLISECONDS) - .timeout(3 * idleTimeout, TimeUnit.MILLISECONDS) - .send()); + client.newRequest("localhost", connector.getLocalPort()) + .scheme(scheme) + .idleTimeout(4 * idleTimeout, TimeUnit.MILLISECONDS) + .timeout(3 * idleTimeout, TimeUnit.MILLISECONDS) + .send()); assertThat(x.getCause(), instanceOf(EOFException.class)); connector.setIdleTimeout(5 * idleTimeout); // Make another request to be sure the connection is recreated ContentResponse response = client.newRequest("localhost", connector.getLocalPort()) - .scheme(scheme) - .idleTimeout(4 * idleTimeout, TimeUnit.MILLISECONDS) - .timeout(3 * idleTimeout, TimeUnit.MILLISECONDS) - .send(); + .scheme(scheme) + .idleTimeout(4 * idleTimeout, TimeUnit.MILLISECONDS) + .timeout(3 * idleTimeout, TimeUnit.MILLISECONDS) + .send(); assertNotNull(response); assertEquals(200, response.getStatus()); @@ -500,9 +504,9 @@ public class HttpClientTest extends AbstractHttpClientServerTest start(new EmptyServerHandler()); ContentResponse response = client.newRequest("[::1]", connector.getLocalPort()) - .scheme(scheme) - .timeout(5, TimeUnit.SECONDS) - .send(); + .scheme(scheme) + .timeout(5, TimeUnit.SECONDS) + .send(); assertNotNull(response); assertEquals(200, response.getStatus()); @@ -525,10 +529,10 @@ public class HttpClientTest extends AbstractHttpClientServerTest // HEAD requests receive a Content-Length header, but do not // receive the content so they must handle this case properly ContentResponse response = client.newRequest("localhost", connector.getLocalPort()) - .scheme(scheme) - .method(HttpMethod.HEAD) - .timeout(5, TimeUnit.SECONDS) - .send(); + .scheme(scheme) + .method(HttpMethod.HEAD) + .timeout(5, TimeUnit.SECONDS) + .send(); assertNotNull(response); assertEquals(200, response.getStatus()); @@ -536,9 +540,9 @@ public class HttpClientTest extends AbstractHttpClientServerTest // Perform a normal GET request to be sure the content is now read response = client.newRequest("localhost", connector.getLocalPort()) - .scheme(scheme) - .timeout(5, TimeUnit.SECONDS) - .send(); + .scheme(scheme) + .timeout(5, TimeUnit.SECONDS) + .send(); assertNotNull(response); assertEquals(200, response.getStatus()); @@ -562,12 +566,12 @@ public class HttpClientTest extends AbstractHttpClientServerTest final CountDownLatch completeLatch = new CountDownLatch(1); client.newRequest("localhost", connector.getLocalPort()) - .scheme(scheme) - .send(result -> - { - if (result.isFailed()) - completeLatch.countDown(); - }); + .scheme(scheme) + .send(result -> + { + if (result.isFailed()) + completeLatch.countDown(); + }); assertTrue(latch.await(5, TimeUnit.SECONDS)); @@ -596,10 +600,10 @@ public class HttpClientTest extends AbstractHttpClientServerTest try (StacklessLogging ignore = new StacklessLogging(org.eclipse.jetty.server.HttpChannel.class)) { assertThrows(ExecutionException.class, () -> - client.newRequest("localhost", connector.getLocalPort()) - .scheme(scheme) - .timeout(60, TimeUnit.SECONDS) - .send()); + client.newRequest("localhost", connector.getLocalPort()) + .scheme(scheme) + .timeout(60, TimeUnit.SECONDS) + .send()); } } @@ -632,8 +636,8 @@ public class HttpClientTest extends AbstractHttpClientServerTest DeferredContentProvider content = new DeferredContentProvider(ByteBuffer.wrap(new byte[]{0})); Request request = client.newRequest("localhost", connector.getLocalPort()) - .scheme(scheme) - .content(content); + .scheme(scheme) + .content(content); FutureResponseListener listener = new FutureResponseListener(request); request.send(listener); // Wait some time to simulate a slow request. @@ -666,14 +670,14 @@ public class HttpClientTest extends AbstractHttpClientServerTest final AtomicReference contentLatch = new AtomicReference<>(new CountDownLatch(1)); final CountDownLatch completeLatch = new CountDownLatch(1); client.newRequest("localhost", connector.getLocalPort()) - .scheme(scheme) - .onResponseContentAsync((response, content, callback) -> - { - contentCount.incrementAndGet(); - callbackRef.set(callback); - contentLatch.get().countDown(); - }) - .send(result -> completeLatch.countDown()); + .scheme(scheme) + .onResponseContentAsync((response, content, callback) -> + { + contentCount.incrementAndGet(); + callbackRef.set(callback); + contentLatch.get().countDown(); + }) + .send(result -> completeLatch.countDown()); assertTrue(contentLatch.get().await(5, TimeUnit.SECONDS)); Callback callback = callbackRef.get(); diff --git a/jetty-fcgi/fcgi-server/src/test/java/org/eclipse/jetty/fcgi/server/proxy/DrupalHTTP2FastCGIProxyServer.java b/jetty-fcgi/fcgi-server/src/test/java/org/eclipse/jetty/fcgi/server/proxy/DrupalHTTP2FastCGIProxyServer.java index 23a89cabada..9584ead7dd2 100644 --- a/jetty-fcgi/fcgi-server/src/test/java/org/eclipse/jetty/fcgi/server/proxy/DrupalHTTP2FastCGIProxyServer.java +++ b/jetty-fcgi/fcgi-server/src/test/java/org/eclipse/jetty/fcgi/server/proxy/DrupalHTTP2FastCGIProxyServer.java @@ -49,18 +49,18 @@ public class DrupalHTTP2FastCGIProxyServer HttpConfiguration config = new HttpConfiguration(); HttpConfiguration https_config = new HttpConfiguration(config); https_config.addCustomizer(new SecureRequestCustomizer()); - + // HTTP2 factory HTTP2ServerConnectionFactory h2 = new HTTP2ServerConnectionFactory(https_config); ALPNServerConnectionFactory alpn = new ALPNServerConnectionFactory(); alpn.setDefaultProtocol(h2.getProtocol()); - + // SSL Factory - SslConnectionFactory ssl = new SslConnectionFactory(sslContextFactory,alpn.getProtocol()); - + SslConnectionFactory ssl = new SslConnectionFactory(sslContextFactory, alpn.getProtocol()); + // HTTP2 Connector - ServerConnector http2Connector = - new ServerConnector(server,ssl,alpn,h2,new HttpConnectionFactory(https_config)); + ServerConnector http2Connector = + new ServerConnector(server, ssl, alpn, h2, new HttpConnectionFactory(https_config)); http2Connector.setPort(8443); http2Connector.setIdleTimeout(15000); server.addConnector(http2Connector); diff --git a/jetty-fcgi/fcgi-server/src/test/java/org/eclipse/jetty/fcgi/server/proxy/FastCGIProxyServletTest.java b/jetty-fcgi/fcgi-server/src/test/java/org/eclipse/jetty/fcgi/server/proxy/FastCGIProxyServletTest.java index 5513cbf9894..e3a93abb663 100644 --- a/jetty-fcgi/fcgi-server/src/test/java/org/eclipse/jetty/fcgi/server/proxy/FastCGIProxyServletTest.java +++ b/jetty-fcgi/fcgi-server/src/test/java/org/eclipse/jetty/fcgi/server/proxy/FastCGIProxyServletTest.java @@ -18,16 +18,10 @@ package org.eclipse.jetty.fcgi.server.proxy; -import static org.hamcrest.MatcherAssert.assertThat; -import static org.junit.jupiter.api.Assertions.assertArrayEquals; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertTrue; - import java.io.IOException; import java.util.Random; import java.util.concurrent.TimeUnit; import java.util.stream.Stream; - import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; @@ -53,13 +47,18 @@ import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.Arguments; import org.junit.jupiter.params.provider.MethodSource; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.junit.jupiter.api.Assertions.assertArrayEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + public class FastCGIProxyServletTest { public static Stream factories() { return Stream.of( - true, // send status 200 - false // don't send status 200 + true, // send status 200 + false // don't send status 200 ).map(Arguments::of); } @@ -116,21 +115,21 @@ public class FastCGIProxyServletTest server.stop(); } - @ParameterizedTest(name="[{index}] sendStatus200={0}") + @ParameterizedTest(name = "[{index}] sendStatus200={0}") @MethodSource("factories") public void testGETWithSmallResponseContent(boolean sendStatus200) throws Exception { testGETWithResponseContent(sendStatus200, 1024, 0); } - @ParameterizedTest(name="[{index}] sendStatus200={0}") + @ParameterizedTest(name = "[{index}] sendStatus200={0}") @MethodSource("factories") public void testGETWithLargeResponseContent(boolean sendStatus200) throws Exception { testGETWithResponseContent(sendStatus200, 16 * 1024 * 1024, 0); } - @ParameterizedTest(name="[{index}] sendStatus200={0}") + @ParameterizedTest(name = "[{index}] sendStatus200={0}") @MethodSource("factories") public void testGETWithLargeResponseContentWithSlowClient(boolean sendStatus200) throws Exception { @@ -155,20 +154,20 @@ public class FastCGIProxyServletTest }); Request request = client.newRequest("localhost", httpConnector.getLocalPort()) - .onResponseContentAsync((response, content, callback) -> + .onResponseContentAsync((response, content, callback) -> + { + try { - try - { - if (delay > 0) - TimeUnit.MILLISECONDS.sleep(delay); - callback.succeeded(); - } - catch (InterruptedException x) - { - callback.failed(x); - } - }) - .path(path); + if (delay > 0) + TimeUnit.MILLISECONDS.sleep(delay); + callback.succeeded(); + } + catch (InterruptedException x) + { + callback.failed(x); + } + }) + .path(path); FutureResponseListener listener = new FutureResponseListener(request, length); request.send(listener); @@ -178,7 +177,7 @@ public class FastCGIProxyServletTest assertArrayEquals(data, response.getContent()); } - @ParameterizedTest(name="[{index}] sendStatus200={0}") + @ParameterizedTest(name = "[{index}] sendStatus200={0}") @MethodSource("factories") public void testURIRewrite(boolean sendStatus200) throws Exception { @@ -217,8 +216,8 @@ public class FastCGIProxyServletTest context.start(); ContentResponse response = client.newRequest("localhost", httpConnector.getLocalPort()) - .path(remotePath) - .send(); + .path(remotePath) + .send(); assertEquals(HttpStatus.OK_200, response.getStatus()); } diff --git a/jetty-fcgi/fcgi-server/src/test/java/org/eclipse/jetty/fcgi/server/proxy/TryFilesFilterTest.java b/jetty-fcgi/fcgi-server/src/test/java/org/eclipse/jetty/fcgi/server/proxy/TryFilesFilterTest.java index e62eb00ec62..f42aaae0a6a 100644 --- a/jetty-fcgi/fcgi-server/src/test/java/org/eclipse/jetty/fcgi/server/proxy/TryFilesFilterTest.java +++ b/jetty-fcgi/fcgi-server/src/test/java/org/eclipse/jetty/fcgi/server/proxy/TryFilesFilterTest.java @@ -19,7 +19,6 @@ package org.eclipse.jetty.fcgi.server.proxy; import java.util.EnumSet; - import javax.servlet.DispatcherType; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; @@ -106,9 +105,9 @@ public class TryFilesFilterTest }); ContentResponse response = client.newRequest("localhost", sslConnector.getLocalPort()) - .scheme("https") - .path(path) - .send(); + .scheme("https") + .path(path) + .send(); assertEquals(200, response.getStatus()); } diff --git a/jetty-fcgi/fcgi-server/src/test/java/org/eclipse/jetty/fcgi/server/proxy/WordPressHTTP2FastCGIProxyServer.java b/jetty-fcgi/fcgi-server/src/test/java/org/eclipse/jetty/fcgi/server/proxy/WordPressHTTP2FastCGIProxyServer.java index c5fa6782b18..0818d1dae93 100644 --- a/jetty-fcgi/fcgi-server/src/test/java/org/eclipse/jetty/fcgi/server/proxy/WordPressHTTP2FastCGIProxyServer.java +++ b/jetty-fcgi/fcgi-server/src/test/java/org/eclipse/jetty/fcgi/server/proxy/WordPressHTTP2FastCGIProxyServer.java @@ -19,7 +19,6 @@ package org.eclipse.jetty.fcgi.server.proxy; import java.util.EnumSet; - import javax.servlet.DispatcherType; import org.eclipse.jetty.alpn.server.ALPNServerConnectionFactory; @@ -56,18 +55,18 @@ public class WordPressHTTP2FastCGIProxyServer HttpConfiguration config = new HttpConfiguration(); HttpConfiguration https_config = new HttpConfiguration(config); https_config.addCustomizer(new SecureRequestCustomizer()); - + // HTTP2 factory HTTP2ServerConnectionFactory h2 = new HTTP2ServerConnectionFactory(https_config); ALPNServerConnectionFactory alpn = new ALPNServerConnectionFactory(); alpn.setDefaultProtocol(h2.getProtocol()); - + // SSL Factory - SslConnectionFactory ssl = new SslConnectionFactory(sslContextFactory,alpn.getProtocol()); - + SslConnectionFactory ssl = new SslConnectionFactory(sslContextFactory, alpn.getProtocol()); + // HTTP2 Connector - ServerConnector http2Connector = - new ServerConnector(server,ssl,alpn,h2,new HttpConnectionFactory(https_config)); + ServerConnector http2Connector = + new ServerConnector(server, ssl, alpn, h2, new HttpConnectionFactory(https_config)); http2Connector.setPort(tlsPort); http2Connector.setIdleTimeout(15000); server.addConnector(http2Connector); diff --git a/jetty-fcgi/pom.xml b/jetty-fcgi/pom.xml index 9df08800c4e..6ea9032ffb8 100644 --- a/jetty-fcgi/pom.xml +++ b/jetty-fcgi/pom.xml @@ -1,28 +1,28 @@ - - org.eclipse.jetty - jetty-project - 10.0.0-SNAPSHOT - + + org.eclipse.jetty + jetty-project + 10.0.0-SNAPSHOT + - 4.0.0 - org.eclipse.jetty.fcgi - fcgi-parent - pom - Jetty :: FastCGI :: Parent + 4.0.0 + org.eclipse.jetty.fcgi + fcgi-parent + pom + Jetty :: FastCGI :: Parent - - fcgi-client - fcgi-server - + + fcgi-client + fcgi-server + - - - org.eclipse.jetty.toolchain - jetty-test-helper - test - - + + + org.eclipse.jetty.toolchain + jetty-test-helper + test + + diff --git a/jetty-gcloud/jetty-gcloud-session-manager/pom.xml b/jetty-gcloud/jetty-gcloud-session-manager/pom.xml index a69d29ecdb0..d4a1a89162d 100644 --- a/jetty-gcloud/jetty-gcloud-session-manager/pom.xml +++ b/jetty-gcloud/jetty-gcloud-session-manager/pom.xml @@ -1,7 +1,5 @@ - + org.eclipse.jetty.gcloud gcloud-parent @@ -143,15 +141,8 @@ - - + + @@ -164,8 +155,8 @@ - - + + diff --git a/jetty-gcloud/jetty-gcloud-session-manager/src/main/java/org/eclipse/jetty/gcloud/session/GCloudSessionDataStore.java b/jetty-gcloud/jetty-gcloud-session-manager/src/main/java/org/eclipse/jetty/gcloud/session/GCloudSessionDataStore.java index 5f304f660e9..595a6422b79 100644 --- a/jetty-gcloud/jetty-gcloud-session-manager/src/main/java/org/eclipse/jetty/gcloud/session/GCloudSessionDataStore.java +++ b/jetty-gcloud/jetty-gcloud-session-manager/src/main/java/org/eclipse/jetty/gcloud/session/GCloudSessionDataStore.java @@ -16,7 +16,6 @@ // ======================================================================== // - package org.eclipse.jetty.gcloud.session; import java.io.ByteArrayOutputStream; @@ -24,18 +23,6 @@ import java.io.ObjectOutputStream; import java.util.HashSet; import java.util.Set; -import org.eclipse.jetty.server.session.AbstractSessionDataStore; -import org.eclipse.jetty.server.session.SessionContext; -import org.eclipse.jetty.server.session.SessionData; -import org.eclipse.jetty.server.session.UnreadableSessionDataException; -import org.eclipse.jetty.server.session.UnwriteableSessionDataException; -import org.eclipse.jetty.util.ClassLoadingObjectInputStream; -import org.eclipse.jetty.util.StringUtil; -import org.eclipse.jetty.util.annotation.ManagedAttribute; -import org.eclipse.jetty.util.annotation.ManagedObject; -import org.eclipse.jetty.util.log.Log; -import org.eclipse.jetty.util.log.Logger; - import com.google.cloud.datastore.Blob; import com.google.cloud.datastore.BlobValue; import com.google.cloud.datastore.Datastore; @@ -49,17 +36,25 @@ import com.google.cloud.datastore.Query; import com.google.cloud.datastore.QueryResults; import com.google.cloud.datastore.StructuredQuery.CompositeFilter; import com.google.cloud.datastore.StructuredQuery.PropertyFilter; +import org.eclipse.jetty.server.session.AbstractSessionDataStore; +import org.eclipse.jetty.server.session.SessionContext; +import org.eclipse.jetty.server.session.SessionData; +import org.eclipse.jetty.server.session.UnreadableSessionDataException; +import org.eclipse.jetty.server.session.UnwriteableSessionDataException; +import org.eclipse.jetty.util.ClassLoadingObjectInputStream; +import org.eclipse.jetty.util.StringUtil; +import org.eclipse.jetty.util.annotation.ManagedAttribute; +import org.eclipse.jetty.util.annotation.ManagedObject; +import org.eclipse.jetty.util.log.Log; +import org.eclipse.jetty.util.log.Logger; /** * GCloudSessionDataStore - * - * */ @ManagedObject public class GCloudSessionDataStore extends AbstractSessionDataStore { - private final static Logger LOG = Log.getLogger("org.eclipse.jetty.server.session"); - + private static final Logger LOG = Log.getLogger("org.eclipse.jetty.server.session"); public static final int DEFAULT_MAX_QUERY_RESULTS = 100; public static final int DEFAULT_MAX_RETRIES = 5; @@ -76,11 +71,8 @@ public class GCloudSessionDataStore extends AbstractSessionDataStore protected EntityDataModel _model; protected boolean _modelProvided; - private String _namespace; - - - + /** * EntityDataModel * @@ -88,18 +80,18 @@ public class GCloudSessionDataStore extends AbstractSessionDataStore */ public static class EntityDataModel { - public static final String ID = "id"; - public static final String CONTEXTPATH = "contextPath"; - public static final String VHOST = "vhost"; - public static final String ACCESSED = "accessed"; - public static final String LASTACCESSED = "lastAccessed"; - public static final String CREATETIME = "createTime"; - public static final String COOKIESETTIME = "cookieSetTime"; - public static final String LASTNODE = "lastNode"; - public static final String EXPIRY = "expiry"; - public static final String MAXINACTIVE = "maxInactive"; - public static final String ATTRIBUTES = "attributes"; - public static final String LASTSAVED = "lastSaved"; + public static final String ID = "id"; + public static final String CONTEXTPATH = "contextPath"; + public static final String VHOST = "vhost"; + public static final String ACCESSED = "accessed"; + public static final String LASTACCESSED = "lastAccessed"; + public static final String CREATETIME = "createTime"; + public static final String COOKIESETTIME = "cookieSetTime"; + public static final String LASTNODE = "lastNode"; + public static final String EXPIRY = "expiry"; + public static final String MAXINACTIVE = "maxInactive"; + public static final String ATTRIBUTES = "attributes"; + public static final String LASTSAVED = "lastSaved"; public static final String KIND = "GCloudSession"; protected String _kind = KIND; @@ -115,14 +107,13 @@ public class GCloudSessionDataStore extends AbstractSessionDataStore protected String _expiry = EXPIRY; protected String _maxInactive = MAXINACTIVE; protected String _attributes = ATTRIBUTES; - - + private void checkNotNull(String s) { if (s == null) throw new IllegalArgumentException(s); } - + /** * @return the lastNode */ @@ -146,6 +137,7 @@ public class GCloudSessionDataStore extends AbstractSessionDataStore { return _kind; } + /** * @param kind the kind to set */ @@ -154,6 +146,7 @@ public class GCloudSessionDataStore extends AbstractSessionDataStore checkNotNull(kind); _kind = kind; } + /** * @return the id */ @@ -161,6 +154,7 @@ public class GCloudSessionDataStore extends AbstractSessionDataStore { return _id; } + /** * @param id the id to set */ @@ -169,6 +163,7 @@ public class GCloudSessionDataStore extends AbstractSessionDataStore checkNotNull(id); _id = id; } + /** * @return the contextPath */ @@ -176,6 +171,7 @@ public class GCloudSessionDataStore extends AbstractSessionDataStore { return _contextPath; } + /** * @param contextPath the contextPath to set */ @@ -184,6 +180,7 @@ public class GCloudSessionDataStore extends AbstractSessionDataStore checkNotNull(contextPath); _contextPath = contextPath; } + /** * @return the vhost */ @@ -191,6 +188,7 @@ public class GCloudSessionDataStore extends AbstractSessionDataStore { return _vhost; } + /** * @param vhost the vhost to set */ @@ -199,6 +197,7 @@ public class GCloudSessionDataStore extends AbstractSessionDataStore checkNotNull(vhost); _vhost = vhost; } + /** * @return the accessed */ @@ -206,6 +205,7 @@ public class GCloudSessionDataStore extends AbstractSessionDataStore { return _accessed; } + /** * @param accessed the accessed to set */ @@ -214,6 +214,7 @@ public class GCloudSessionDataStore extends AbstractSessionDataStore checkNotNull(accessed); _accessed = accessed; } + /** * @return the lastAccessed */ @@ -221,6 +222,7 @@ public class GCloudSessionDataStore extends AbstractSessionDataStore { return _lastAccessed; } + /** * @param lastAccessed the lastAccessed to set */ @@ -229,6 +231,7 @@ public class GCloudSessionDataStore extends AbstractSessionDataStore checkNotNull(lastAccessed); _lastAccessed = lastAccessed; } + /** * @return the createTime */ @@ -236,6 +239,7 @@ public class GCloudSessionDataStore extends AbstractSessionDataStore { return _createTime; } + /** * @param createTime the createTime to set */ @@ -244,6 +248,7 @@ public class GCloudSessionDataStore extends AbstractSessionDataStore checkNotNull(createTime); _createTime = createTime; } + /** * @return the cookieSetTime */ @@ -251,6 +256,7 @@ public class GCloudSessionDataStore extends AbstractSessionDataStore { return _cookieSetTime; } + /** * @param cookieSetTime the cookieSetTime to set */ @@ -259,6 +265,7 @@ public class GCloudSessionDataStore extends AbstractSessionDataStore checkNotNull(cookieSetTime); _cookieSetTime = cookieSetTime; } + /** * @return the expiry */ @@ -266,6 +273,7 @@ public class GCloudSessionDataStore extends AbstractSessionDataStore { return _expiry; } + /** * @param expiry the expiry to set */ @@ -274,6 +282,7 @@ public class GCloudSessionDataStore extends AbstractSessionDataStore checkNotNull(expiry); _expiry = expiry; } + /** * @return the maxInactive */ @@ -281,6 +290,7 @@ public class GCloudSessionDataStore extends AbstractSessionDataStore { return _maxInactive; } + /** * @param maxInactive the maxInactive to set */ @@ -289,6 +299,7 @@ public class GCloudSessionDataStore extends AbstractSessionDataStore checkNotNull(maxInactive); _maxInactive = maxInactive; } + /** * @return the attributes */ @@ -296,6 +307,7 @@ public class GCloudSessionDataStore extends AbstractSessionDataStore { return _attributes; } + /** * @param attributes the attributes to set */ @@ -322,17 +334,14 @@ public class GCloudSessionDataStore extends AbstractSessionDataStore _lastSaved = lastSaved; } - @Override public String toString() { - return String.format("%s==%s:%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s",this.getClass().getName(), - _kind,_accessed,_attributes,_contextPath,_cookieSetTime,_createTime,_expiry,_id,_lastAccessed,_lastNode,_maxInactive,_vhost); + return String.format("%s==%s:%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s", this.getClass().getName(), + _kind, _accessed, _attributes, _contextPath, _cookieSetTime, _createTime, _expiry, _id, _lastAccessed, _lastNode, _maxInactive, _vhost); } - } - - + /** * ExpiryInfo * @@ -343,13 +352,13 @@ public class GCloudSessionDataStore extends AbstractSessionDataStore String _id; String _lastNode; long _expiry; - + /** * @param id session id - * @param lastNode last node id to manage the session - * @param expiry timestamp of expiry + * @param lastNode last node id to manage the session + * @param expiry timestamp of expiry */ - public ExpiryInfo (String id, String lastNode, long expiry) + public ExpiryInfo(String id, String lastNode, long expiry) { _id = id; _lastNode = lastNode; @@ -379,59 +388,53 @@ public class GCloudSessionDataStore extends AbstractSessionDataStore { return _expiry; } - - } - + public void setEntityDataModel(EntityDataModel model) { updateBean(_model, model); _model = model; _modelProvided = true; } - - - public EntityDataModel getEntityDataModel () + + public EntityDataModel getEntityDataModel() { return _model; } - - - public void setBackoffMs (int ms) + + public void setBackoffMs(int ms) { _backoff = ms; } - - public void setNamespace (String namespace) + + public void setNamespace(String namespace) { _namespace = namespace; } - - @ManagedAttribute(value="gclound namespace", readonly=true) - public String getNamespace () + + @ManagedAttribute(value = "gclound namespace", readonly = true) + public String getNamespace() { return _namespace; } - - @ManagedAttribute(value="unit in ms of exponential backoff") - public int getBackoffMs () + + @ManagedAttribute(value = "unit in ms of exponential backoff") + public int getBackoffMs() { return _backoff; } - - - public void setMaxRetries (int retries) + + public void setMaxRetries(int retries) { _maxRetries = retries; } - - @ManagedAttribute(value="max number of retries for failed writes") - public int getMaxRetries () + + @ManagedAttribute(value = "max number of retries for failed writes") + public int getMaxRetries() { return _maxRetries; } - @Override protected void doStart() throws Exception { @@ -446,19 +449,18 @@ public class GCloudSessionDataStore extends AbstractSessionDataStore if (_model == null) { _model = new EntityDataModel(); - addBean(_model,true); + addBean(_model, true); } - _keyFactory = _datastore.newKeyFactory().setKind(_model.getKind()); - + _keyFactory = _datastore.newKeyFactory().setKind(_model.getKind()); + _indexesPresent = checkIndexes(); if (!_indexesPresent) LOG.warn("Session indexes not uploaded, falling back to less efficient queries"); - + super.doStart(); } - @Override protected void doStop() throws Exception { @@ -468,20 +470,19 @@ public class GCloudSessionDataStore extends AbstractSessionDataStore if (!_modelProvided) _model = null; } - - public void setDatastore (Datastore datastore) + + public void setDatastore(Datastore datastore) { _datastore = datastore; _dsProvided = true; } - - @ManagedAttribute(value="max number of results to return from gcloud searches") + + @ManagedAttribute(value = "max number of results to return from gcloud searches") public int getMaxResults() { return _maxResults; } - public void setMaxResults(int maxResults) { if (_maxResults <= 0) @@ -489,19 +490,20 @@ public class GCloudSessionDataStore extends AbstractSessionDataStore else _maxResults = maxResults; } - - + @Override public SessionData doLoad(String id) throws Exception { - if (LOG.isDebugEnabled()) LOG.debug("Loading session {} from DataStore", id); + if (LOG.isDebugEnabled()) + LOG.debug("Loading session {} from DataStore", id); try { Entity entity = _datastore.get(makeKey(id, _context)); if (entity == null) { - if (LOG.isDebugEnabled()) LOG.debug("No session {} in DataStore ", id); + if (LOG.isDebugEnabled()) + LOG.debug("No session {} in DataStore ", id); return null; } else @@ -515,16 +517,15 @@ public class GCloudSessionDataStore extends AbstractSessionDataStore } } - @Override public boolean delete(String id) throws Exception { - if (LOG.isDebugEnabled()) LOG.debug("Removing session {} from DataStore", id); + if (LOG.isDebugEnabled()) + LOG.debug("Removing session {} from DataStore", id); _datastore.delete(makeKey(id, _context)); return true; } - @Override public Set doGetExpired(Set candidates) { @@ -532,14 +533,14 @@ public class GCloudSessionDataStore extends AbstractSessionDataStore Set expired = new HashSet(); try - { + { Set info = null; if (_indexesPresent) info = queryExpiryByIndex(); else info = queryExpiryByEntity(); - - for (ExpiryInfo item:info) + + for (ExpiryInfo item : info) { if (StringUtil.isBlank(item.getLastNode())) { @@ -558,7 +559,8 @@ public class GCloudSessionDataStore extends AbstractSessionDataStore //our first check, just look for sessions that we managed by another node that //expired at least 3 graceperiods ago if (item.getExpiry() < (now - (1000L * (3 * _gracePeriodSec)))) - expired.add(item.getId()); } + expired.add(item.getId()); + } else { //another node was last managing it, only expire it if it expired a graceperiod ago @@ -571,22 +573,22 @@ public class GCloudSessionDataStore extends AbstractSessionDataStore //reconcile against ids that the SessionCache thinks are expired Set tmp = new HashSet(candidates); - tmp.removeAll(expired); + tmp.removeAll(expired); if (!tmp.isEmpty()) { //sessionstore thinks these are expired, but they are either no //longer in the db or not expired in the db, or we exceeded the //number of records retrieved by the expiry query, so check them //individually - for (String s:tmp) + for (String s : tmp) { try { Query q = Query.newKeyQueryBuilder() - .setKind(_model.getKind()) - .setFilter(PropertyFilter.eq(_model.getId(), s)) - .build(); - QueryResults res = _datastore.run(q); + .setKind(_model.getKind()) + .setFilter(PropertyFilter.eq(_model.getId(), s)) + .build(); + QueryResults res = _datastore.run(q); if (!res.hasNext()) expired.add(s); //not in db, can be expired } @@ -604,70 +606,70 @@ public class GCloudSessionDataStore extends AbstractSessionDataStore LOG.warn(e); return expired; //return what we got } - } - /** * A less efficient query to find sessions whose expiry time has passed: * retrieves the whole Entity. - * @return set of ExpiryInfo representing the id, lastNode and expiry time of + * + * @return set of ExpiryInfo representing the id, lastNode and expiry time of * sessions that are expired * @throws Exception if datastore experiences a problem */ - protected Set queryExpiryByEntity () throws Exception + protected Set queryExpiryByEntity() throws Exception { Set info = new HashSet<>(); //get up to maxResult number of sessions that have expired Query query = Query.newEntityQueryBuilder() - .setKind(_model.getKind()) - .setFilter(CompositeFilter.and(PropertyFilter.gt(_model.getExpiry(), 0), PropertyFilter.le(_model.getExpiry(), System.currentTimeMillis()))) - .setLimit(_maxResults) - .build(); + .setKind(_model.getKind()) + .setFilter(CompositeFilter.and(PropertyFilter.gt(_model.getExpiry(), 0), PropertyFilter.le(_model.getExpiry(), System.currentTimeMillis()))) + .setLimit(_maxResults) + .build(); QueryResults results; if (LOG.isDebugEnabled()) { long start = System.currentTimeMillis(); results = _datastore.run(query); - LOG.debug("Expiry query no index in {}ms", System.currentTimeMillis()-start); + LOG.debug("Expiry query no index in {}ms", System.currentTimeMillis() - start); } else results = _datastore.run(query); while (results.hasNext()) { Entity entity = results.next(); - info.add(new ExpiryInfo(entity.getString(_model.getId()),entity.getString(_model.getLastNode()), entity.getLong(_model.getExpiry()))); + info.add(new ExpiryInfo(entity.getString(_model.getId()), entity.getString(_model.getLastNode()), entity.getLong(_model.getExpiry()))); } return info; } - - /** An efficient query to find sessions whose expiry time has passed: + /** + * An efficient query to find sessions whose expiry time has passed: * uses a projection query, which requires indexes to be uploaded. - * @return id,lastnode and expiry time of sessions that have expired + * + * @return id, lastnode and expiry time of sessions that have expired * @throws Exception if datastore experiences a problem */ - protected Set queryExpiryByIndex () throws Exception + protected Set queryExpiryByIndex() throws Exception { long now = System.currentTimeMillis(); Set info = new HashSet<>(); Query query = Query.newProjectionEntityQueryBuilder() - .setKind(_model.getKind()) - .setProjection(_model.getId(), _model.getLastNode(), _model.getExpiry()) - .setFilter(CompositeFilter.and(PropertyFilter.gt(_model.getExpiry(), 0), PropertyFilter.le(_model.getExpiry(), now))) - .setLimit(_maxResults) - .build(); + .setKind(_model.getKind()) + .setProjection(_model.getId(), _model.getLastNode(), _model.getExpiry()) + .setFilter(CompositeFilter.and(PropertyFilter.gt(_model.getExpiry(), 0), PropertyFilter.le(_model.getExpiry(), now))) + .setLimit(_maxResults) + .build(); QueryResults presults; - + if (LOG.isDebugEnabled()) { long start = System.currentTimeMillis(); presults = _datastore.run(query); - LOG.debug("Expiry query by index in {}ms", System.currentTimeMillis()-start); + LOG.debug("Expiry query by index in {}ms", System.currentTimeMillis() - start); } else presults = _datastore.run(query); @@ -675,34 +677,32 @@ public class GCloudSessionDataStore extends AbstractSessionDataStore while (presults.hasNext()) { ProjectionEntity pe = presults.next(); - info.add(new ExpiryInfo(pe.getString(_model.getId()),pe.getString(_model.getLastNode()), pe.getLong(_model.getExpiry()))); + info.add(new ExpiryInfo(pe.getString(_model.getId()), pe.getString(_model.getLastNode()), pe.getLong(_model.getExpiry()))); } return info; } - - @Override public boolean exists(String id) throws Exception { if (_indexesPresent) { Query query = Query.newProjectionEntityQueryBuilder() - .setKind(_model.getKind()) - .setProjection(_model.getExpiry()) - .setFilter(CompositeFilter.and(PropertyFilter.eq(_model.getId(), id), - PropertyFilter.eq(_model.getContextPath(), _context.getCanonicalContextPath()), - PropertyFilter.eq(_model.getVhost(), _context.getVhost()))) - //.setFilter(PropertyFilter.eq(_model.getId(), id)) - .build(); + .setKind(_model.getKind()) + .setProjection(_model.getExpiry()) + .setFilter(CompositeFilter.and(PropertyFilter.eq(_model.getId(), id), + PropertyFilter.eq(_model.getContextPath(), _context.getCanonicalContextPath()), + PropertyFilter.eq(_model.getVhost(), _context.getVhost()))) + //.setFilter(PropertyFilter.eq(_model.getId(), id)) + .build(); QueryResults presults; if (LOG.isDebugEnabled()) { long start = System.currentTimeMillis(); presults = _datastore.run(query); - LOG.debug("Exists query by index in {}ms", System.currentTimeMillis()-start); + LOG.debug("Exists query by index in {}ms", System.currentTimeMillis() - start); } else presults = _datastore.run(query); @@ -718,23 +718,23 @@ public class GCloudSessionDataStore extends AbstractSessionDataStore else { Query query = Query.newEntityQueryBuilder() - .setKind(_model.getKind()) - .setFilter(CompositeFilter.and(PropertyFilter.eq(_model.getId(), id), - PropertyFilter.eq(_model.getContextPath(), _context.getCanonicalContextPath()), - PropertyFilter.eq(_model.getVhost(), _context.getVhost()))) - //.setFilter(PropertyFilter.eq(_model.getId(), id)) - .build(); - + .setKind(_model.getKind()) + .setFilter(CompositeFilter.and(PropertyFilter.eq(_model.getId(), id), + PropertyFilter.eq(_model.getContextPath(), _context.getCanonicalContextPath()), + PropertyFilter.eq(_model.getVhost(), _context.getVhost()))) + //.setFilter(PropertyFilter.eq(_model.getId(), id)) + .build(); + QueryResults results; if (LOG.isDebugEnabled()) { long start = System.currentTimeMillis(); results = _datastore.run(query); - LOG.debug("Exists query no index in {}ms", System.currentTimeMillis()-start); + LOG.debug("Exists query no index in {}ms", System.currentTimeMillis() - start); } else results = _datastore.run(query); - + if (results.hasNext()) { Entity entity = results.next(); @@ -744,27 +744,26 @@ public class GCloudSessionDataStore extends AbstractSessionDataStore return false; } } - - + /** * Check to see if the given time is in the past. - * + * * @param timestamp the time to check * @return false if the timestamp is 0 or less, true if it is in the past */ - protected boolean isExpired (long timestamp) + protected boolean isExpired(long timestamp) { if (timestamp <= 0) return false; - else - return timestamp < System.currentTimeMillis(); + else + return timestamp < System.currentTimeMillis(); } - @Override public void doStore(String id, SessionData data, long lastSaveTime) throws Exception { - if (LOG.isDebugEnabled()) LOG.debug("Writing session {} to DataStore", data.getId()); + if (LOG.isDebugEnabled()) + LOG.debug("Writing session {} to DataStore", data.getId()); Entity entity = entityFromSession(data, makeKey(id, _context)); //attempt the update with exponential back-off @@ -781,24 +780,25 @@ public class GCloudSessionDataStore extends AbstractSessionDataStore { if (e.isRetryable()) { - if (LOG.isDebugEnabled()) LOG.debug("Datastore put retry {} waiting {}ms", attempts, backoff); - + if (LOG.isDebugEnabled()) + LOG.debug("Datastore put retry {} waiting {}ms", attempts, backoff); + try { Thread.currentThread().sleep(backoff); } - catch (InterruptedException x) + catch (InterruptedException ignored) { } backoff *= 2; } else { - throw e; + throw e; } } } - + //retries have been exceeded throw new UnwriteableSessionDataException(id, _context, null); } @@ -812,22 +812,21 @@ public class GCloudSessionDataStore extends AbstractSessionDataStore *
  • the context path
  • *
  • the virtual hosts
  • * - * * * @param id the id * @param context the session context * @return the key */ - protected Key makeKey (String id, SessionContext context) + protected Key makeKey(String id, SessionContext context) { - String key = context.getCanonicalContextPath()+"_"+context.getVhost()+"_"+id; + String key = context.getCanonicalContextPath() + "_" + context.getVhost() + "_" + id; return _keyFactory.newKey(key); } - /** * Check to see if indexes are available, in which case * we can do more performant queries. + * * @return true if indexes are available */ protected boolean checkIndexes() @@ -835,10 +834,10 @@ public class GCloudSessionDataStore extends AbstractSessionDataStore try { Query query = Query.newProjectionEntityQueryBuilder() - .setKind(_model.getKind()) - .setProjection(_model.getExpiry()) - .setFilter(PropertyFilter.eq(_model.getId(), "-")) - .build(); + .setKind(_model.getKind()) + .setProjection(_model.getExpiry()) + .setFilter(PropertyFilter.eq(_model.getId(), "-")) + .build(); _datastore.run(query); return true; } @@ -852,22 +851,22 @@ public class GCloudSessionDataStore extends AbstractSessionDataStore return false; } } - - + /** * Generate a gcloud datastore Entity from SessionData + * * @param session the session data * @param key the key * @return the entity * @throws Exception if there is a deserialization error */ - protected Entity entityFromSession (SessionData session, Key key) throws Exception + protected Entity entityFromSession(SessionData session, Key key) throws Exception { if (session == null) return null; - + Entity entity = null; - + //serialize the attribute map try (ByteArrayOutputStream baos = new ByteArrayOutputStream(); ObjectOutputStream oos = new ObjectOutputStream(baos)) @@ -876,29 +875,30 @@ public class GCloudSessionDataStore extends AbstractSessionDataStore //turn a session into an entity entity = Entity.newBuilder(key) - .set(_model.getId(), session.getId()) - .set(_model.getContextPath(), session.getContextPath()) - .set(_model.getVhost(), session.getVhost()) - .set(_model.getAccessed(), session.getAccessed()) - .set(_model.getLastAccessed(), session.getLastAccessed()) - .set(_model.getCreateTime(), session.getCreated()) - .set(_model.getCookieSetTime(), session.getCookieSet()) - .set(_model.getLastNode(),session.getLastNode()) - .set(_model.getExpiry(), session.getExpiry()) - .set(_model.getMaxInactive(), session.getMaxInactiveMs()) - .set(_model.getLastSaved(), session.getLastSaved()) - .set(_model.getAttributes(), BlobValue.newBuilder(Blob.copyFrom(baos.toByteArray())).setExcludeFromIndexes(true).build()).build(); + .set(_model.getId(), session.getId()) + .set(_model.getContextPath(), session.getContextPath()) + .set(_model.getVhost(), session.getVhost()) + .set(_model.getAccessed(), session.getAccessed()) + .set(_model.getLastAccessed(), session.getLastAccessed()) + .set(_model.getCreateTime(), session.getCreated()) + .set(_model.getCookieSetTime(), session.getCookieSet()) + .set(_model.getLastNode(), session.getLastNode()) + .set(_model.getExpiry(), session.getExpiry()) + .set(_model.getMaxInactive(), session.getMaxInactiveMs()) + .set(_model.getLastSaved(), session.getLastSaved()) + .set(_model.getAttributes(), BlobValue.newBuilder(Blob.copyFrom(baos.toByteArray())).setExcludeFromIndexes(true).build()).build(); return entity; } } - + /** * Generate SessionData from an Entity retrieved from gcloud datastore. + * * @param entity the entity * @return the session data * @throws Exception if unable to get the entity */ - protected SessionData sessionFromEntity (Entity entity) throws Exception + protected SessionData sessionFromEntity(Entity entity) throws Exception { if (entity == null) return null; @@ -925,9 +925,9 @@ public class GCloudSessionDataStore extends AbstractSessionDataStore } long expiry = entity.getLong(_model.getExpiry()); long maxInactive = entity.getLong(_model.getMaxInactive()); - Blob blob = (Blob) entity.getBlob(_model.getAttributes()); + Blob blob = (Blob)entity.getBlob(_model.getAttributes()); - SessionData session = newSessionData (id, createTime, accessed, lastAccessed, maxInactive); + SessionData session = newSessionData(id, createTime, accessed, lastAccessed, maxInactive); session.setLastNode(lastNode); session.setContextPath(contextPath); session.setVhost(vhost); @@ -941,25 +941,21 @@ public class GCloudSessionDataStore extends AbstractSessionDataStore } catch (Exception e) { - throw new UnreadableSessionDataException (id, _context, e); + throw new UnreadableSessionDataException(id, _context, e); } return session; - } - - @ManagedAttribute(value="does gcloud serialize session data", readonly=true) + @ManagedAttribute(value = "does gcloud serialize session data", readonly = true) @Override public boolean isPassivating() { - return true; + return true; } - @Override public String toString() { - return String.format("%s[namespace=%s,backoff=%d,maxRetries=%d,maxResults=%d,indexes=%b]",super.toString(), _namespace, _backoff, _maxRetries, _maxResults,_indexesPresent); + return String.format("%s[namespace=%s,backoff=%d,maxRetries=%d,maxResults=%d,indexes=%b]", super.toString(), _namespace, _backoff, _maxRetries, _maxResults, _indexesPresent); } - } diff --git a/jetty-gcloud/jetty-gcloud-session-manager/src/main/java/org/eclipse/jetty/gcloud/session/GCloudSessionDataStoreFactory.java b/jetty-gcloud/jetty-gcloud-session-manager/src/main/java/org/eclipse/jetty/gcloud/session/GCloudSessionDataStoreFactory.java index 7c8e480d4d7..d4743b7af6d 100644 --- a/jetty-gcloud/jetty-gcloud-session-manager/src/main/java/org/eclipse/jetty/gcloud/session/GCloudSessionDataStoreFactory.java +++ b/jetty-gcloud/jetty-gcloud-session-manager/src/main/java/org/eclipse/jetty/gcloud/session/GCloudSessionDataStoreFactory.java @@ -16,7 +16,6 @@ // ======================================================================== // - package org.eclipse.jetty.gcloud.session; import org.eclipse.jetty.server.session.AbstractSessionDataStoreFactory; @@ -25,8 +24,6 @@ import org.eclipse.jetty.server.session.SessionHandler; /** * GCloudSessionDataStoreFactory - * - * */ public class GCloudSessionDataStoreFactory extends AbstractSessionDataStoreFactory { @@ -34,13 +31,12 @@ public class GCloudSessionDataStoreFactory extends AbstractSessionDataStoreFacto private int _maxRetries; private int _backoffMs; private GCloudSessionDataStore.EntityDataModel _model; - - + public GCloudSessionDataStore.EntityDataModel getEntityDataModel() { return _model; } - + public void setEntityDataModel(GCloudSessionDataStore.EntityDataModel model) { _model = model; @@ -66,7 +62,6 @@ public class GCloudSessionDataStoreFactory extends AbstractSessionDataStoreFacto _backoffMs = backoffMs; } - /** * @return the namespace */ @@ -83,7 +78,7 @@ public class GCloudSessionDataStoreFactory extends AbstractSessionDataStoreFacto _namespace = namespace; } - /** + /** * @see org.eclipse.jetty.server.session.SessionDataStoreFactory#getSessionDataStore(org.eclipse.jetty.server.session.SessionHandler) */ @Override @@ -97,5 +92,4 @@ public class GCloudSessionDataStoreFactory extends AbstractSessionDataStoreFacto ds.setSavePeriodSec(getSavePeriodSec()); return ds; } - } diff --git a/jetty-gcloud/jetty-gcloud-session-manager/src/test/java/org/eclipse/jetty/gcloud/session/GCloudSessionTester.java b/jetty-gcloud/jetty-gcloud-session-manager/src/test/java/org/eclipse/jetty/gcloud/session/GCloudSessionTester.java index d58d8bb3144..b132a76511d 100644 --- a/jetty-gcloud/jetty-gcloud-session-manager/src/test/java/org/eclipse/jetty/gcloud/session/GCloudSessionTester.java +++ b/jetty-gcloud/jetty-gcloud-session-manager/src/test/java/org/eclipse/jetty/gcloud/session/GCloudSessionTester.java @@ -18,38 +18,32 @@ package org.eclipse.jetty.gcloud.session; - - - import org.eclipse.jetty.security.HashLoginService; import org.eclipse.jetty.server.Server; import org.eclipse.jetty.server.handler.AllowSymLinkAliasChecker; -import org.eclipse.jetty.server.session.DefaultSessionIdManager; import org.eclipse.jetty.server.session.DefaultSessionCache; -import org.eclipse.jetty.server.session.SessionHandler; +import org.eclipse.jetty.server.session.DefaultSessionIdManager; import org.eclipse.jetty.webapp.WebAppContext; public class GCloudSessionTester { - public static void main( String[] args ) throws Exception + public static void main(String[] args) throws Exception { if (args.length < 4) System.err.println("Usage: GCloudSessionTester projectid p12file password serviceaccount"); - + System.setProperty("org.eclipse.jetty.server.session.LEVEL", "DEBUG"); - + Server server = new Server(8080); HashLoginService loginService = new HashLoginService(); - loginService.setName( "Test Realm" ); - loginService.setConfig( "../../jetty-distribution/target/distribution/demo-base/resources/realm.properties" ); - server.addBean( loginService ); - + loginService.setName("Test Realm"); + loginService.setConfig("../../jetty-distribution/target/distribution/demo-base/resources/realm.properties"); + server.addBean(loginService); DefaultSessionIdManager idmgr = new DefaultSessionIdManager(server); idmgr.setWorkerName("w1"); server.setSessionIdManager(idmgr); - WebAppContext webapp = new WebAppContext(); webapp.setContextPath("/"); webapp.setWar("../../jetty-distribution/target/distribution/demo-base/webapps/test.war"); @@ -68,7 +62,6 @@ public class GCloudSessionTester // Start things up! server.start(); - server.join(); } } diff --git a/jetty-hazelcast/pom.xml b/jetty-hazelcast/pom.xml index 07fe7252898..5ed59343949 100644 --- a/jetty-hazelcast/pom.xml +++ b/jetty-hazelcast/pom.xml @@ -1,6 +1,5 @@ - + org.eclipse.jetty jetty-project diff --git a/jetty-hazelcast/src/main/java/org/eclipse/jetty/hazelcast/session/HazelcastSessionDataStore.java b/jetty-hazelcast/src/main/java/org/eclipse/jetty/hazelcast/session/HazelcastSessionDataStore.java index 5b42edd4ab3..8e2d32c1906 100644 --- a/jetty-hazelcast/src/main/java/org/eclipse/jetty/hazelcast/session/HazelcastSessionDataStore.java +++ b/jetty-hazelcast/src/main/java/org/eclipse/jetty/hazelcast/session/HazelcastSessionDataStore.java @@ -46,7 +46,7 @@ public class HazelcastSessionDataStore implements SessionDataStore { - private final static Logger LOG = Log.getLogger( "org.eclipse.jetty.server.session"); + private static final Logger LOG = Log.getLogger("org.eclipse.jetty.server.session"); private IMap sessionDataMap; @@ -56,41 +56,42 @@ public class HazelcastSessionDataStore { } - /** Control whether or not to execute queries to find + /** + * Control whether or not to execute queries to find * "zombie" sessions - ie sessions that are no longer * actively referenced by any jetty instance and should * be expired. - * + * * If you use this feature, be aware that if your session * stores any attributes that use classes from within your * webapp, or from within jetty, you will need to make sure - * those classes are available to all of your hazelcast + * those classes are available to all of your hazelcast * instances, whether embedded or remote. - * + * * @param scavengeZombies true means unreferenced sessions * will be actively sought and expired. False means that they * will remain in hazelcast until some other mechanism removes them. */ - public void setScavengeZombieSessions (boolean scavengeZombies) + public void setScavengeZombieSessions(boolean scavengeZombies) { _scavengeZombies = scavengeZombies; } - + public boolean isScavengeZombies() { return _scavengeZombies; } @Override - public SessionData doLoad( String id ) - throws Exception + public SessionData doLoad(String id) + throws Exception { try { if (LOG.isDebugEnabled()) - LOG.debug( "Loading session {} from hazelcast", id ); + LOG.debug("Loading session {} from hazelcast", id); - SessionData sd = sessionDataMap.get( getCacheKey( id ) ); + SessionData sd = sessionDataMap.get(getCacheKey(id)); return sd; } catch (Exception e) @@ -99,16 +100,15 @@ public class HazelcastSessionDataStore } } - @Override - public boolean delete( String id ) + public boolean delete(String id) throws Exception { if (sessionDataMap == null) return false; - + //use delete which does not deserialize the SessionData object being removed - sessionDataMap.delete( getCacheKey(id)); + sessionDataMap.delete(getCacheKey(id)); return true; } @@ -117,13 +117,13 @@ public class HazelcastSessionDataStore return sessionDataMap; } - public void setSessionDataMap( IMap sessionDataMap ) + public void setSessionDataMap(IMap sessionDataMap) { this.sessionDataMap = sessionDataMap; } @Override - public void initialize( SessionContext context ) + public void initialize(SessionContext context) throws Exception { super.initialize(context); @@ -132,10 +132,10 @@ public class HazelcastSessionDataStore } @Override - public void doStore( String id, SessionData data, long lastSaveTime ) + public void doStore(String id, SessionData data, long lastSaveTime) throws Exception { - this.sessionDataMap.set( getCacheKey( id ), data); + this.sessionDataMap.set(getCacheKey(id), data); } @Override @@ -144,17 +144,17 @@ public class HazelcastSessionDataStore return true; } - @Override - public Set doGetExpired( Set candidates ) + public Set doGetExpired(Set candidates) { long now = System.currentTimeMillis(); - - Set expiredSessionIds = candidates.stream().filter( candidate -> { - + + Set expiredSessionIds = candidates.stream().filter(candidate -> + { + if (LOG.isDebugEnabled()) - LOG.debug( "Checking expiry for candidate {}", candidate ); - + LOG.debug("Checking expiry for candidate {}", candidate); + try { SessionData sd = load(candidate); @@ -164,7 +164,7 @@ public class HazelcastSessionDataStore { if (LOG.isDebugEnabled()) { - LOG.debug( "Session {} does not exist in Hazelcast", candidate ); + LOG.debug("Session {} does not exist in Hazelcast", candidate); } return true; } @@ -173,11 +173,11 @@ public class HazelcastSessionDataStore if (_context.getWorkerName().equals(sd.getLastNode())) { //we are its manager, add it to the expired set if it is expired now - if ((sd.getExpiry() > 0 ) && sd.getExpiry() <= now) + if ((sd.getExpiry() > 0) && sd.getExpiry() <= now) { if (LOG.isDebugEnabled()) { - LOG.debug( "Session {} managed by {} is expired", candidate, _context.getWorkerName() ); + LOG.debug("Session {} managed by {} is expired", candidate, _context.getWorkerName()); } return true; } @@ -188,16 +188,16 @@ public class HazelcastSessionDataStore // this is our first expiryCheck and the session expired a long time ago //or //the session expired at least one graceperiod ago - if (_lastExpiryCheckTime <=0) + if (_lastExpiryCheckTime <= 0) { - if ((sd.getExpiry() > 0 ) && sd.getExpiry() < (now - (1000L * (3 * _gracePeriodSec)))) + if ((sd.getExpiry() > 0) && sd.getExpiry() < (now - (1000L * (3 * _gracePeriodSec)))) { return true; } } else { - if ((sd.getExpiry() > 0 ) && sd.getExpiry() < (now - (1000L * _gracePeriodSec))) + if ((sd.getExpiry() > 0) && sd.getExpiry() < (now - (1000L * _gracePeriodSec))) { return true; } @@ -211,7 +211,7 @@ public class HazelcastSessionDataStore return true; } return false; - } ).collect( Collectors.toSet() ); + }).collect(Collectors.toSet()); if (isScavengeZombies()) { @@ -219,7 +219,7 @@ public class HazelcastSessionDataStore final AtomicReference> reference = new AtomicReference<>(); final AtomicReference exception = new AtomicReference<>(); - _context.run(()-> + _context.run(() -> { try { @@ -229,8 +229,10 @@ public class HazelcastSessionDataStore Collection results = sessionDataMap.values(predicate); if (results != null) { - for (SessionData sd: results) + for (SessionData sd : results) + { ids.add(sd.getId()); + } } reference.set(ids); } @@ -251,14 +253,13 @@ public class HazelcastSessionDataStore expiredSessionIds.addAll(reference.get()); } } - + return expiredSessionIds; } - @Override - public boolean exists( String id ) - throws Exception + public boolean exists(String id) + throws Exception { //TODO find way to do query without pulling in whole session data SessionData sd = load(id); @@ -271,7 +272,7 @@ public class HazelcastSessionDataStore return sd.getExpiry() > System.currentTimeMillis(); //not expired yet } - public String getCacheKey( String id ) + public String getCacheKey(String id) { return _context.getCanonicalContextPath() + "_" + _context.getVhost() + "_" + id; } diff --git a/jetty-hazelcast/src/main/java/org/eclipse/jetty/hazelcast/session/HazelcastSessionDataStoreFactory.java b/jetty-hazelcast/src/main/java/org/eclipse/jetty/hazelcast/session/HazelcastSessionDataStoreFactory.java index d2094251df9..d6106ce9f34 100644 --- a/jetty-hazelcast/src/main/java/org/eclipse/jetty/hazelcast/session/HazelcastSessionDataStoreFactory.java +++ b/jetty-hazelcast/src/main/java/org/eclipse/jetty/hazelcast/session/HazelcastSessionDataStoreFactory.java @@ -54,9 +54,8 @@ public class HazelcastSessionDataStoreFactory private HazelcastInstance hazelcastInstance; private MapConfig mapConfig; - - private boolean scavengeZombies = false; + private boolean scavengeZombies = false; public boolean isScavengeZombies() { @@ -69,72 +68,71 @@ public class HazelcastSessionDataStoreFactory } @Override - public SessionDataStore getSessionDataStore( SessionHandler handler ) + public SessionDataStore getSessionDataStore(SessionHandler handler) throws Exception { HazelcastSessionDataStore hazelcastSessionDataStore = new HazelcastSessionDataStore(); - if ( hazelcastInstance == null ) + if (hazelcastInstance == null) { try { - if ( onlyClient ) + if (onlyClient) { - if ( configurationLocation == null ) + if (configurationLocation == null) { ClientConfig config = new ClientConfig(); - SerializerConfig sc = new SerializerConfig(). - setImplementation(new SessionDataSerializer()). - setTypeClass(SessionData.class); + SerializerConfig sc = new SerializerConfig() + .setImplementation(new SessionDataSerializer()) + .setTypeClass(SessionData.class); config.getSerializationConfig().addSerializerConfig(sc); hazelcastInstance = HazelcastClient.newHazelcastClient(config); } else { hazelcastInstance = HazelcastClient.newHazelcastClient( - new XmlClientConfigBuilder( configurationLocation ).build() ); + new XmlClientConfigBuilder(configurationLocation).build()); } - } else { Config config; - if ( configurationLocation == null ) + if (configurationLocation == null) { - - SerializerConfig sc = new SerializerConfig(). - setImplementation(new SessionDataSerializer()). - setTypeClass(SessionData.class); + + SerializerConfig sc = new SerializerConfig() + .setImplementation(new SessionDataSerializer()) + .setTypeClass(SessionData.class); config = new Config(); config.getSerializationConfig().addSerializerConfig(sc); // configure a default Map if null - if ( mapConfig == null ) + if (mapConfig == null) { mapConfig = new MapConfig(); - mapConfig.setName( mapName ); + mapConfig.setName(mapName); } else { // otherwise we reuse the name mapName = mapConfig.getName(); } - config.addMapConfig( mapConfig ); + config.addMapConfig(mapConfig); } else { - config = new XmlConfigBuilder( configurationLocation ).build(); + config = new XmlConfigBuilder(configurationLocation).build(); } - config.setInstanceName( hazelcastInstanceName ); - hazelcastInstance = Hazelcast.getOrCreateHazelcastInstance( config ); + config.setInstanceName(hazelcastInstanceName); + hazelcastInstance = Hazelcast.getOrCreateHazelcastInstance(config); } } - catch ( IOException e ) + catch (IOException e) { - throw new RuntimeException( e.getMessage(), e ); + throw new RuntimeException(e.getMessage(), e); } } // initialize the map - hazelcastSessionDataStore.setSessionDataMap(hazelcastInstance.getMap( mapName )); + hazelcastSessionDataStore.setSessionDataMap(hazelcastInstance.getMap(mapName)); hazelcastSessionDataStore.setGracePeriodSec(getGracePeriodSec()); hazelcastSessionDataStore.setSavePeriodSec(getSavePeriodSec()); hazelcastSessionDataStore.setScavengeZombieSessions(scavengeZombies); @@ -147,11 +145,10 @@ public class HazelcastSessionDataStoreFactory } /** - * * @param onlyClient if true the session manager will only connect to an external Hazelcast instance - * and not use this JVM to start an Hazelcast instance + * and not use this JVM to start an Hazelcast instance */ - public void setOnlyClient( boolean onlyClient ) + public void setOnlyClient(boolean onlyClient) { this.onlyClient = onlyClient; } @@ -161,7 +158,7 @@ public class HazelcastSessionDataStoreFactory return configurationLocation; } - public void setConfigurationLocation( String configurationLocation ) + public void setConfigurationLocation(String configurationLocation) { this.configurationLocation = configurationLocation; } @@ -171,7 +168,7 @@ public class HazelcastSessionDataStoreFactory return mapName; } - public void setMapName( String mapName ) + public void setMapName(String mapName) { this.mapName = mapName; } @@ -181,7 +178,7 @@ public class HazelcastSessionDataStoreFactory return hazelcastInstance; } - public void setHazelcastInstance( HazelcastInstance hazelcastInstance ) + public void setHazelcastInstance(HazelcastInstance hazelcastInstance) { this.hazelcastInstance = hazelcastInstance; } @@ -191,7 +188,7 @@ public class HazelcastSessionDataStoreFactory return mapConfig; } - public void setMapConfig( MapConfig mapConfig ) + public void setMapConfig(MapConfig mapConfig) { this.mapConfig = mapConfig; } @@ -201,7 +198,7 @@ public class HazelcastSessionDataStoreFactory return hazelcastInstanceName; } - public void setHazelcastInstanceName( String hazelcastInstanceName ) + public void setHazelcastInstanceName(String hazelcastInstanceName) { this.hazelcastInstanceName = hazelcastInstanceName; } diff --git a/jetty-hazelcast/src/main/java/org/eclipse/jetty/hazelcast/session/SessionDataSerializer.java b/jetty-hazelcast/src/main/java/org/eclipse/jetty/hazelcast/session/SessionDataSerializer.java index 5179f685cf4..b4b82fb96ae 100644 --- a/jetty-hazelcast/src/main/java/org/eclipse/jetty/hazelcast/session/SessionDataSerializer.java +++ b/jetty-hazelcast/src/main/java/org/eclipse/jetty/hazelcast/session/SessionDataSerializer.java @@ -16,7 +16,6 @@ // ======================================================================== // - package org.eclipse.jetty.hazelcast.session; import java.io.ByteArrayInputStream; @@ -24,12 +23,11 @@ import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.ObjectOutputStream; -import org.eclipse.jetty.server.session.SessionData; -import org.eclipse.jetty.util.ClassLoadingObjectInputStream; - import com.hazelcast.nio.ObjectDataInput; import com.hazelcast.nio.ObjectDataOutput; import com.hazelcast.nio.serialization.StreamSerializer; +import org.eclipse.jetty.server.session.SessionData; +import org.eclipse.jetty.util.ClassLoadingObjectInputStream; /** * SessionDataSerializer @@ -40,6 +38,7 @@ import com.hazelcast.nio.serialization.StreamSerializer; public class SessionDataSerializer implements StreamSerializer { public static final int __TYPEID = 99; + @Override public int getTypeId() { @@ -63,8 +62,8 @@ public class SessionDataSerializer implements StreamSerializer out.writeLong(data.getCreated()); out.writeLong(data.getCookieSet()); out.writeUTF(data.getLastNode()); - - out.writeLong(data.getExpiry()); + + out.writeLong(data.getExpiry()); out.writeLong(data.getMaxInactiveMs()); try (ByteArrayOutputStream baos = new ByteArrayOutputStream(); @@ -77,19 +76,19 @@ public class SessionDataSerializer implements StreamSerializer @Override public SessionData read(ObjectDataInput in) throws IOException - { + { String id = in.readUTF(); String contextPath = in.readUTF(); String vhost = in.readUTF(); - + long accessed = in.readLong(); long lastAccessed = in.readLong(); long created = in.readLong(); long cookieSet = in.readLong(); String lastNode = in.readUTF(); - long expiry = in.readLong(); + long expiry = in.readLong(); long maxInactiveMs = in.readLong(); - + SessionData sd = new SessionData(id, contextPath, vhost, created, accessed, lastAccessed, maxInactiveMs); ByteArrayInputStream bais = new ByteArrayInputStream(in.readByteArray()); @@ -97,7 +96,7 @@ public class SessionDataSerializer implements StreamSerializer { SessionData.deserializeAttributes(sd, ois); } - catch(ClassNotFoundException e) + catch (ClassNotFoundException e) { throw new IOException(e); } @@ -106,5 +105,4 @@ public class SessionDataSerializer implements StreamSerializer sd.setExpiry(expiry); return sd; } - } diff --git a/jetty-hazelcast/src/test/java/org/eclipse/jetty/hazelcast/session/TestHazelcastSessions.java b/jetty-hazelcast/src/test/java/org/eclipse/jetty/hazelcast/session/TestHazelcastSessions.java index 896ccd35ace..641dd478007 100644 --- a/jetty-hazelcast/src/test/java/org/eclipse/jetty/hazelcast/session/TestHazelcastSessions.java +++ b/jetty-hazelcast/src/test/java/org/eclipse/jetty/hazelcast/session/TestHazelcastSessions.java @@ -18,7 +18,6 @@ package org.eclipse.jetty.hazelcast.session; - import java.io.IOException; import java.io.PrintWriter; import javax.servlet.ServletException; @@ -52,46 +51,45 @@ public class TestHazelcastSessions { @Override - protected void doGet( HttpServletRequest req, HttpServletResponse resp ) + protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { - String arg = req.getParameter( "action" ); - if ( arg == null ) + String arg = req.getParameter("action"); + if (arg == null) { return; } HttpSession s = null; - if ( "set".equals( arg ) ) + if ("set".equals(arg)) { - s = req.getSession( true ); - assertNotNull( s ); - s.setAttribute( "val", req.getParameter( "value" ) ); + s = req.getSession(true); + assertNotNull(s); + s.setAttribute("val", req.getParameter("value")); } - else if ( "get".equals( arg ) ) + else if ("get".equals(arg)) { - s = req.getSession( false ); - System.err.println( "GET: s=" + s + ",id=" + (s != null ? s.getId() : "" ) ); + s = req.getSession(false); + System.err.println("GET: s=" + s + ",id=" + (s != null ? s.getId() : "")); } - else if ( "del".equals( arg ) ) + else if ("del".equals(arg)) { s = req.getSession(); - assertNotNull( s ); + assertNotNull(s); s.invalidate(); s = null; } - resp.setContentType( "text/html" ); + resp.setContentType("text/html"); PrintWriter w = resp.getWriter(); - if ( s == null ) + if (s == null) { - w.write( "No session" ); + w.write("No session"); } else { - w.write( (String) s.getAttribute( "val" ) ); + w.write((String)s.getAttribute("val")); } } - } private HazelcastSessionDataStore hazelcastSessionDataStore; @@ -109,26 +107,26 @@ public class TestHazelcastSessions { server = new Server(); - serverConnector = new ServerConnector( server, new HttpConnectionFactory() ); - server.addConnector( serverConnector ); + serverConnector = new ServerConnector(server, new HttpConnectionFactory()); + server.addConnector(serverConnector); - ServletContextHandler context = new ServletContextHandler( ServletContextHandler.SESSIONS ); - context.setContextPath( contextPath ); - context.setResourceBase( System.getProperty( "java.io.tmpdir" ) ); - server.setHandler( context ); + ServletContextHandler context = new ServletContextHandler(ServletContextHandler.SESSIONS); + context.setContextPath(contextPath); + context.setResourceBase(System.getProperty("java.io.tmpdir")); + server.setHandler(context); - SessionContext sessionContext = new SessionContext( "foo", null ); + SessionContext sessionContext = new SessionContext("foo", null); hazelcastSessionDataStoreFactory = new HazelcastSessionDataStoreFactory(); - hazelcastSessionDataStore = (HazelcastSessionDataStore) hazelcastSessionDataStoreFactory.getSessionDataStore( - context.getSessionHandler() ); - hazelcastSessionDataStore.initialize( sessionContext ); + hazelcastSessionDataStore = (HazelcastSessionDataStore)hazelcastSessionDataStoreFactory.getSessionDataStore( + context.getSessionHandler()); + hazelcastSessionDataStore.initialize(sessionContext); - DefaultSessionCache defaultSessionCache = new DefaultSessionCache( context.getSessionHandler() ); - defaultSessionCache.setSessionDataStore( hazelcastSessionDataStore ); - context.getSessionHandler().setSessionCache( defaultSessionCache ); + DefaultSessionCache defaultSessionCache = new DefaultSessionCache(context.getSessionHandler()); + defaultSessionCache.setSessionDataStore(hazelcastSessionDataStore); + context.getSessionHandler().setSessionCache(defaultSessionCache); // Add a test servlet - context.addServlet( new ServletHolder( new TestServlet() ), contextPath ); + context.addServlet(new ServletHolder(new TestServlet()), contextPath); server.start(); } @@ -153,47 +151,42 @@ public class TestHazelcastSessions { int value = 42; ContentResponse response = - client.GET( "http://localhost:" + port + contextPath + "?action=set&value=" + value ); - assertEquals( HttpServletResponse.SC_OK, response.getStatus() ); - String sessionCookie = response.getHeaders().get( "Set-Cookie" ); - assertTrue( sessionCookie != null ); + client.GET("http://localhost:" + port + contextPath + "?action=set&value=" + value); + assertEquals(HttpServletResponse.SC_OK, response.getStatus()); + String sessionCookie = response.getHeaders().get("Set-Cookie"); + assertTrue(sessionCookie != null); // Mangle the cookie, replacing Path with $Path, etc. - sessionCookie = sessionCookie.replaceFirst( "(\\W)(P|p)ath=", "$1\\$Path=" ); + sessionCookie = sessionCookie.replaceFirst("(\\W)(P|p)ath=", "$1\\$Path="); String resp = response.getContentAsString(); - assertEquals( resp.trim(), String.valueOf( value ) ); + assertEquals(resp.trim(), String.valueOf(value)); // Be sure the session value is still there - Request request = client.newRequest( "http://localhost:" + port + contextPath + "?action=get" ); - request.header( "Cookie", sessionCookie ); + Request request = client.newRequest("http://localhost:" + port + contextPath + "?action=get"); + request.header("Cookie", sessionCookie); response = request.send(); - assertEquals( HttpServletResponse.SC_OK, response.getStatus() ); + assertEquals(HttpServletResponse.SC_OK, response.getStatus()); resp = response.getContentAsString(); - assertEquals( String.valueOf( value ), resp.trim() ); + assertEquals(String.valueOf(value), resp.trim()); //Delete the session - request = client.newRequest( "http://localhost:" + port + contextPath + "?action=del" ); - request.header( "Cookie", sessionCookie ); + request = client.newRequest("http://localhost:" + port + contextPath + "?action=del"); + request.header("Cookie", sessionCookie); response = request.send(); - assertEquals( HttpServletResponse.SC_OK, response.getStatus() ); + assertEquals(HttpServletResponse.SC_OK, response.getStatus()); //Check that the session is gone - request = client.newRequest( "http://localhost:" + port + contextPath + "?action=get" ); - request.header( "Cookie", sessionCookie ); + request = client.newRequest("http://localhost:" + port + contextPath + "?action=get"); + request.header("Cookie", sessionCookie); response = request.send(); - assertEquals( HttpServletResponse.SC_OK, response.getStatus() ); + assertEquals(HttpServletResponse.SC_OK, response.getStatus()); resp = response.getContentAsString(); - assertEquals( "No session", resp.trim() ); - - - + assertEquals("No session", resp.trim()); } finally { client.stop(); } - } - } diff --git a/jetty-http-spi/pom.xml b/jetty-http-spi/pom.xml index 3b96c7f85d1..2fb509cd685 100644 --- a/jetty-http-spi/pom.xml +++ b/jetty-http-spi/pom.xml @@ -22,7 +22,7 @@ jetty-client ${project.version} test - + com.sun.net.httpserver http @@ -74,14 +74,14 @@ org.apache.felix maven-bundle-plugin true - - - Jetty Http SPI - osgi.extender; filter:="(osgi.extender=osgi.serviceloader.registrar)";resolution:=optional - osgi.serviceloader; osgi.serviceloader=com.sun.net.httpserver.spi.HttpServerProvider - <_nouses>true - - + + + Jetty Http SPI + osgi.extender; filter:="(osgi.extender=osgi.serviceloader.registrar)";resolution:=optional + osgi.serviceloader; osgi.serviceloader=com.sun.net.httpserver.spi.HttpServerProvider + <_nouses>true + + org.jacoco diff --git a/jetty-http-spi/src/main/java/org/eclipse/jetty/http/spi/DelegatingThreadPool.java b/jetty-http-spi/src/main/java/org/eclipse/jetty/http/spi/DelegatingThreadPool.java index 0f8fbb08caa..9dac2add752 100644 --- a/jetty-http-spi/src/main/java/org/eclipse/jetty/http/spi/DelegatingThreadPool.java +++ b/jetty-http-spi/src/main/java/org/eclipse/jetty/http/spi/DelegatingThreadPool.java @@ -29,55 +29,50 @@ import org.eclipse.jetty.util.thread.ThreadPool; import org.eclipse.jetty.util.thread.TryExecutor; public class DelegatingThreadPool extends ContainerLifeCycle implements ThreadPool, TryExecutor -{ +{ private Executor _executor; // memory barrier provided by start/stop semantics private TryExecutor _tryExecutor; public DelegatingThreadPool(Executor executor) { - _executor=executor; - _tryExecutor=TryExecutor.asTryExecutor(executor); + _executor = executor; + _tryExecutor = TryExecutor.asTryExecutor(executor); addBean(_executor); } - /* ------------------------------------------------------------ */ public Executor getExecutor() { return _executor; } - - /* ------------------------------------------------------------ */ + public void setExecutor(Executor executor) { if (isRunning()) throw new IllegalStateException(getState()); - updateBean(_executor,executor); - _executor=executor; - _tryExecutor=TryExecutor.asTryExecutor(executor); + updateBean(_executor, executor); + _executor = executor; + _tryExecutor = TryExecutor.asTryExecutor(executor); } - - /* ------------------------------------------------------------ */ + @Override public void execute(Runnable job) { _executor.execute(job); } - /* ------------------------------------------------------------ */ @Override public boolean tryExecute(Runnable task) { return _tryExecutor.tryExecute(task); } - /* ------------------------------------------------------------ */ @Override public int getIdleThreads() { - final Executor executor=_executor; + final Executor executor = _executor; if (executor instanceof ThreadPool) return ((ThreadPool)executor).getIdleThreads(); - + if (executor instanceof ThreadPoolExecutor) { final ThreadPoolExecutor tpe = (ThreadPoolExecutor)executor; @@ -86,14 +81,13 @@ public class DelegatingThreadPool extends ContainerLifeCycle implements ThreadPo return -1; } - /* ------------------------------------------------------------ */ @Override public int getThreads() { - final Executor executor=_executor; + final Executor executor = _executor; if (executor instanceof ThreadPool) return ((ThreadPool)executor).getThreads(); - + if (executor instanceof ThreadPoolExecutor) { final ThreadPoolExecutor tpe = (ThreadPoolExecutor)executor; @@ -102,29 +96,27 @@ public class DelegatingThreadPool extends ContainerLifeCycle implements ThreadPo return -1; } - /* ------------------------------------------------------------ */ @Override public boolean isLowOnThreads() { - final Executor executor=_executor; + final Executor executor = _executor; if (executor instanceof ThreadPool) return ((ThreadPool)executor).isLowOnThreads(); - + if (executor instanceof ThreadPoolExecutor) { final ThreadPoolExecutor tpe = (ThreadPoolExecutor)executor; // getActiveCount() locks the thread pool, so execute it last return tpe.getPoolSize() == tpe.getMaximumPoolSize() && - tpe.getQueue().size() >= tpe.getPoolSize() - tpe.getActiveCount(); + tpe.getQueue().size() >= tpe.getPoolSize() - tpe.getActiveCount(); } return false; } - /* ------------------------------------------------------------ */ @Override public void join() throws InterruptedException { - final Executor executor=_executor; + final Executor executor = _executor; if (executor instanceof ThreadPool) ((ThreadPool)executor).join(); else if (executor instanceof ExecutorService) @@ -133,7 +125,6 @@ public class DelegatingThreadPool extends ContainerLifeCycle implements ThreadPo throw new IllegalStateException(); } - /* ------------------------------------------------------------ */ @Override protected void doStop() throws Exception { @@ -141,5 +132,4 @@ public class DelegatingThreadPool extends ContainerLifeCycle implements ThreadPo if (!(_executor instanceof LifeCycle) && (_executor instanceof ExecutorService)) ((ExecutorService)_executor).shutdownNow(); } - } diff --git a/jetty-http-spi/src/main/java/org/eclipse/jetty/http/spi/HttpSpiContextHandler.java b/jetty-http-spi/src/main/java/org/eclipse/jetty/http/spi/HttpSpiContextHandler.java index 7149e747775..8753e30493f 100644 --- a/jetty-http-spi/src/main/java/org/eclipse/jetty/http/spi/HttpSpiContextHandler.java +++ b/jetty-http-spi/src/main/java/org/eclipse/jetty/http/spi/HttpSpiContextHandler.java @@ -22,23 +22,21 @@ import java.io.IOException; import java.io.PrintWriter; import java.util.List; import java.util.Map; - import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; -import org.eclipse.jetty.server.Request; -import org.eclipse.jetty.server.handler.ContextHandler; -import org.eclipse.jetty.util.StringUtil; -import org.eclipse.jetty.util.log.Log; -import org.eclipse.jetty.util.log.Logger; - import com.sun.net.httpserver.Authenticator; import com.sun.net.httpserver.Authenticator.Result; import com.sun.net.httpserver.HttpContext; import com.sun.net.httpserver.HttpExchange; import com.sun.net.httpserver.HttpHandler; import com.sun.net.httpserver.HttpPrincipal; +import org.eclipse.jetty.server.Request; +import org.eclipse.jetty.server.handler.ContextHandler; +import org.eclipse.jetty.util.StringUtil; +import org.eclipse.jetty.util.log.Log; +import org.eclipse.jetty.util.log.Logger; /** * Jetty handler that bridges requests to {@link HttpHandler}. @@ -68,11 +66,11 @@ public class HttpSpiContextHandler extends ContextHandler HttpExchange jettyHttpExchange; if (baseRequest.isSecure()) { - jettyHttpExchange = new JettyHttpsExchange(_httpContext,req,resp); + jettyHttpExchange = new JettyHttpsExchange(_httpContext, req, resp); } else { - jettyHttpExchange = new JettyHttpExchange(_httpContext,req,resp); + jettyHttpExchange = new JettyHttpExchange(_httpContext, req, resp); } // TODO: add filters processing @@ -82,7 +80,7 @@ public class HttpSpiContextHandler extends ContextHandler Authenticator auth = _httpContext.getAuthenticator(); if (auth != null) { - handleAuthentication(resp,jettyHttpExchange,auth); + handleAuthentication(resp, jettyHttpExchange, auth); } else { @@ -105,8 +103,8 @@ public class HttpSpiContextHandler extends ContextHandler ex.printStackTrace(writer); writer.println(""); } - - baseRequest.getHttpChannel().getHttpConfiguration().writePoweredBy(writer,"

    ","

    "); + + baseRequest.getHttpChannel().getHttpConfiguration().writePoweredBy(writer, "

    ", "

    "); writer.close(); } @@ -114,7 +112,6 @@ public class HttpSpiContextHandler extends ContextHandler { baseRequest.setHandled(true); } - } private void handleAuthentication(HttpServletResponse resp, HttpExchange httpExchange, Authenticator auth) throws IOException @@ -123,20 +120,24 @@ public class HttpSpiContextHandler extends ContextHandler if (result instanceof Authenticator.Failure) { int rc = ((Authenticator.Failure)result).getResponseCode(); - for (Map.Entry> header : httpExchange.getResponseHeaders().entrySet()) + for (Map.Entry> header : httpExchange.getResponseHeaders().entrySet()) { for (String value : header.getValue()) - resp.addHeader(header.getKey(),value); + { + resp.addHeader(header.getKey(), value); + } } resp.sendError(rc); } else if (result instanceof Authenticator.Retry) { int rc = ((Authenticator.Retry)result).getResponseCode(); - for (Map.Entry> header : httpExchange.getResponseHeaders().entrySet()) + for (Map.Entry> header : httpExchange.getResponseHeaders().entrySet()) { for (String value : header.getValue()) - resp.addHeader(header.getKey(),value); + { + resp.addHeader(header.getKey(), value); + } } resp.setStatus(rc); resp.flushBuffer(); @@ -158,5 +159,4 @@ public class HttpSpiContextHandler extends ContextHandler { this._httpHandler = handler; } - } diff --git a/jetty-http-spi/src/main/java/org/eclipse/jetty/http/spi/JettyExchange.java b/jetty-http-spi/src/main/java/org/eclipse/jetty/http/spi/JettyExchange.java index 18085d6ef46..ecb02f41bac 100644 --- a/jetty-http-spi/src/main/java/org/eclipse/jetty/http/spi/JettyExchange.java +++ b/jetty-http-spi/src/main/java/org/eclipse/jetty/http/spi/JettyExchange.java @@ -20,8 +20,8 @@ package org.eclipse.jetty.http.spi; import com.sun.net.httpserver.HttpPrincipal; -/* ------------------------------------------------------------ */ /** + * */ public interface JettyExchange { @@ -29,5 +29,4 @@ public interface JettyExchange HttpPrincipal getPrincipal(); void setPrincipal(HttpPrincipal principal); - } diff --git a/jetty-http-spi/src/main/java/org/eclipse/jetty/http/spi/JettyHttpContext.java b/jetty-http-spi/src/main/java/org/eclipse/jetty/http/spi/JettyHttpContext.java index 7e1d56b877f..98da2cad6a4 100644 --- a/jetty-http-spi/src/main/java/org/eclipse/jetty/http/spi/JettyHttpContext.java +++ b/jetty-http-spi/src/main/java/org/eclipse/jetty/http/spi/JettyHttpContext.java @@ -37,16 +37,15 @@ public class JettyHttpContext extends com.sun.net.httpserver.HttpContext private HttpSpiContextHandler _jettyContextHandler; private HttpServer _server; - - private Map _attributes = new HashMap(); - + + private Map _attributes = new HashMap(); + private List _filters = new ArrayList(); - + private Authenticator _authenticator; - protected JettyHttpContext(HttpServer server, String path, - HttpHandler handler) + HttpHandler handler) { this._server = server; _jettyContextHandler = new HttpSpiContextHandler(this, handler); @@ -107,5 +106,4 @@ public class JettyHttpContext extends com.sun.net.httpserver.HttpContext { return _authenticator; } - } diff --git a/jetty-http-spi/src/main/java/org/eclipse/jetty/http/spi/JettyHttpExchange.java b/jetty-http-spi/src/main/java/org/eclipse/jetty/http/spi/JettyHttpExchange.java index 1c436c67264..01ab7408c42 100644 --- a/jetty-http-spi/src/main/java/org/eclipse/jetty/http/spi/JettyHttpExchange.java +++ b/jetty-http-spi/src/main/java/org/eclipse/jetty/http/spi/JettyHttpExchange.java @@ -23,7 +23,6 @@ import java.io.InputStream; import java.io.OutputStream; import java.net.InetSocketAddress; import java.net.URI; - import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; @@ -39,154 +38,132 @@ public class JettyHttpExchange extends HttpExchange implements JettyExchange public JettyHttpExchange(HttpContext jaxWsContext, HttpServletRequest req, HttpServletResponse resp) { super(); - _delegate = new JettyHttpExchangeDelegate(jaxWsContext,req,resp); + _delegate = new JettyHttpExchangeDelegate(jaxWsContext, req, resp); } - /* ------------------------------------------------------------ */ @Override public int hashCode() { return _delegate.hashCode(); } - /* ------------------------------------------------------------ */ @Override public Headers getRequestHeaders() { return _delegate.getRequestHeaders(); } - /* ------------------------------------------------------------ */ @Override public Headers getResponseHeaders() { return _delegate.getResponseHeaders(); } - /* ------------------------------------------------------------ */ @Override public URI getRequestURI() { return _delegate.getRequestURI(); } - /* ------------------------------------------------------------ */ @Override public String getRequestMethod() { return _delegate.getRequestMethod(); } - /* ------------------------------------------------------------ */ @Override public HttpContext getHttpContext() { return _delegate.getHttpContext(); } - /* ------------------------------------------------------------ */ @Override public void close() { _delegate.close(); } - /* ------------------------------------------------------------ */ @Override public boolean equals(Object obj) { return _delegate.equals(obj); } - /* ------------------------------------------------------------ */ @Override public InputStream getRequestBody() { return _delegate.getRequestBody(); } - /* ------------------------------------------------------------ */ @Override public OutputStream getResponseBody() { return _delegate.getResponseBody(); } - /* ------------------------------------------------------------ */ @Override public void sendResponseHeaders(int rCode, long responseLength) throws IOException { - _delegate.sendResponseHeaders(rCode,responseLength); + _delegate.sendResponseHeaders(rCode, responseLength); } - /* ------------------------------------------------------------ */ @Override public InetSocketAddress getRemoteAddress() { return _delegate.getRemoteAddress(); } - /* ------------------------------------------------------------ */ @Override public int getResponseCode() { return _delegate.getResponseCode(); } - /* ------------------------------------------------------------ */ @Override public InetSocketAddress getLocalAddress() { return _delegate.getLocalAddress(); } - /* ------------------------------------------------------------ */ @Override public String getProtocol() { return _delegate.getProtocol(); } - /* ------------------------------------------------------------ */ @Override public Object getAttribute(String name) { return _delegate.getAttribute(name); } - /* ------------------------------------------------------------ */ @Override public void setAttribute(String name, Object value) { - _delegate.setAttribute(name,value); + _delegate.setAttribute(name, value); } - /* ------------------------------------------------------------ */ @Override public void setStreams(InputStream i, OutputStream o) { - _delegate.setStreams(i,o); + _delegate.setStreams(i, o); } - /* ------------------------------------------------------------ */ @Override public HttpPrincipal getPrincipal() { return _delegate.getPrincipal(); } - /* ------------------------------------------------------------ */ @Override public void setPrincipal(HttpPrincipal principal) { _delegate.setPrincipal(principal); } - /* ------------------------------------------------------------ */ @Override public String toString() { return _delegate.toString(); } - } diff --git a/jetty-http-spi/src/main/java/org/eclipse/jetty/http/spi/JettyHttpExchangeDelegate.java b/jetty-http-spi/src/main/java/org/eclipse/jetty/http/spi/JettyHttpExchangeDelegate.java index 92de9c1386a..20ba1c4bcb4 100644 --- a/jetty-http-spi/src/main/java/org/eclipse/jetty/http/spi/JettyHttpExchangeDelegate.java +++ b/jetty-http-spi/src/main/java/org/eclipse/jetty/http/spi/JettyHttpExchangeDelegate.java @@ -27,7 +27,6 @@ import java.net.URISyntaxException; import java.util.Enumeration; import java.util.List; import java.util.Map; - import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; @@ -86,7 +85,7 @@ public class JettyHttpExchangeDelegate extends HttpExchange while (en2.hasMoreElements()) { String value = (String)en2.nextElement(); - headers.add(name,value); + headers.add(name, value); } } return headers; @@ -166,12 +165,12 @@ public class JettyHttpExchangeDelegate extends HttpExchange for (String value : values) { - _resp.setHeader(name,value); + _resp.setHeader(name, value); } } if (responseLength > 0) { - _resp.setHeader("content-length","" + responseLength); + _resp.setHeader("content-length", "" + responseLength); } _resp.setStatus(rCode); } @@ -179,7 +178,7 @@ public class JettyHttpExchangeDelegate extends HttpExchange @Override public InetSocketAddress getRemoteAddress() { - return new InetSocketAddress(_req.getRemoteAddr(),_req.getRemotePort()); + return new InetSocketAddress(_req.getRemoteAddr(), _req.getRemotePort()); } @Override @@ -191,7 +190,7 @@ public class JettyHttpExchangeDelegate extends HttpExchange @Override public InetSocketAddress getLocalAddress() { - return new InetSocketAddress(_req.getLocalAddr(),_req.getLocalPort()); + return new InetSocketAddress(_req.getLocalAddr(), _req.getLocalPort()); } @Override @@ -209,7 +208,7 @@ public class JettyHttpExchangeDelegate extends HttpExchange @Override public void setAttribute(String name, Object value) { - _req.setAttribute(name,value); + _req.setAttribute(name, value); } @Override @@ -229,5 +228,4 @@ public class JettyHttpExchangeDelegate extends HttpExchange { this._httpPrincipal = principal; } - } diff --git a/jetty-http-spi/src/main/java/org/eclipse/jetty/http/spi/JettyHttpServer.java b/jetty-http-spi/src/main/java/org/eclipse/jetty/http/spi/JettyHttpServer.java index 18e8fa65c65..faee5d99998 100644 --- a/jetty-http-spi/src/main/java/org/eclipse/jetty/http/spi/JettyHttpServer.java +++ b/jetty-http-spi/src/main/java/org/eclipse/jetty/http/spi/JettyHttpServer.java @@ -25,6 +25,8 @@ import java.util.HashMap; import java.util.Map; import java.util.concurrent.Executor; +import com.sun.net.httpserver.HttpContext; +import com.sun.net.httpserver.HttpHandler; import org.eclipse.jetty.server.Connector; import org.eclipse.jetty.server.Handler; import org.eclipse.jetty.server.HttpConfiguration; @@ -38,9 +40,6 @@ import org.eclipse.jetty.util.log.Log; import org.eclipse.jetty.util.log.Logger; import org.eclipse.jetty.util.thread.ThreadPool; -import com.sun.net.httpserver.HttpContext; -import com.sun.net.httpserver.HttpHandler; - /** * Jetty implementation of {@link com.sun.net.httpserver.HttpServer}. */ @@ -56,15 +55,13 @@ public class JettyHttpServer extends com.sun.net.httpserver.HttpServer private InetSocketAddress _addr; - private Map _contexts = new HashMap<>(); private Map _connectors = new HashMap<>(); - public JettyHttpServer(Server server, boolean shared) { - this(server,shared,new HttpConfiguration()); + this(server, shared, new HttpConfiguration()); } public JettyHttpServer(Server server, boolean shared, HttpConfiguration configuration) @@ -89,8 +86,10 @@ public class JettyHttpServer extends com.sun.net.httpserver.HttpServer { for (NetworkConnector connector : connectors) { - if (connector.getPort() == addr.getPort()||connector.getLocalPort() == addr.getPort()) { - if (LOG.isDebugEnabled()) LOG.debug("server already bound to port " + addr.getPort() + ", no need to rebind"); + if (connector.getPort() == addr.getPort() || connector.getLocalPort() == addr.getPort()) + { + if (LOG.isDebugEnabled()) + LOG.debug("server already bound to port " + addr.getPort() + ", no need to rebind"); return; } } @@ -99,9 +98,8 @@ public class JettyHttpServer extends com.sun.net.httpserver.HttpServer if (_serverShared) throw new IOException("jetty server is not bound to port " + addr.getPort()); - - - if (LOG.isDebugEnabled()) LOG.debug("binding server to port " + addr.getPort()); + if (LOG.isDebugEnabled()) + LOG.debug("binding server to port " + addr.getPort()); ServerConnector connector = new ServerConnector(_server); connector.setPort(addr.getPort()); connector.setHost(addr.getHostName()); @@ -116,9 +114,9 @@ public class JettyHttpServer extends com.sun.net.httpserver.HttpServer return _server; } - protected ServerConnector newServerConnector(InetSocketAddress addr,int backlog) + protected ServerConnector newServerConnector(InetSocketAddress addr, int backlog) { - ServerConnector connector = new ServerConnector(_server,new HttpConnectionFactory(_httpConfiguration)); + ServerConnector connector = new ServerConnector(_server, new HttpConnectionFactory(_httpConfiguration)); connector.setPort(addr.getPort()); connector.setHost(addr.getHostName()); return connector; @@ -127,15 +125,16 @@ public class JettyHttpServer extends com.sun.net.httpserver.HttpServer @Override public InetSocketAddress getAddress() { - if (_addr.getPort()==0 && _server.isStarted()) - return new InetSocketAddress(_addr.getHostString(),_server.getBean(NetworkConnector.class).getLocalPort()); + if (_addr.getPort() == 0 && _server.isStarted()) + return new InetSocketAddress(_addr.getHostString(), _server.getBean(NetworkConnector.class).getLocalPort()); return _addr; } @Override public void start() { - if (_serverShared) return; + if (_serverShared) + return; try { @@ -161,15 +160,17 @@ public class JettyHttpServer extends com.sun.net.httpserver.HttpServer { _server.stop(); } - ((DelegatingThreadPool) _server.getThreadPool()).setExecutor(executor); + ((DelegatingThreadPool)_server.getThreadPool()).setExecutor(executor); _server.start(); } - catch ( Exception e ) + catch (Exception e) { throw new RuntimeException(e.getMessage(), e); } - } else { - throw new UnsupportedOperationException( "!DelegatingThreadPool" ); + } + else + { + throw new UnsupportedOperationException("!DelegatingThreadPool"); } } @@ -188,7 +189,8 @@ public class JettyHttpServer extends com.sun.net.httpserver.HttpServer cleanUpContexts(); cleanUpConnectors(); - if (_serverShared) return; + if (_serverShared) + return; try { @@ -262,18 +264,20 @@ public class JettyHttpServer extends com.sun.net.httpserver.HttpServer Handler serverHandler = _server.getHandler(); if (serverHandler instanceof ContextHandler) { - ContextHandler ctx = (ContextHandler) serverHandler; + ContextHandler ctx = (ContextHandler)serverHandler; if (ctx.getContextPath().equals(path)) throw new RuntimeException("another context already bound to path " + path); } Handler[] handlers = _server.getHandlers(); - if (handlers == null) return; + if (handlers == null) + return; for (Handler handler : handlers) { - if (handler instanceof ContextHandler) { - ContextHandler ctx = (ContextHandler) handler; + if (handler instanceof ContextHandler) + { + ContextHandler ctx = (ContextHandler)handler; if (ctx.getContextPath().equals(path)) throw new RuntimeException("another context already bound to path " + path); } @@ -290,7 +294,8 @@ public class JettyHttpServer extends com.sun.net.httpserver.HttpServer public void removeContext(String path) throws IllegalArgumentException { JettyHttpContext context = _contexts.remove(path); - if (context == null) return; + if (context == null) + return; HttpSpiContextHandler handler = context.getJettyContextHandler(); ContextHandlerCollection chc = _server.getChildHandlerByClass(ContextHandlerCollection.class); @@ -310,5 +315,4 @@ public class JettyHttpServer extends com.sun.net.httpserver.HttpServer { removeContext(context.getPath()); } - } diff --git a/jetty-http-spi/src/main/java/org/eclipse/jetty/http/spi/JettyHttpServerProvider.java b/jetty-http-spi/src/main/java/org/eclipse/jetty/http/spi/JettyHttpServerProvider.java index aa36ac27ce6..6809d698577 100644 --- a/jetty-http-spi/src/main/java/org/eclipse/jetty/http/spi/JettyHttpServerProvider.java +++ b/jetty-http-spi/src/main/java/org/eclipse/jetty/http/spi/JettyHttpServerProvider.java @@ -18,6 +18,9 @@ package org.eclipse.jetty.http.spi; +import java.io.IOException; +import java.net.InetSocketAddress; + import com.sun.net.httpserver.HttpServer; import com.sun.net.httpserver.HttpsServer; import com.sun.net.httpserver.spi.HttpServerProvider; @@ -29,9 +32,6 @@ import org.eclipse.jetty.server.handler.HandlerCollection; import org.eclipse.jetty.util.thread.QueuedThreadPool; import org.eclipse.jetty.util.thread.ThreadPool; -import java.io.IOException; -import java.net.InetSocketAddress; - /** * Jetty implementation of Java HTTP Server SPI */ @@ -47,7 +47,7 @@ public class JettyHttpServerProvider extends HttpServerProvider @Override public HttpServer createHttpServer(InetSocketAddress addr, int backlog) - throws IOException + throws IOException { Server server = _server; boolean shared = true; @@ -58,7 +58,7 @@ public class JettyHttpServerProvider extends HttpServerProvider server = new Server(threadPool); HandlerCollection handlerCollection = new HandlerCollection(); - handlerCollection.setHandlers(new Handler[] {new ContextHandlerCollection(), new DefaultHandler()}); + handlerCollection.setHandlers(new Handler[]{new ContextHandlerCollection(), new DefaultHandler()}); server.setHandler(handlerCollection); shared = false; @@ -66,7 +66,7 @@ public class JettyHttpServerProvider extends HttpServerProvider JettyHttpServer jettyHttpServer = new JettyHttpServer(server, shared); if (addr != null) - jettyHttpServer.bind(addr, backlog); + jettyHttpServer.bind(addr, backlog); return jettyHttpServer; } @@ -75,5 +75,4 @@ public class JettyHttpServerProvider extends HttpServerProvider { throw new UnsupportedOperationException(); } - } diff --git a/jetty-http-spi/src/main/java/org/eclipse/jetty/http/spi/JettyHttpsExchange.java b/jetty-http-spi/src/main/java/org/eclipse/jetty/http/spi/JettyHttpsExchange.java index f67b111afe4..02e0e82498b 100644 --- a/jetty-http-spi/src/main/java/org/eclipse/jetty/http/spi/JettyHttpsExchange.java +++ b/jetty-http-spi/src/main/java/org/eclipse/jetty/http/spi/JettyHttpsExchange.java @@ -23,7 +23,6 @@ import java.io.InputStream; import java.io.OutputStream; import java.net.InetSocketAddress; import java.net.URI; - import javax.net.ssl.SSLSession; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; @@ -33,8 +32,8 @@ import com.sun.net.httpserver.HttpContext; import com.sun.net.httpserver.HttpPrincipal; import com.sun.net.httpserver.HttpsExchange; -/* ------------------------------------------------------------ */ /** + * */ public class JettyHttpsExchange extends HttpsExchange implements JettyExchange { @@ -43,7 +42,7 @@ public class JettyHttpsExchange extends HttpsExchange implements JettyExchange public JettyHttpsExchange(HttpContext jaxWsContext, HttpServletRequest req, HttpServletResponse resp) { super(); - _delegate = new JettyHttpExchangeDelegate(jaxWsContext,req,resp); + _delegate = new JettyHttpExchangeDelegate(jaxWsContext, req, resp); } @Override @@ -109,7 +108,7 @@ public class JettyHttpsExchange extends HttpsExchange implements JettyExchange @Override public void sendResponseHeaders(int rCode, long responseLength) throws IOException { - _delegate.sendResponseHeaders(rCode,responseLength); + _delegate.sendResponseHeaders(rCode, responseLength); } @Override @@ -145,13 +144,13 @@ public class JettyHttpsExchange extends HttpsExchange implements JettyExchange @Override public void setAttribute(String name, Object value) { - _delegate.setAttribute(name,value); + _delegate.setAttribute(name, value); } @Override public void setStreams(InputStream i, OutputStream o) { - _delegate.setStreams(i,o); + _delegate.setStreams(i, o); } @Override @@ -172,7 +171,6 @@ public class JettyHttpsExchange extends HttpsExchange implements JettyExchange return _delegate.toString(); } - /* ------------------------------------------------------------ */ /** * @see com.sun.net.httpserver.HttpsExchange#getSSLSession() */ @@ -181,5 +179,4 @@ public class JettyHttpsExchange extends HttpsExchange implements JettyExchange { return null; } - } diff --git a/jetty-http-spi/src/test/java/org/eclipse/jetty/http/spi/SPIServerTest.java b/jetty-http-spi/src/test/java/org/eclipse/jetty/http/spi/SPIServerTest.java index 619da3a7336..e2a8b8ece06 100644 --- a/jetty-http-spi/src/test/java/org/eclipse/jetty/http/spi/SPIServerTest.java +++ b/jetty-http-spi/src/test/java/org/eclipse/jetty/http/spi/SPIServerTest.java @@ -18,6 +18,16 @@ package org.eclipse.jetty.http.spi; +import java.io.IOException; +import java.io.OutputStream; +import java.net.Authenticator; +import java.net.HttpURLConnection; +import java.net.InetSocketAddress; +import java.net.PasswordAuthentication; +import java.net.URL; +import java.nio.charset.StandardCharsets; +import java.util.Base64; + import com.sun.net.httpserver.BasicAuthenticator; import com.sun.net.httpserver.Headers; import com.sun.net.httpserver.HttpContext; @@ -29,51 +39,41 @@ import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; -import java.io.IOException; -import java.io.OutputStream; -import java.net.Authenticator; -import java.net.HttpURLConnection; -import java.net.InetSocketAddress; -import java.net.PasswordAuthentication; -import java.net.URL; -import java.nio.charset.StandardCharsets; -import java.util.Base64; - -import static org.hamcrest.Matchers.is; import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.is; public class SPIServerTest { String host = "localhost"; HttpServer server; int port; - + @BeforeEach public void before() throws Exception { - server = new JettyHttpServerProvider().createHttpServer(new InetSocketAddress(host,0),10); - + server = new JettyHttpServerProvider().createHttpServer(new InetSocketAddress(host, 0), 10); + server.start(); port = server.getAddress().getPort(); System.err.println(port); } - + @AfterEach public void after() throws Exception { server.stop(0); } - + @Test public void testSimple() throws Exception { - server.createContext("/",new HttpHandler() + server.createContext("/", new HttpHandler() { public void handle(HttpExchange exchange) throws IOException { Headers responseHeaders = exchange.getResponseHeaders(); - responseHeaders.set("Content-Type","text/plain"); - exchange.sendResponseHeaders(200,0); + responseHeaders.set("Content-Type", "text/plain"); + exchange.sendResponseHeaders(200, 0); OutputStream responseBody = exchange.getResponseBody(); responseBody.write("Hello".getBytes(StandardCharsets.ISO_8859_1)); @@ -81,25 +81,24 @@ public class SPIServerTest } }); - URL url = new URL("http://localhost:"+port+"/"); - assertThat(IO.toString(url.openConnection().getInputStream()),is("Hello")); + URL url = new URL("http://localhost:" + port + "/"); + assertThat(IO.toString(url.openConnection().getInputStream()), is("Hello")); } @Test public void testAuth() throws Exception { - final HttpContext httpContext = server.createContext("/",new HttpHandler() + final HttpContext httpContext = server.createContext("/", new HttpHandler() { public void handle(HttpExchange exchange) throws IOException { Headers responseHeaders = exchange.getResponseHeaders(); - responseHeaders.set("Content-Type","text/plain"); - exchange.sendResponseHeaders(200,0); + responseHeaders.set("Content-Type", "text/plain"); + exchange.sendResponseHeaders(200, 0); OutputStream responseBody = exchange.getResponseBody(); responseBody.write("Hello".getBytes(StandardCharsets.ISO_8859_1)); responseBody.close(); - } }); @@ -113,27 +112,27 @@ public class SPIServerTest return false; } }); - - URL url = new URL("http://localhost:"+port+"/"); + URL url = new URL("http://localhost:" + port + "/"); HttpURLConnection client = (HttpURLConnection)url.openConnection(); client.connect(); - assertThat(client.getResponseCode(),is(401)); - - Authenticator.setDefault (new Authenticator() { - protected PasswordAuthentication getPasswordAuthentication() { - return new PasswordAuthentication ("username", "password".toCharArray()); + assertThat(client.getResponseCode(), is(401)); + + Authenticator.setDefault(new Authenticator() + { + protected PasswordAuthentication getPasswordAuthentication() + { + return new PasswordAuthentication("username", "password".toCharArray()); } }); - + client = (HttpURLConnection)url.openConnection(); String userpass = "username:password"; String basicAuth = "Basic " + Base64.getEncoder().encodeToString(userpass.getBytes(StandardCharsets.ISO_8859_1)); - client.setRequestProperty ("Authorization", basicAuth); + client.setRequestProperty("Authorization", basicAuth); client.connect(); - assertThat(client.getResponseCode(),is(200)); - assertThat(IO.toString(client.getInputStream()),is("Hello")); + assertThat(client.getResponseCode(), is(200)); + assertThat(IO.toString(client.getInputStream()), is("Hello")); } - } diff --git a/jetty-http-spi/src/test/java/org/eclipse/jetty/http/spi/TestEndpointMultiplePublishProblem.java b/jetty-http-spi/src/test/java/org/eclipse/jetty/http/spi/TestEndpointMultiplePublishProblem.java index 8cb1e1f1c0d..e488b24aa2d 100644 --- a/jetty-http-spi/src/test/java/org/eclipse/jetty/http/spi/TestEndpointMultiplePublishProblem.java +++ b/jetty-http-spi/src/test/java/org/eclipse/jetty/http/spi/TestEndpointMultiplePublishProblem.java @@ -18,6 +18,16 @@ package org.eclipse.jetty.http.spi; +import java.net.URL; +import javax.jws.WebMethod; +import javax.jws.WebService; +import javax.xml.namespace.QName; +import javax.xml.ws.BindingProvider; +import javax.xml.ws.Endpoint; +import javax.xml.ws.Service; +import javax.xml.ws.WebEndpoint; +import javax.xml.ws.WebServiceClient; + import org.eclipse.jetty.client.HttpClient; import org.eclipse.jetty.client.api.ContentResponse; import org.eclipse.jetty.server.Server; @@ -29,33 +39,23 @@ import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; -import javax.jws.WebMethod; -import javax.jws.WebService; -import javax.xml.namespace.QName; -import javax.xml.ws.BindingProvider; -import javax.xml.ws.Endpoint; -import javax.xml.ws.Service; -import javax.xml.ws.WebEndpoint; -import javax.xml.ws.WebServiceClient; -import java.net.URL; - public class TestEndpointMultiplePublishProblem { - private static String default_impl = System.getProperty( "com.sun.net.httpserver.HttpServerProvider" ); + private static String default_impl = System.getProperty("com.sun.net.httpserver.HttpServerProvider"); @BeforeAll public static void change_Impl() { - System.setProperty( "com.sun.net.httpserver.HttpServerProvider", JettyHttpServerProvider.class.getName() ); + System.setProperty("com.sun.net.httpserver.HttpServerProvider", JettyHttpServerProvider.class.getName()); } @AfterAll public static void restore_Impl() { - if ( default_impl != null ) + if (default_impl != null) { - System.setProperty( "com.sun.net.httpserver.HttpServerProvider", default_impl ); + System.setProperty("com.sun.net.httpserver.HttpServerProvider", default_impl); } } @@ -64,20 +64,20 @@ public class TestEndpointMultiplePublishProblem throws Exception { - Server jettyWebServer = new Server( new DelegatingThreadPool( new QueuedThreadPool() ) ); - ServerConnector connector = new ServerConnector( jettyWebServer ); - connector.setHost( "localhost" ); - connector.setPort( 0 ); - connector.setReuseAddress( true ); - jettyWebServer.addConnector( connector ); - jettyWebServer.setHandler( new ContextHandlerCollection() ); + Server jettyWebServer = new Server(new DelegatingThreadPool(new QueuedThreadPool())); + ServerConnector connector = new ServerConnector(jettyWebServer); + connector.setHost("localhost"); + connector.setPort(0); + connector.setReuseAddress(true); + jettyWebServer.addConnector(connector); + jettyWebServer.setHandler(new ContextHandlerCollection()); - JettyHttpServerProvider.setServer( jettyWebServer ); + JettyHttpServerProvider.setServer(jettyWebServer); jettyWebServer.start(); - Endpoint.publish( String.format( "http://%s:%d/hello", "localhost", 0 ), new WsHello() ); - Endpoint.publish( String.format( "http://%s:%d/hello2", "localhost", 0 ), new WsHello() ); + Endpoint.publish(String.format("http://%s:%d/hello", "localhost", 0), new WsHello()); + Endpoint.publish(String.format("http://%s:%d/hello2", "localhost", 0), new WsHello()); int port = connector.getLocalPort(); @@ -85,47 +85,45 @@ public class TestEndpointMultiplePublishProblem httpClient.start(); { - String url = String.format( "http://localhost:%d/hello", port ); + String url = String.format("http://localhost:%d/hello", port); String urlWsdl = url + "?wsdl"; - ContentResponse contentResponse = httpClient.newRequest( url ).send(); - Assertions.assertEquals( 200, contentResponse.getStatus() ); + ContentResponse contentResponse = httpClient.newRequest(url).send(); + Assertions.assertEquals(200, contentResponse.getStatus()); - HelloMessengerService helloMessengerService = new HelloMessengerService( new URL( urlWsdl ) ); + HelloMessengerService helloMessengerService = new HelloMessengerService(new URL(urlWsdl)); Hello hello = helloMessengerService.getHelloMessengerPort(); - ( (BindingProvider) hello ).getRequestContext().put( BindingProvider.ENDPOINT_ADDRESS_PROPERTY, url ); + ((BindingProvider)hello).getRequestContext().put(BindingProvider.ENDPOINT_ADDRESS_PROPERTY, url); String helloResponse = hello.hello(); - Assertions.assertEquals( "G'Day mate!", helloResponse ); - + Assertions.assertEquals("G'Day mate!", helloResponse); } { - String url2 = String.format( "http://localhost:%d/hello2", port ); + String url2 = String.format("http://localhost:%d/hello2", port); String url2Wsdl = url2 + "?wsdl"; - ContentResponse contentResponse = httpClient.newRequest( url2Wsdl ).send(); - Assertions.assertEquals( 200, contentResponse.getStatus() ); + ContentResponse contentResponse = httpClient.newRequest(url2Wsdl).send(); + Assertions.assertEquals(200, contentResponse.getStatus()); - HelloMessengerService helloMessengerService = new HelloMessengerService( new URL( url2Wsdl ) ); + HelloMessengerService helloMessengerService = new HelloMessengerService(new URL(url2Wsdl)); Hello hello = helloMessengerService.getHelloMessengerPort(); - ( (BindingProvider) hello ).getRequestContext().put( BindingProvider.ENDPOINT_ADDRESS_PROPERTY, url2 ); + ((BindingProvider)hello).getRequestContext().put(BindingProvider.ENDPOINT_ADDRESS_PROPERTY, url2); String helloResponse = hello.hello(); - Assertions.assertEquals( "G'Day mate!", helloResponse ); + Assertions.assertEquals("G'Day mate!", helloResponse); } httpClient.stop(); jettyWebServer.stop(); } - @WebService( targetNamespace = "http://org.eclipse.jetty.ws.test", name = "HelloService" ) + @WebService(targetNamespace = "http://org.eclipse.jetty.ws.test", name = "HelloService") public interface Hello { @WebMethod String hello(); } - - @WebService( targetNamespace = "http://org.eclipse.jetty.ws.test", name = "HelloService" ) + @WebService(targetNamespace = "http://org.eclipse.jetty.ws.test", name = "HelloService") public static class WsHello implements Hello { @@ -136,28 +134,26 @@ public class TestEndpointMultiplePublishProblem } } - - @WebServiceClient( name = "HelloService", targetNamespace = "http://org.eclipse.jetty.ws.test" ) + @WebServiceClient(name = "HelloService", targetNamespace = "http://org.eclipse.jetty.ws.test") public static class HelloMessengerService extends Service { - public HelloMessengerService( URL wsdlLocation ) + public HelloMessengerService(URL wsdlLocation) { - super( wsdlLocation, // - new QName( "http://org.eclipse.jetty.ws.test", "WsHelloService" ) ); + super(wsdlLocation, // + new QName("http://org.eclipse.jetty.ws.test", "WsHelloService")); } - @WebEndpoint( name = "HelloServicePort" ) + @WebEndpoint(name = "HelloServicePort") public Hello getHelloMessengerPort() { - return super.getPort( new QName( "http://org.eclipse.jetty.ws.test", "HelloServicePort" ), // - Hello.class ); + return super.getPort(new QName("http://org.eclipse.jetty.ws.test", "HelloServicePort"), // + Hello.class); } } - - private void assertWsdl( String wsdl ) + private void assertWsdl(String wsdl) throws Exception { diff --git a/jetty-http-spi/src/test/java/org/eclipse/jetty/http/spi/TestSPIServer.java b/jetty-http-spi/src/test/java/org/eclipse/jetty/http/spi/TestSPIServer.java index 89168cf770a..1b44817bd46 100644 --- a/jetty-http-spi/src/test/java/org/eclipse/jetty/http/spi/TestSPIServer.java +++ b/jetty-http-spi/src/test/java/org/eclipse/jetty/http/spi/TestSPIServer.java @@ -18,46 +18,34 @@ package org.eclipse.jetty.http.spi; +import java.io.OutputStream; +import java.net.InetSocketAddress; +import java.net.URI; +import java.util.Iterator; +import java.util.List; +import java.util.Set; +import javax.servlet.http.HttpServletResponse; + +import com.sun.net.httpserver.BasicAuthenticator; +import com.sun.net.httpserver.Headers; +import com.sun.net.httpserver.HttpContext; +import com.sun.net.httpserver.HttpServer; import org.eclipse.jetty.client.HttpClient; import org.eclipse.jetty.client.api.ContentResponse; import org.eclipse.jetty.client.api.Request; import org.eclipse.jetty.client.util.BasicAuthentication; import org.eclipse.jetty.server.NetworkConnector; import org.eclipse.jetty.server.Server; +import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertEquals; -import java.io.IOException; -import java.io.OutputStream; -import java.net.InetAddress; -import java.net.InetSocketAddress; -import java.net.URI; -import java.util.Iterator; -import java.util.List; -import java.util.Set; - -import javax.servlet.http.HttpServletResponse; - -import com.sun.net.httpserver.BasicAuthenticator; -import com.sun.net.httpserver.Headers; -import com.sun.net.httpserver.HttpContext; -import com.sun.net.httpserver.HttpExchange; -import com.sun.net.httpserver.HttpHandler; -import com.sun.net.httpserver.HttpServer; - -import org.junit.jupiter.api.Test; - - - - public class TestSPIServer { - + /** * Create a server that has a null InetSocketAddress, then * bind before using. - * - * @throws Exception */ @Test public void testUnboundHttpServer() throws Exception @@ -71,10 +59,11 @@ public class TestSPIServer server = new JettyHttpServerProvider().createHttpServer(null, 10); final HttpContext httpContext = server.createContext("/", - exchange -> { + exchange -> + { Headers responseHeaders = exchange.getResponseHeaders(); - responseHeaders.set("Content-Type","text/plain"); - exchange.sendResponseHeaders(200,0); + responseHeaders.set("Content-Type", "text/plain"); + exchange.sendResponseHeaders(200, 0); OutputStream responseBody = exchange.getResponseBody(); Headers requestHeaders = exchange.getRequestHeaders(); @@ -88,7 +77,7 @@ public class TestSPIServer responseBody.write(s.getBytes()); } responseBody.close(); - }); + }); httpContext.setAuthenticator(new BasicAuthenticator("Test") { @@ -105,23 +94,23 @@ public class TestSPIServer //address to bind so this test isn't port-specific //and thus is portable and can be run concurrently on CI //environments - server.bind(new InetSocketAddress("localhost", 0), 10); - + server.bind(new InetSocketAddress("localhost", 0), 10); + server.start(); //find out the port jetty picked Server jetty = ((JettyHttpServer)server).getServer(); - int port = ((NetworkConnector)jetty.getConnectors()[0]).getLocalPort(); - + int port = ((NetworkConnector)jetty.getConnectors()[0]).getLocalPort(); + HttpClient client = new HttpClient(); client.start(); try { Request request = client.newRequest("http://localhost:" + port + "/"); - client.getAuthenticationStore().addAuthentication(new BasicAuthentication(URI.create("http://localhost:"+port), "Test", "username", "password")); + client.getAuthenticationStore().addAuthentication(new BasicAuthentication(URI.create("http://localhost:" + port), "Test", "username", "password")); ContentResponse response = request.send(); - assertEquals(HttpServletResponse.SC_OK,response.getStatus()); + assertEquals(HttpServletResponse.SC_OK, response.getStatus()); } finally { @@ -137,11 +126,10 @@ public class TestSPIServer /** * Test using a server that is created with a given InetSocketAddress - * @throws Exception */ @Test public void testBoundHttpServer() throws Exception - { + { HttpServer server = null; @@ -151,13 +139,14 @@ public class TestSPIServer //jetty to pick a free port. Ensures test is not tied to specific port number //for test portability and concurrency. server = new JettyHttpServerProvider().createHttpServer(new - InetSocketAddress("localhost", 0), 10); + InetSocketAddress("localhost", 0), 10); final HttpContext httpContext = server.createContext("/", - exchange -> { + exchange -> + { Headers responseHeaders = exchange.getResponseHeaders(); - responseHeaders.set("Content-Type","text/plain"); - exchange.sendResponseHeaders(200,0); + responseHeaders.set("Content-Type", "text/plain"); + exchange.sendResponseHeaders(200, 0); OutputStream responseBody = exchange.getResponseBody(); Headers requestHeaders = exchange.getRequestHeaders(); @@ -171,7 +160,7 @@ public class TestSPIServer responseBody.write(s.getBytes()); } responseBody.close(); - }); + }); httpContext.setAuthenticator(new BasicAuthenticator("Test") { @@ -188,7 +177,7 @@ public class TestSPIServer //find out the port jetty picked Server jetty = ((JettyHttpServer)server).getServer(); - int port = ((NetworkConnector)jetty.getConnectors()[0]).getLocalPort(); + int port = ((NetworkConnector)jetty.getConnectors()[0]).getLocalPort(); HttpClient client = new HttpClient(); client.start(); @@ -196,9 +185,9 @@ public class TestSPIServer try { Request request = client.newRequest("http://localhost:" + port + "/"); - client.getAuthenticationStore().addAuthentication(new BasicAuthentication(URI.create("http://localhost:"+port), "Test", "username", "password")); + client.getAuthenticationStore().addAuthentication(new BasicAuthentication(URI.create("http://localhost:" + port), "Test", "username", "password")); ContentResponse response = request.send(); - assertEquals(HttpServletResponse.SC_OK,response.getStatus()); + assertEquals(HttpServletResponse.SC_OK, response.getStatus()); } finally { diff --git a/jetty-http-spi/src/test/java/org/eclipse/jetty/http/spi/util/Pool.java b/jetty-http-spi/src/test/java/org/eclipse/jetty/http/spi/util/Pool.java index 3363cc8b94e..ea5e6335813 100644 --- a/jetty-http-spi/src/test/java/org/eclipse/jetty/http/spi/util/Pool.java +++ b/jetty-http-spi/src/test/java/org/eclipse/jetty/http/spi/util/Pool.java @@ -20,7 +20,6 @@ package org.eclipse.jetty.http.spi.util; /** * This class holds the default pool constants - * */ public enum Pool { diff --git a/jetty-http-spi/src/test/java/org/eclipse/jetty/http/spi/util/PrintTask.java b/jetty-http-spi/src/test/java/org/eclipse/jetty/http/spi/util/PrintTask.java index d96dae43b80..e9a3a9e7dc6 100644 --- a/jetty-http-spi/src/test/java/org/eclipse/jetty/http/spi/util/PrintTask.java +++ b/jetty-http-spi/src/test/java/org/eclipse/jetty/http/spi/util/PrintTask.java @@ -19,9 +19,7 @@ package org.eclipse.jetty.http.spi.util; /** - * * This is a sample task. Test cases uses this for testing purpose - * */ public class PrintTask implements Runnable { diff --git a/jetty-http-spi/src/test/java/org/eclipse/jetty/http/spi/util/SpiConstants.java b/jetty-http-spi/src/test/java/org/eclipse/jetty/http/spi/util/SpiConstants.java index 3c9f9b2b72d..7520135a898 100644 --- a/jetty-http-spi/src/test/java/org/eclipse/jetty/http/spi/util/SpiConstants.java +++ b/jetty-http-spi/src/test/java/org/eclipse/jetty/http/spi/util/SpiConstants.java @@ -19,15 +19,13 @@ package org.eclipse.jetty.http.spi.util; /** - * * This class holds the constant required for test cases. - * */ public class SpiConstants { public static final int[] poolInfo = - { Pool.MAXIMUM_POOL_SIZE.getValue(), Pool.KEEP_ALIVE_TIME.getValue(), Pool.DEFAULT_WORK_QUEUE_SIZE.getValue() }; + {Pool.MAXIMUM_POOL_SIZE.getValue(), Pool.KEEP_ALIVE_TIME.getValue(), Pool.DEFAULT_WORK_QUEUE_SIZE.getValue()}; public static final String LOCAL_HOST = "localhost"; diff --git a/jetty-http-spi/src/test/java/org/eclipse/jetty/http/spi/util/SpiUtility.java b/jetty-http-spi/src/test/java/org/eclipse/jetty/http/spi/util/SpiUtility.java index 6cf32c93364..0ea8a3c8b39 100644 --- a/jetty-http-spi/src/test/java/org/eclipse/jetty/http/spi/util/SpiUtility.java +++ b/jetty-http-spi/src/test/java/org/eclipse/jetty/http/spi/util/SpiUtility.java @@ -26,6 +26,7 @@ import java.util.Map; import java.util.concurrent.ArrayBlockingQueue; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; + import org.eclipse.jetty.http.spi.DelegatingThreadPool; import org.eclipse.jetty.http.spi.JettyHttpServer; import org.eclipse.jetty.server.Handler; @@ -36,33 +37,31 @@ import org.eclipse.jetty.server.handler.HandlerCollection; /** * This is a utility class. Test cases uses this utility class - * - * */ public class SpiUtility { public static ThreadPoolExecutor getThreadPoolExecutor(int poolSize, int[] poolInfo) { - return new ThreadPoolExecutor(poolSize,poolInfo[0],poolInfo[1],TimeUnit.SECONDS,new ArrayBlockingQueue(poolInfo[2])); + return new ThreadPoolExecutor(poolSize, poolInfo[0], poolInfo[1], TimeUnit.SECONDS, new ArrayBlockingQueue(poolInfo[2])); } public static DelegatingThreadPool getDelegatingThreadPool() { - ThreadPoolExecutor threadPoolExecutor = SpiUtility.getThreadPoolExecutor(Pool.CORE_POOL_SIZE.getValue(),SpiConstants.poolInfo); + ThreadPoolExecutor threadPoolExecutor = SpiUtility.getThreadPoolExecutor(Pool.CORE_POOL_SIZE.getValue(), SpiConstants.poolInfo); DelegatingThreadPool delegatingThreadPool = new DelegatingThreadPool(threadPoolExecutor); return delegatingThreadPool; } public static InetSocketAddress getInetSocketAddress() { - return new InetSocketAddress(SpiConstants.LOCAL_HOST,SpiConstants.DEFAULT_PORT); + return new InetSocketAddress(SpiConstants.LOCAL_HOST, SpiConstants.DEFAULT_PORT); } public static void callBind(JettyHttpServer jettyHttpServer) throws Exception { InetSocketAddress inetSocketAddress = SpiUtility.getInetSocketAddress(); - jettyHttpServer.bind(inetSocketAddress,SpiConstants.BACK_LOG); + jettyHttpServer.bind(inetSocketAddress, SpiConstants.BACK_LOG); } public static Server getServerForContextHandler() @@ -85,7 +84,7 @@ public class SpiUtility { ContextHandler handler = new ContextHandler(); Handler[] handles = - { handler }; + {handler}; HandlerCollection contextHandler = new HandlerCollection(); contextHandler.setHandlers(handles); Server server = new Server(); @@ -98,7 +97,7 @@ public class SpiUtility ArrayList valueSet = new ArrayList(); valueSet.add(SpiConstants.UTF_8); Map> headers = new Hashtable<>(); - headers.put(SpiConstants.ACCEPT_CHARSET,valueSet); + headers.put(SpiConstants.ACCEPT_CHARSET, valueSet); return headers; } diff --git a/jetty-http/pom.xml b/jetty-http/pom.xml index 7f364d1aff3..a5071238200 100644 --- a/jetty-http/pom.xml +++ b/jetty-http/pom.xml @@ -1,6 +1,5 @@ - + jetty-project org.eclipse.jetty @@ -45,8 +44,7 @@ maven-surefire-plugin - @{argLine} ${jetty.surefire.argLine} - --add-modules jetty.servlet.api + @{argLine} ${jetty.surefire.argLine} --add-modules jetty.servlet.api
    @@ -56,10 +54,7 @@ true - osgi.serviceloader; - filter:="(osgi.serviceloader=org.eclipse.jetty.http.HttpFieldPreEncoder)";resolution:=optional;cardinality:=multiple, - osgi.extender; filter:="(osgi.extender=osgi.serviceloader.processor)";resolution:=optional, osgi.extender; - filter:="(osgi.extender=osgi.serviceloader.registrar)";resolution:=optional + osgi.serviceloader; filter:="(osgi.serviceloader=org.eclipse.jetty.http.HttpFieldPreEncoder)";resolution:=optional;cardinality:=multiple, osgi.extender; filter:="(osgi.extender=osgi.serviceloader.processor)";resolution:=optional, osgi.extender; filter:="(osgi.extender=osgi.serviceloader.registrar)";resolution:=optional osgi.serviceloader; osgi.serviceloader=org.eclipse.jetty.http.HttpFieldPreEncoder @@ -91,8 +86,7 @@ - + org.openjdk.jmh.Main diff --git a/jetty-http/src/main/java/org/eclipse/jetty/http/BadMessageException.java b/jetty-http/src/main/java/org/eclipse/jetty/http/BadMessageException.java index 9623a3aa35e..84c446edd9f 100644 --- a/jetty-http/src/main/java/org/eclipse/jetty/http/BadMessageException.java +++ b/jetty-http/src/main/java/org/eclipse/jetty/http/BadMessageException.java @@ -18,8 +18,7 @@ package org.eclipse.jetty.http; -/* ------------------------------------------------------------------------------- */ -/** +/** *

    Exception thrown to indicate a Bad HTTP Message has either been received * or attempted to be generated. Typically these are handled with either 400 * or 500 responses.

    @@ -32,41 +31,41 @@ public class BadMessageException extends RuntimeException public BadMessageException() { - this(400,null); + this(400, null); } - + public BadMessageException(int code) { - this(code,null); + this(code, null); } - + public BadMessageException(String reason) { - this(400,reason); + this(400, reason); } - + public BadMessageException(String reason, Throwable cause) { this(400, reason, cause); } - + public BadMessageException(int code, String reason) { this(code, reason, null); } - + public BadMessageException(int code, String reason, Throwable cause) { - super(code+": "+reason, cause); - _code=code; - _reason=reason; + super(code + ": " + reason, cause); + _code = code; + _reason = reason; } - + public int getCode() { return _code; } - + public String getReason() { return _reason; diff --git a/jetty-http/src/main/java/org/eclipse/jetty/http/ComplianceViolation.java b/jetty-http/src/main/java/org/eclipse/jetty/http/ComplianceViolation.java index 3972c2171bc..b0ec773e161 100644 --- a/jetty-http/src/main/java/org/eclipse/jetty/http/ComplianceViolation.java +++ b/jetty-http/src/main/java/org/eclipse/jetty/http/ComplianceViolation.java @@ -23,7 +23,9 @@ import java.util.Set; public interface ComplianceViolation { String getName(); + String getURL(); + String getDescription(); default boolean isAllowedBy(Mode mode) @@ -34,8 +36,11 @@ public interface ComplianceViolation interface Mode { String getName(); + boolean allows(ComplianceViolation violation); + Set getKnown(); + Set getAllowed(); } diff --git a/jetty-http/src/main/java/org/eclipse/jetty/http/CompressedContentFormat.java b/jetty-http/src/main/java/org/eclipse/jetty/http/CompressedContentFormat.java index 8cce4fc22a0..dfe8c9db79f 100644 --- a/jetty-http/src/main/java/org/eclipse/jetty/http/CompressedContentFormat.java +++ b/jetty-http/src/main/java/org/eclipse/jetty/http/CompressedContentFormat.java @@ -18,8 +18,6 @@ package org.eclipse.jetty.http; - -/* ------------------------------------------------------------ */ public class CompressedContentFormat { public static final CompressedContentFormat GZIP = new CompressedContentFormat("gzip", ".gz"); @@ -40,19 +38,19 @@ public class CompressedContentFormat _etagQuote = _etag + "\""; _contentEncoding = new PreEncodedHttpField(HttpHeader.CONTENT_ENCODING, encoding); } - + @Override public boolean equals(Object o) { if (!(o instanceof CompressedContentFormat)) return false; CompressedContentFormat ccf = (CompressedContentFormat)o; - if (_encoding==null && ccf._encoding!=null) + if (_encoding == null && ccf._encoding != null) return false; - if (_extension==null && ccf._extension!=null) + if (_extension == null && ccf._extension != null) return false; - - return _encoding.equalsIgnoreCase(ccf._encoding) && _extension.equalsIgnoreCase(ccf._extension); + + return _encoding.equalsIgnoreCase(ccf._encoding) && _extension.equalsIgnoreCase(ccf._extension); } public static boolean tagEquals(String etag, String tag) @@ -61,8 +59,8 @@ public class CompressedContentFormat return true; int dashdash = tag.indexOf("--"); - if (dashdash>0 && dashdash==etag.length()-1) - return etag.regionMatches(0,tag,0,dashdash); + if (dashdash > 0 && dashdash == etag.length() - 1) + return etag.regionMatches(0, tag, 0, dashdash); return false; } } diff --git a/jetty-http/src/main/java/org/eclipse/jetty/http/CookieCompliance.java b/jetty-http/src/main/java/org/eclipse/jetty/http/CookieCompliance.java index aa852a90d3b..48a80eda6f5 100644 --- a/jetty-http/src/main/java/org/eclipse/jetty/http/CookieCompliance.java +++ b/jetty-http/src/main/java/org/eclipse/jetty/http/CookieCompliance.java @@ -31,15 +31,13 @@ import static java.util.EnumSet.noneOf; /** * The compliance for Cookie handling. - * */ public class CookieCompliance implements ComplianceViolation.Mode { enum Violation implements ComplianceViolation { COMMA_NOT_VALID_OCTET("https://tools.ietf.org/html/rfc6265#section-4.1.1", "Comma not valid as cookie-octet or separator"), - RESERVED_NAMES_NOT_DOLLAR_PREFIXED("https://tools.ietf.org/html/rfc6265#section-4.1.1","Reserved names no longer use '$' prefix") - ; + RESERVED_NAMES_NOT_DOLLAR_PREFIXED("https://tools.ietf.org/html/rfc6265#section-4.1.1", "Reserved names no longer use '$' prefix"); private final String url; private final String description; @@ -55,6 +53,7 @@ public class CookieCompliance implements ComplianceViolation.Mode { return name(); } + @Override public String getURL() { @@ -71,13 +70,15 @@ public class CookieCompliance implements ComplianceViolation.Mode public static final CookieCompliance RFC6265 = new CookieCompliance("RFC6265", noneOf(Violation.class)); public static final CookieCompliance RFC2965 = new CookieCompliance("RFC2965", allOf(Violation.class)); - private final static List KNOWN_MODES = Arrays.asList(RFC6265,RFC2965); + private static final List KNOWN_MODES = Arrays.asList(RFC6265, RFC2965); public static CookieCompliance valueOf(String name) { for (CookieCompliance compliance : KNOWN_MODES) + { if (compliance.getName().equals(name)) return compliance; + } return null; } diff --git a/jetty-http/src/main/java/org/eclipse/jetty/http/CookieCutter.java b/jetty-http/src/main/java/org/eclipse/jetty/http/CookieCutter.java index cee4bcaa1fd..a5a4ac64952 100644 --- a/jetty-http/src/main/java/org/eclipse/jetty/http/CookieCutter.java +++ b/jetty-http/src/main/java/org/eclipse/jetty/http/CookieCutter.java @@ -27,7 +27,8 @@ import org.eclipse.jetty.util.log.Logger; import static org.eclipse.jetty.http.CookieCompliance.Violation.COMMA_NOT_VALID_OCTET; import static org.eclipse.jetty.http.CookieCompliance.Violation.RESERVED_NAMES_NOT_DOLLAR_PREFIXED; -/** Cookie parser +/** + * Cookie parser */ public abstract class CookieCutter { @@ -44,7 +45,7 @@ public abstract class CookieCutter protected void parseFields(List rawFields) { - StringBuilder unquoted=null; + StringBuilder unquoted = null; // For each cookie field for (String hdr : rawFields) @@ -59,15 +60,15 @@ public abstract class CookieCutter String cookieComment = null; int cookieVersion = 0; - boolean invalue=false; - boolean inQuoted=false; - boolean quoted=false; - boolean escaped=false; - int tokenstart=-1; - int tokenend=-1; + boolean invalue = false; + boolean inQuoted = false; + boolean quoted = false; + boolean escaped = false; + int tokenstart = -1; + int tokenend = -1; for (int i = 0, length = hdr.length(); i <= length; i++) { - char c = i==length?0:hdr.charAt(i); + char c = i == length ? 0 : hdr.charAt(i); // System.err.printf("i=%d/%d c=%s v=%b q=%b/%b e=%b u=%s s=%d e=%d \t%s=%s%n" ,i,length,c==0?"|":(""+c),invalue,inQuoted,quoted,escaped,unquoted,tokenstart,tokenend,name,value); @@ -76,8 +77,8 @@ public abstract class CookieCutter { if (escaped) { - escaped=false; - if (c>0) + escaped = false; + if (c > 0) unquoted.append(c); else { @@ -107,7 +108,7 @@ public abstract class CookieCutter inQuoted = false; i--; continue; - + default: unquoted.append(c); continue; @@ -127,20 +128,20 @@ public abstract class CookieCutter case ',': if (COMMA_NOT_VALID_OCTET.isAllowedBy(_complianceMode)) - reportComplianceViolation(COMMA_NOT_VALID_OCTET, "Cookie "+cookieName); + reportComplianceViolation(COMMA_NOT_VALID_OCTET, "Cookie " + cookieName); else { if (quoted) { // must have been a bad internal quote. let's fix as best we can - unquoted.append(hdr,tokenstart,i--); + unquoted.append(hdr, tokenstart, i--); inQuoted = true; quoted = false; continue; } - if (tokenstart<0) + if (tokenstart < 0) tokenstart = i; - tokenend=i; + tokenend = i; continue; } // fall through @@ -155,8 +156,8 @@ public abstract class CookieCutter unquoted.setLength(0); quoted = false; } - else if(tokenstart>=0) - value = tokenend>=tokenstart?hdr.substring(tokenstart, tokenend+1):hdr.substring(tokenstart); + else if (tokenstart >= 0) + value = tokenend >= tokenstart ? hdr.substring(tokenstart, tokenend + 1) : hdr.substring(tokenstart); else value = ""; @@ -166,9 +167,9 @@ public abstract class CookieCutter { if (RESERVED_NAMES_NOT_DOLLAR_PREFIXED.isAllowedBy(_complianceMode)) { - reportComplianceViolation(RESERVED_NAMES_NOT_DOLLAR_PREFIXED, "Cookie "+cookieName+" field "+name); + reportComplianceViolation(RESERVED_NAMES_NOT_DOLLAR_PREFIXED, "Cookie " + cookieName + " field " + name); String lowercaseName = name.toLowerCase(Locale.ENGLISH); - switch(lowercaseName) + switch (lowercaseName) { case "$path": cookiePath = value; @@ -177,7 +178,7 @@ public abstract class CookieCutter cookieDomain = value; break; case "$port": - cookieComment = "$port="+value; + cookieComment = "$port=" + value; break; case "$version": cookieVersion = Integer.parseInt(value); @@ -190,7 +191,7 @@ public abstract class CookieCutter else { // This is a new cookie, so add the completed last cookie if we have one - if (cookieName!=null) + if (cookieName != null) { addCookie(cookieName, cookieValue, cookieDomain, cookiePath, cookieVersion, cookieComment); cookieDomain = null; @@ -208,18 +209,18 @@ public abstract class CookieCutter name = null; tokenstart = -1; - invalue=false; + invalue = false; break; } case '"': - if (tokenstart<0) + if (tokenstart < 0) { - tokenstart=i; - inQuoted=true; - if (unquoted==null) - unquoted=new StringBuilder(); + tokenstart = i; + inQuoted = true; + if (unquoted == null) + unquoted = new StringBuilder(); break; } // fall through to default case @@ -228,14 +229,14 @@ public abstract class CookieCutter if (quoted) { // must have been a bad internal quote. let's fix as best we can - unquoted.append(hdr,tokenstart,i--); + unquoted.append(hdr, tokenstart, i--); inQuoted = true; quoted = false; continue; } - if (tokenstart<0) + if (tokenstart < 0) tokenstart = i; - tokenend=i; + tokenend = i; continue; } } @@ -255,8 +256,8 @@ public abstract class CookieCutter unquoted.setLength(0); quoted = false; } - else if(tokenstart>=0) - name = tokenend>=tokenstart?hdr.substring(tokenstart, tokenend+1):hdr.substring(tokenstart); + else if (tokenstart >= 0) + name = tokenend >= tokenstart ? hdr.substring(tokenstart, tokenend + 1) : hdr.substring(tokenstart); tokenstart = -1; invalue = true; @@ -266,22 +267,22 @@ public abstract class CookieCutter if (quoted) { // must have been a bad internal quote. let's fix as best we can - unquoted.append(hdr,tokenstart,i--); + unquoted.append(hdr, tokenstart, i--); inQuoted = true; quoted = false; continue; } - if (tokenstart<0) - tokenstart=i; - tokenend=i; + if (tokenstart < 0) + tokenstart = i; + tokenend = i; continue; } } } } - if (cookieName!=null) - addCookie(cookieName,cookieValue,cookieDomain,cookiePath,cookieVersion,cookieComment); + if (cookieName != null) + addCookie(cookieName, cookieValue, cookieDomain, cookiePath, cookieVersion, cookieComment); } } diff --git a/jetty-http/src/main/java/org/eclipse/jetty/http/DateGenerator.java b/jetty-http/src/main/java/org/eclipse/jetty/http/DateGenerator.java index d768d4f470b..f37b2cb0ab4 100644 --- a/jetty-http/src/main/java/org/eclipse/jetty/http/DateGenerator.java +++ b/jetty-http/src/main/java/org/eclipse/jetty/http/DateGenerator.java @@ -30,18 +30,18 @@ import org.eclipse.jetty.util.StringUtil; public class DateGenerator { private static final TimeZone __GMT = TimeZone.getTimeZone("GMT"); + static { __GMT.setID("GMT"); } - + static final String[] DAYS = - { "Sat", "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"}; + {"Sat", "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"}; static final String[] MONTHS = - { "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec", "Jan"}; + {"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec", "Jan"}; - - private static final ThreadLocal __dateGenerator =new ThreadLocal() + private static final ThreadLocal __dateGenerator = new ThreadLocal() { @Override protected DateGenerator initialValue() @@ -50,11 +50,11 @@ public class DateGenerator } }; + public static final String __01Jan1970 = DateGenerator.formatDate(0); - public final static String __01Jan1970=DateGenerator.formatDate(0); - /** * Format HTTP date "EEE, dd MMM yyyy HH:mm:ss 'GMT'" + * * @param date the date in milliseconds * @return the formatted date */ @@ -65,17 +65,19 @@ public class DateGenerator /** * Format "EEE, dd-MMM-yyyy HH:mm:ss 'GMT'" for cookies + * * @param buf the buffer to put the formatted date into * @param date the date in milliseconds */ public static void formatCookieDate(StringBuilder buf, long date) { - __dateGenerator.get().doFormatCookieDate(buf,date); + __dateGenerator.get().doFormatCookieDate(buf, date); } /** * Format "EEE, dd-MMM-yyyy HH:mm:ss 'GMT'" for cookies - * @param date the date in milliseconds + * + * @param date the date in milliseconds * @return the formatted date */ public static String formatCookieDate(long date) @@ -84,12 +86,13 @@ public class DateGenerator formatCookieDate(buf, date); return buf.toString(); } - + private final StringBuilder buf = new StringBuilder(32); private final GregorianCalendar gc = new GregorianCalendar(__GMT); /** * Format HTTP date "EEE, dd MMM yyyy HH:mm:ss 'GMT'" + * * @param date the date in milliseconds * @return the formatted date */ @@ -98,8 +101,8 @@ public class DateGenerator buf.setLength(0); gc.setTimeInMillis(date); - int day_of_week = gc.get(Calendar.DAY_OF_WEEK); - int day_of_month = gc.get(Calendar.DAY_OF_MONTH); + int dayOfWeek = gc.get(Calendar.DAY_OF_WEEK); + int dayOfMonth = gc.get(Calendar.DAY_OF_MONTH); int month = gc.get(Calendar.MONTH); int year = gc.get(Calendar.YEAR); int century = year / 100; @@ -109,10 +112,10 @@ public class DateGenerator int minutes = gc.get(Calendar.MINUTE); int seconds = gc.get(Calendar.SECOND); - buf.append(DAYS[day_of_week]); + buf.append(DAYS[dayOfWeek]); buf.append(','); buf.append(' '); - StringUtil.append2digits(buf, day_of_month); + StringUtil.append2digits(buf, dayOfMonth); buf.append(' '); buf.append(MONTHS[month]); @@ -132,6 +135,7 @@ public class DateGenerator /** * Format "EEE, dd-MMM-yy HH:mm:ss 'GMT'" for cookies + * * @param buf the buffer to format the date into * @param date the date in milliseconds */ @@ -139,28 +143,28 @@ public class DateGenerator { gc.setTimeInMillis(date); - int day_of_week = gc.get(Calendar.DAY_OF_WEEK); - int day_of_month = gc.get(Calendar.DAY_OF_MONTH); + int dayOfWeek = gc.get(Calendar.DAY_OF_WEEK); + int dayOfMonth = gc.get(Calendar.DAY_OF_MONTH); int month = gc.get(Calendar.MONTH); int year = gc.get(Calendar.YEAR); year = year % 10000; - int epoch = (int) ((date / 1000) % (60 * 60 * 24)); + int epoch = (int)((date / 1000) % (60 * 60 * 24)); int seconds = epoch % 60; epoch = epoch / 60; int minutes = epoch % 60; int hours = epoch / 60; - buf.append(DAYS[day_of_week]); + buf.append(DAYS[dayOfWeek]); buf.append(','); buf.append(' '); - StringUtil.append2digits(buf, day_of_month); + StringUtil.append2digits(buf, dayOfMonth); buf.append('-'); buf.append(MONTHS[month]); buf.append('-'); - StringUtil.append2digits(buf, year/100); - StringUtil.append2digits(buf, year%100); + StringUtil.append2digits(buf, year / 100); + StringUtil.append2digits(buf, year % 100); buf.append(' '); StringUtil.append2digits(buf, hours); diff --git a/jetty-http/src/main/java/org/eclipse/jetty/http/DateParser.java b/jetty-http/src/main/java/org/eclipse/jetty/http/DateParser.java index 9dd257533e5..3367bb567cf 100644 --- a/jetty-http/src/main/java/org/eclipse/jetty/http/DateParser.java +++ b/jetty-http/src/main/java/org/eclipse/jetty/http/DateParser.java @@ -25,37 +25,37 @@ import java.util.TimeZone; /** * ThreadLocal data parsers for HTTP style dates - * */ public class DateParser { - private static final TimeZone __GMT = TimeZone.getTimeZone("GMT"); + private static final TimeZone GMT = TimeZone.getTimeZone("GMT"); + static { - __GMT.setID("GMT"); + GMT.setID("GMT"); } - - final static String __dateReceiveFmt[] = - { - "EEE, dd MMM yyyy HH:mm:ss zzz", - "EEE, dd-MMM-yy HH:mm:ss", - "EEE MMM dd HH:mm:ss yyyy", - "EEE, dd MMM yyyy HH:mm:ss", "EEE dd MMM yyyy HH:mm:ss zzz", - "EEE dd MMM yyyy HH:mm:ss", "EEE MMM dd yyyy HH:mm:ss zzz", "EEE MMM dd yyyy HH:mm:ss", - "EEE MMM-dd-yyyy HH:mm:ss zzz", "EEE MMM-dd-yyyy HH:mm:ss", "dd MMM yyyy HH:mm:ss zzz", - "dd MMM yyyy HH:mm:ss", "dd-MMM-yy HH:mm:ss zzz", "dd-MMM-yy HH:mm:ss", "MMM dd HH:mm:ss yyyy zzz", - "MMM dd HH:mm:ss yyyy", "EEE MMM dd HH:mm:ss yyyy zzz", - "EEE, MMM dd HH:mm:ss yyyy zzz", "EEE, MMM dd HH:mm:ss yyyy", "EEE, dd-MMM-yy HH:mm:ss zzz", - "EEE dd-MMM-yy HH:mm:ss zzz", "EEE dd-MMM-yy HH:mm:ss", - }; + static final String[] DATE_RECEIVE_FMT = + { + "EEE, dd MMM yyyy HH:mm:ss zzz", + "EEE, dd-MMM-yy HH:mm:ss", + "EEE MMM dd HH:mm:ss yyyy", + + "EEE, dd MMM yyyy HH:mm:ss", "EEE dd MMM yyyy HH:mm:ss zzz", + "EEE dd MMM yyyy HH:mm:ss", "EEE MMM dd yyyy HH:mm:ss zzz", "EEE MMM dd yyyy HH:mm:ss", + "EEE MMM-dd-yyyy HH:mm:ss zzz", "EEE MMM-dd-yyyy HH:mm:ss", "dd MMM yyyy HH:mm:ss zzz", + "dd MMM yyyy HH:mm:ss", "dd-MMM-yy HH:mm:ss zzz", "dd-MMM-yy HH:mm:ss", "MMM dd HH:mm:ss yyyy zzz", + "MMM dd HH:mm:ss yyyy", "EEE MMM dd HH:mm:ss yyyy zzz", + "EEE, MMM dd HH:mm:ss yyyy zzz", "EEE, MMM dd HH:mm:ss yyyy", "EEE, dd-MMM-yy HH:mm:ss zzz", + "EEE dd-MMM-yy HH:mm:ss zzz", "EEE dd-MMM-yy HH:mm:ss" + }; public static long parseDate(String date) { - return __dateParser.get().parse(date); + return DATE_PARSER.get().parse(date); } - private static final ThreadLocal __dateParser =new ThreadLocal() + private static final ThreadLocal DATE_PARSER = new ThreadLocal() { @Override protected DateParser initialValue() @@ -63,8 +63,8 @@ public class DateParser return new DateParser(); } }; - - final SimpleDateFormat _dateReceive[]= new SimpleDateFormat[__dateReceiveFmt.length]; + + final SimpleDateFormat[] _dateReceive = new SimpleDateFormat[DATE_RECEIVE_FMT.length]; private long parse(final String dateVal) { @@ -72,18 +72,17 @@ public class DateParser { if (_dateReceive[i] == null) { - _dateReceive[i] = new SimpleDateFormat(__dateReceiveFmt[i], Locale.US); - _dateReceive[i].setTimeZone(__GMT); + _dateReceive[i] = new SimpleDateFormat(DATE_RECEIVE_FMT[i], Locale.US); + _dateReceive[i].setTimeZone(GMT); } try { - Date date = (Date) _dateReceive[i].parseObject(dateVal); + Date date = (Date)_dateReceive[i].parseObject(dateVal); return date.getTime(); } - catch (java.lang.Exception e) + catch (java.lang.Exception ignored) { - // LOG.ignore(e); } } @@ -95,12 +94,11 @@ public class DateParser { try { - Date date = (Date) element.parseObject(val); + Date date = (Date)element.parseObject(val); return date.getTime(); } - catch (java.lang.Exception e) + catch (java.lang.Exception ignored) { - // LOG.ignore(e); } } } diff --git a/jetty-http/src/main/java/org/eclipse/jetty/http/HostPortHttpField.java b/jetty-http/src/main/java/org/eclipse/jetty/http/HostPortHttpField.java index 6c9f3b921e8..2379bcef99e 100644 --- a/jetty-http/src/main/java/org/eclipse/jetty/http/HostPortHttpField.java +++ b/jetty-http/src/main/java/org/eclipse/jetty/http/HostPortHttpField.java @@ -16,14 +16,13 @@ // ======================================================================== // - package org.eclipse.jetty.http; import org.eclipse.jetty.util.HostPort; - /** * A HttpField holding a preparsed Host and port number + * * @see HostPort */ public class HostPortHttpField extends HttpField @@ -32,19 +31,19 @@ public class HostPortHttpField extends HttpField public HostPortHttpField(String authority) { - this(HttpHeader.HOST,HttpHeader.HOST.asString(),authority); + this(HttpHeader.HOST, HttpHeader.HOST.asString(), authority); } protected HostPortHttpField(HttpHeader header, String name, String authority) { - super(header,name,authority); + super(header, name, authority); try { - _hostPort=new HostPort(authority); + _hostPort = new HostPort(authority); } - catch(Exception e) + catch (Exception e) { - throw new BadMessageException(HttpStatus.BAD_REQUEST_400,"Bad HostPort",e); + throw new BadMessageException(HttpStatus.BAD_REQUEST_400, "Bad HostPort", e); } } @@ -55,11 +54,13 @@ public class HostPortHttpField extends HttpField public HostPortHttpField(HostPort hostport) { - super(HttpHeader.HOST,HttpHeader.HOST.asString(),hostport.toString()); + super(HttpHeader.HOST, HttpHeader.HOST.asString(), hostport.toString()); _hostPort = hostport; } - /** Get the host. + /** + * Get the host. + * * @return the host */ public String getHost() @@ -67,15 +68,19 @@ public class HostPortHttpField extends HttpField return _hostPort.getHost(); } - /** Get the port. + /** + * Get the port. + * * @return the port */ public int getPort() { return _hostPort.getPort(); } - - /** Get the port. + + /** + * Get the port. + * * @param defaultPort The default port to return if no port set * @return the port */ diff --git a/jetty-http/src/main/java/org/eclipse/jetty/http/Http1FieldPreEncoder.java b/jetty-http/src/main/java/org/eclipse/jetty/http/Http1FieldPreEncoder.java index 17da781202e..41f80514143 100644 --- a/jetty-http/src/main/java/org/eclipse/jetty/http/Http1FieldPreEncoder.java +++ b/jetty-http/src/main/java/org/eclipse/jetty/http/Http1FieldPreEncoder.java @@ -16,20 +16,18 @@ // ======================================================================== // - package org.eclipse.jetty.http; import java.util.Arrays; import static java.nio.charset.StandardCharsets.ISO_8859_1; - -/* ------------------------------------------------------------ */ /** + * */ public class Http1FieldPreEncoder implements HttpFieldPreEncoder { - /* ------------------------------------------------------------ */ + /** * @see org.eclipse.jetty.http.HttpFieldPreEncoder#getHttpVersion() */ @@ -39,31 +37,30 @@ public class Http1FieldPreEncoder implements HttpFieldPreEncoder return HttpVersion.HTTP_1_0; } - /* ------------------------------------------------------------ */ /** * @see org.eclipse.jetty.http.HttpFieldPreEncoder#getEncodedField(org.eclipse.jetty.http.HttpHeader, java.lang.String, java.lang.String) */ @Override public byte[] getEncodedField(HttpHeader header, String headerString, String value) { - if (header!=null) + if (header != null) { - int cbl=header.getBytesColonSpace().length; - byte[] bytes=Arrays.copyOf(header.getBytesColonSpace(), cbl+value.length()+2); - System.arraycopy(value.getBytes(ISO_8859_1),0,bytes,cbl,value.length()); - bytes[bytes.length-2]=(byte)'\r'; - bytes[bytes.length-1]=(byte)'\n'; + int cbl = header.getBytesColonSpace().length; + byte[] bytes = Arrays.copyOf(header.getBytesColonSpace(), cbl + value.length() + 2); + System.arraycopy(value.getBytes(ISO_8859_1), 0, bytes, cbl, value.length()); + bytes[bytes.length - 2] = (byte)'\r'; + bytes[bytes.length - 1] = (byte)'\n'; return bytes; } - byte[] n=headerString.getBytes(ISO_8859_1); - byte[] v=value.getBytes(ISO_8859_1); - byte[] bytes=Arrays.copyOf(n,n.length+2+v.length+2); - bytes[n.length]=(byte)':'; - bytes[n.length+1]=(byte)' '; - System.arraycopy(v, 0, bytes, n.length+2, v.length); - bytes[bytes.length-2]=(byte)'\r'; - bytes[bytes.length-1]=(byte)'\n'; + byte[] n = headerString.getBytes(ISO_8859_1); + byte[] v = value.getBytes(ISO_8859_1); + byte[] bytes = Arrays.copyOf(n, n.length + 2 + v.length + 2); + bytes[n.length] = (byte)':'; + bytes[n.length + 1] = (byte)' '; + System.arraycopy(v, 0, bytes, n.length + 2, v.length); + bytes[bytes.length - 2] = (byte)'\r'; + bytes[bytes.length - 1] = (byte)'\n'; return bytes; } diff --git a/jetty-http/src/main/java/org/eclipse/jetty/http/HttpCompliance.java b/jetty-http/src/main/java/org/eclipse/jetty/http/HttpCompliance.java index be2f6d70a5d..9a19d3cf675 100644 --- a/jetty-http/src/main/java/org/eclipse/jetty/http/HttpCompliance.java +++ b/jetty-http/src/main/java/org/eclipse/jetty/http/HttpCompliance.java @@ -87,32 +87,33 @@ public final class HttpCompliance implements ComplianceViolation.Mode private static final Logger LOG = Log.getLogger(HttpParser.class); public static final String VIOLATIONS_ATTR = "org.eclipse.jetty.http.compliance.violations"; - public final static HttpCompliance RFC7230 = new HttpCompliance("RFC7230", noneOf(Violation.class)); - public final static HttpCompliance RFC2616 = new HttpCompliance("RFC2616", of(Violation.HTTP_0_9, Violation.MULTILINE_FIELD_VALUE)); - public final static HttpCompliance LEGACY = new HttpCompliance("LEGACY", complementOf(of(Violation.CASE_INSENSITIVE_METHOD))); - public final static HttpCompliance RFC2616_LEGACY = RFC2616.with( "RFC2616_LEGACY", - Violation.CASE_INSENSITIVE_METHOD, - Violation.NO_COLON_AFTER_FIELD_NAME, - Violation.TRANSFER_ENCODING_WITH_CONTENT_LENGTH, - Violation.MULTIPLE_CONTENT_LENGTHS); - public final static HttpCompliance RFC7230_LEGACY = RFC7230.with("RFC7230_LEGACY", Violation.CASE_INSENSITIVE_METHOD); + public static final HttpCompliance RFC7230 = new HttpCompliance("RFC7230", noneOf(Violation.class)); + public static final HttpCompliance RFC2616 = new HttpCompliance("RFC2616", of(Violation.HTTP_0_9, Violation.MULTILINE_FIELD_VALUE)); + public static final HttpCompliance LEGACY = new HttpCompliance("LEGACY", complementOf(of(Violation.CASE_INSENSITIVE_METHOD))); + public static final HttpCompliance RFC2616_LEGACY = RFC2616.with("RFC2616_LEGACY", + Violation.CASE_INSENSITIVE_METHOD, + Violation.NO_COLON_AFTER_FIELD_NAME, + Violation.TRANSFER_ENCODING_WITH_CONTENT_LENGTH, + Violation.MULTIPLE_CONTENT_LENGTHS); + public static final HttpCompliance RFC7230_LEGACY = RFC7230.with("RFC7230_LEGACY", Violation.CASE_INSENSITIVE_METHOD); - - private final static List KNOWN_MODES = Arrays.asList(RFC7230,RFC2616,LEGACY,RFC2616_LEGACY,RFC7230_LEGACY); - private final static AtomicInteger __custom = new AtomicInteger(); + private static final List KNOWN_MODES = Arrays.asList(RFC7230, RFC2616, LEGACY, RFC2616_LEGACY, RFC7230_LEGACY); + private static final AtomicInteger __custom = new AtomicInteger(); public static HttpCompliance valueOf(String name) { for (HttpCompliance compliance : KNOWN_MODES) + { if (compliance.getName().equals(name)) return compliance; + } return null; } /** * Create compliance set from string. *

    - * Format: + * Format: *

    *
    *
    0
    No {@link Violation}s
    @@ -126,6 +127,7 @@ public final class HttpCompliance implements ComplianceViolation.Mode * The remainder of the list can contain then names of {@link Violation}s to include them in the mode, or prefixed * with a '-' to exclude thm from the mode. *

    + * * @param spec A string in the format of a comma separated list starting with one of the following strings: * @return the compliance from the string spec */ @@ -133,7 +135,7 @@ public final class HttpCompliance implements ComplianceViolation.Mode { Set sections; String[] elements = spec.split("\\s*,\\s*"); - switch(elements[0]) + switch (elements[0]) { case "0": sections = noneOf(Violation.class); @@ -146,23 +148,23 @@ public final class HttpCompliance implements ComplianceViolation.Mode default: { HttpCompliance mode = HttpCompliance.valueOf(elements[0]); - if (mode==null) + if (mode == null) sections = noneOf(Violation.class); else sections = copyOf(mode.getAllowed()); } } - for (int i=1; i _violations; @@ -182,7 +183,7 @@ public final class HttpCompliance implements ComplianceViolation.Mode { Objects.nonNull(violations); _name = name; - _violations = unmodifiableSet(violations.isEmpty()?noneOf(Violation.class):copyOf(violations)); + _violations = unmodifiableSet(violations.isEmpty() ? noneOf(Violation.class) : copyOf(violations)); } @Override @@ -199,6 +200,7 @@ public final class HttpCompliance implements ComplianceViolation.Mode /** * Get the set of {@link Violation}s allowed by this compliance mode. + * * @return The immutable set of {@link Violation}s allowed by this compliance mode. */ @Override @@ -215,26 +217,28 @@ public final class HttpCompliance implements ComplianceViolation.Mode /** * Create a new HttpCompliance mode that includes the passed {@link Violation}s. + * * @param name The name of the new mode * @param violations The violations to include * @return A new {@link HttpCompliance} mode. */ public HttpCompliance with(String name, Violation... violations) { - Set union = _violations.isEmpty()?EnumSet.noneOf(Violation.class):copyOf(_violations); + Set union = _violations.isEmpty() ? EnumSet.noneOf(Violation.class) : copyOf(_violations); union.addAll(copyOf(violations)); return new HttpCompliance(name, union); } /** * Create a new HttpCompliance mode that excludes the passed {@link Violation}s. + * * @param name The name of the new mode * @param violations The violations to exclude * @return A new {@link HttpCompliance} mode. */ public HttpCompliance without(String name, Violation... violations) { - Set remainder = _violations.isEmpty()?EnumSet.noneOf(Violation.class):copyOf(_violations); + Set remainder = _violations.isEmpty() ? EnumSet.noneOf(Violation.class) : copyOf(_violations); remainder.removeAll(copyOf(violations)); return new HttpCompliance(name, remainder); } @@ -242,20 +246,19 @@ public final class HttpCompliance implements ComplianceViolation.Mode @Override public String toString() { - return String.format("%s%s",_name,_violations); + return String.format("%s%s", _name, _violations); } - private static Set copyOf(Violation[] violations) { - if (violations==null || violations.length==0) + if (violations == null || violations.length == 0) return EnumSet.noneOf(Violation.class); return EnumSet.copyOf(asList(violations)); } private static Set copyOf(Set violations) { - if (violations==null || violations.isEmpty()) + if (violations == null || violations.isEmpty()) return EnumSet.noneOf(Violation.class); return EnumSet.copyOf(violations); } diff --git a/jetty-http/src/main/java/org/eclipse/jetty/http/HttpContent.java b/jetty-http/src/main/java/org/eclipse/jetty/http/HttpContent.java index c2a03d12692..858f21d3fcd 100644 --- a/jetty-http/src/main/java/org/eclipse/jetty/http/HttpContent.java +++ b/jetty-http/src/main/java/org/eclipse/jetty/http/HttpContent.java @@ -27,46 +27,56 @@ import java.util.Map; import org.eclipse.jetty.http.MimeTypes.Type; import org.eclipse.jetty.util.resource.Resource; -/* ------------------------------------------------------------ */ -/** HttpContent interface. - *

    This information represents all the information about a +/** + * HttpContent interface. + *

    This information represents all the information about a * static resource that is needed to evaluate conditional headers * and to serve the content if need be. It can be implemented - * either transiently (values and fields generated on demand) or + * either transiently (values and fields generated on demand) or * persistently (values and fields pre-generated in anticipation of * reuse in from a cache). - *

    - * + *

    */ public interface HttpContent { HttpField getContentType(); + String getContentTypeValue(); + String getCharacterEncoding(); + Type getMimeType(); HttpField getContentEncoding(); + String getContentEncodingValue(); - + HttpField getContentLength(); + long getContentLengthValue(); - + HttpField getLastModified(); + String getLastModifiedValue(); - + HttpField getETag(); + String getETagValue(); - + ByteBuffer getIndirectBuffer(); + ByteBuffer getDirectBuffer(); + Resource getResource(); + InputStream getInputStream() throws IOException; + ReadableByteChannel getReadableByteChannel() throws IOException; + void release(); - Map getPrecompressedContents(); - - + Map getPrecompressedContents(); + public interface ContentFactory { /** @@ -76,6 +86,6 @@ public interface HttpContent * @return A {@link HttpContent} * @throws IOException if unable to get content */ - HttpContent getContent(String path,int maxBuffer) throws IOException; + HttpContent getContent(String path, int maxBuffer) throws IOException; } } diff --git a/jetty-http/src/main/java/org/eclipse/jetty/http/HttpCookie.java b/jetty-http/src/main/java/org/eclipse/jetty/http/HttpCookie.java index a4c63baa007..e52ec2dee6a 100644 --- a/jetty-http/src/main/java/org/eclipse/jetty/http/HttpCookie.java +++ b/jetty-http/src/main/java/org/eclipse/jetty/http/HttpCookie.java @@ -26,7 +26,7 @@ import org.eclipse.jetty.util.QuotedStringTokenizer; // TODO consider replacing this with java.net.HttpCookie public class HttpCookie { - private static final String __COOKIE_DELIM="\",;\\ \t"; + private static final String __COOKIE_DELIM = "\",;\\ \t"; private static final String __01Jan1970_COOKIE = DateGenerator.formatCookieDate(0).trim(); private final String _name; @@ -77,7 +77,7 @@ public class HttpCookie public HttpCookie(String setCookie) { List cookies = java.net.HttpCookie.parse(setCookie); - if (cookies.size()!=1) + if (cookies.size() != 1) throw new IllegalStateException(); java.net.HttpCookie cookie = cookies.get(0); @@ -94,7 +94,6 @@ public class HttpCookie _expiration = _maxAge < 0 ? -1 : System.nanoTime() + TimeUnit.SECONDS.toNanos(_maxAge); } - /** * @return the cookie name */ @@ -190,35 +189,36 @@ public class HttpCookie return builder.toString(); } - private static void quoteOnlyOrAppend(StringBuilder buf, String s, boolean quote) { if (quote) - QuotedStringTokenizer.quoteOnly(buf,s); + QuotedStringTokenizer.quoteOnly(buf, s); else buf.append(s); } - /** Does a cookie value need to be quoted? + /** + * Does a cookie value need to be quoted? + * * @param s value string * @return true if quoted; * @throws IllegalArgumentException If there a control characters in the string */ private static boolean isQuoteNeededForCookie(String s) { - if (s==null || s.length()==0) + if (s == null || s.length() == 0) return true; if (QuotedStringTokenizer.isQuoted(s)) return false; - for (int i=0;i=0) + if (__COOKIE_DELIM.indexOf(c) >= 0) return true; - if (c<0x20 || c>=0x7f) + if (c < 0x20 || c >= 0x7f) throw new IllegalArgumentException("Illegal character in cookie value"); } @@ -245,46 +245,46 @@ public class HttpCookie StringBuilder buf = new StringBuilder(); // Name is checked for legality by servlet spec, but can also be passed directly so check again for quoting - boolean quote_name=isQuoteNeededForCookie(_name); - quoteOnlyOrAppend(buf,_name,quote_name); + boolean quoteName = isQuoteNeededForCookie(_name); + quoteOnlyOrAppend(buf, _name, quoteName); buf.append('='); // Append the value - boolean quote_value=isQuoteNeededForCookie(_value); - quoteOnlyOrAppend(buf,_value,quote_value); + boolean quoteValue = isQuoteNeededForCookie(_value); + quoteOnlyOrAppend(buf, _value, quoteValue); // Look for domain and path fields and check if they need to be quoted - boolean has_domain = _domain!=null && _domain.length()>0; - boolean quote_domain = has_domain && isQuoteNeededForCookie(_domain); - boolean has_path = _path!=null && _path.length()>0; - boolean quote_path = has_path && isQuoteNeededForCookie(_path); + boolean hasDomain = _domain != null && _domain.length() > 0; + boolean quoteDomain = hasDomain && isQuoteNeededForCookie(_domain); + boolean hasPath = _path != null && _path.length() > 0; + boolean quotePath = hasPath && isQuoteNeededForCookie(_path); // Upgrade the version if we have a comment or we need to quote value/path/domain or if they were already quoted int version = _version; - if (version==0 && ( _comment!=null || quote_name || quote_value || quote_domain || quote_path || + if (version == 0 && (_comment != null || quoteName || quoteValue || quoteDomain || quotePath || QuotedStringTokenizer.isQuoted(_name) || QuotedStringTokenizer.isQuoted(_value) || QuotedStringTokenizer.isQuoted(_path) || QuotedStringTokenizer.isQuoted(_domain))) - version=1; + version = 1; // Append version - if (version==1) - buf.append (";Version=1"); - else if (version>1) - buf.append (";Version=").append(version); + if (version == 1) + buf.append(";Version=1"); + else if (version > 1) + buf.append(";Version=").append(version); // Append path - if (has_path) + if (hasPath) { buf.append(";Path="); - quoteOnlyOrAppend(buf,_path,quote_path); + quoteOnlyOrAppend(buf, _path, quotePath); } // Append domain - if (has_domain) + if (hasDomain) { buf.append(";Domain="); - quoteOnlyOrAppend(buf,_domain,quote_domain); + quoteOnlyOrAppend(buf, _domain, quoteDomain); } // Handle max-age and/or expires @@ -299,7 +299,7 @@ public class HttpCookie DateGenerator.formatCookieDate(buf, System.currentTimeMillis() + 1000L * _maxAge); // for v1 cookies, also send max-age - if (version>=1) + if (version >= 1) { buf.append(";Max-Age="); buf.append(_maxAge); @@ -314,7 +314,7 @@ public class HttpCookie if (_comment != null) { buf.append(";Comment="); - quoteOnlyOrAppend(buf,_comment,isQuoteNeededForCookie(_comment)); + quoteOnlyOrAppend(buf, _comment, isQuoteNeededForCookie(_comment)); } return buf.toString(); } @@ -333,14 +333,14 @@ public class HttpCookie // Format value and params StringBuilder buf = new StringBuilder(); - buf.append(_name).append('=').append(_value==null?"":_value); + buf.append(_name).append('=').append(_value == null ? "" : _value); // Append path - if (_path!=null && _path.length()>0) + if (_path != null && _path.length() > 0) buf.append("; Path=").append(_path); // Append domain - if (_domain!=null && _domain.length()>0) + if (_domain != null && _domain.length() > 0) buf.append("; Domain=").append(_domain); // Handle max-age and/or expires @@ -366,7 +366,6 @@ public class HttpCookie return buf.toString(); } - public static class SetCookieHttpField extends HttpField { final HttpCookie _cookie; diff --git a/jetty-http/src/main/java/org/eclipse/jetty/http/HttpField.java b/jetty-http/src/main/java/org/eclipse/jetty/http/HttpField.java index dbbc048d839..e69af07893f 100644 --- a/jetty-http/src/main/java/org/eclipse/jetty/http/HttpField.java +++ b/jetty-http/src/main/java/org/eclipse/jetty/http/HttpField.java @@ -22,11 +22,12 @@ import java.util.Objects; import org.eclipse.jetty.util.StringUtil; -/** A HTTP Field +/** + * A HTTP Field */ public class HttpField { - private final static String __zeroquality="q=0"; + private static final String __zeroquality = "q=0"; private final HttpHeader _header; private final String _name; private final String _value; @@ -42,17 +43,17 @@ public class HttpField public HttpField(HttpHeader header, String value) { - this(header,header.asString(),value); + this(header, header.asString(), value); } public HttpField(HttpHeader header, HttpHeaderValue value) { - this(header,header.asString(),value.asString()); + this(header, header.asString(), value.asString()); } public HttpField(String name, String value) { - this(HttpHeader.CACHE.get(name),name,value); + this(HttpHeader.CACHE.get(name), name, value); } public HttpHeader getHeader() @@ -84,13 +85,14 @@ public class HttpField { if (_value == null) return null; - - QuotedCSV list = new QuotedCSV(false,_value); + + QuotedCSV list = new QuotedCSV(false, _value); return list.getValues().toArray(new String[list.size()]); } /** * Look for a value in a possible multi valued field + * * @param search Values to search for (case insensitive) * @return True iff the value is contained in the field value entirely or * as an element of a quoted comma separated list. List element parameters (eg qualities) are ignored, @@ -98,41 +100,41 @@ public class HttpField */ public boolean contains(String search) { - if (search==null) - return _value==null; + if (search == null) + return _value == null; if (search.isEmpty()) return false; - if (_value==null) + if (_value == null) return false; if (search.equals(_value)) return true; search = StringUtil.asciiToLowerCase(search); - int state=0; - int match=0; - int param=0; + int state = 0; + int match = 0; + int param = 0; - for (int i=0;i<_value.length();i++) + for (int i = 0; i < _value.length(); i++) { char c = _value.charAt(i); - switch(state) + switch (state) { case 0: // initial white space - switch(c) + switch (c) { case '"': // open quote - match=0; - state=2; + match = 0; + state = 2; break; case ',': // ignore leading empty field break; case ';': // ignore leading empty field parameter - param=-1; - match=-1; - state=5; + param = -1; + match = -1; + state = 5; break; case ' ': // more white space @@ -140,106 +142,105 @@ public class HttpField break; default: // character - match = Character.toLowerCase(c)==search.charAt(0)?1:-1; - state=1; + match = Character.toLowerCase(c) == search.charAt(0) ? 1 : -1; + state = 1; break; } break; case 1: // In token - switch(c) + switch (c) { case ',': // next field // Have we matched the token? - if (match==search.length()) + if (match == search.length()) return true; - state=0; + state = 0; break; case ';': - param=match>=0?0:-1; - state=5; // parameter + param = match >= 0 ? 0 : -1; + state = 5; // parameter break; default: - if (match>0) + if (match > 0) { - if (match=0) + if (match >= 0) { - if (match=0) + if (match >= 0) { - if (match=0) + if (param >= 0) { - if (param<__zeroquality.length()) - param=Character.toLowerCase(c)==__zeroquality.charAt(param)?(param+1):-1; - else if (c!='0'&&c!='.') - param=-1; + if (param < __zeroquality.length()) + param = Character.toLowerCase(c) == __zeroquality.charAt(param) ? (param + 1) : -1; + else if (c != '0' && c != '.') + param = -1; } - } break; @@ -263,24 +263,23 @@ public class HttpField } } - return param!=__zeroquality.length() && match==search.length(); + return param != __zeroquality.length() && match == search.length(); } - @Override public String toString() { - String v=getValue(); - return getName() + ": " + (v==null?"":v); + String v = getValue(); + return getName() + ": " + (v == null ? "" : v); } public boolean isSameName(HttpField field) { - if (field==null) + if (field == null) return false; - if (field==this) + if (field == this) return true; - if (_header!=null && _header==field.getHeader()) + if (_header != null && _header == field.getHeader()) return true; if (_name.equalsIgnoreCase(field.getName())) return true; @@ -311,7 +310,7 @@ public class HttpField public int hashCode() { int vhc = Objects.hashCode(_value); - if (_header==null) + if (_header == null) return vhc ^ nameHashCode(); return vhc ^ _header.hashCode(); } @@ -319,18 +318,18 @@ public class HttpField @Override public boolean equals(Object o) { - if (o==this) + if (o == this) return true; if (!(o instanceof HttpField)) return false; - HttpField field=(HttpField)o; - if (_header!=field.getHeader()) + HttpField field = (HttpField)o; + if (_header != field.getHeader()) return false; if (!_name.equalsIgnoreCase(field.getName())) return false; - if (_value==null && field.getValue()!=null) + if (_value == null && field.getValue() != null) return false; - return Objects.equals(_value,field.getValue()); + return Objects.equals(_value, field.getValue()); } public static class IntValueHttpField extends HttpField @@ -339,23 +338,23 @@ public class HttpField public IntValueHttpField(HttpHeader header, String name, String value, int intValue) { - super(header,name,value); - _int=intValue; + super(header, name, value); + _int = intValue; } public IntValueHttpField(HttpHeader header, String name, String value) { - this(header,name,value,Integer.parseInt(value)); + this(header, name, value, Integer.parseInt(value)); } public IntValueHttpField(HttpHeader header, String name, int intValue) { - this(header,name,Integer.toString(intValue),intValue); + this(header, name, Integer.toString(intValue), intValue); } public IntValueHttpField(HttpHeader header, int value) { - this(header,header.asString(),value); + this(header, header.asString(), value); } @Override @@ -377,23 +376,23 @@ public class HttpField public LongValueHttpField(HttpHeader header, String name, String value, long longValue) { - super(header,name,value); - _long=longValue; + super(header, name, value); + _long = longValue; } public LongValueHttpField(HttpHeader header, String name, String value) { - this(header,name,value,Long.parseLong(value)); + this(header, name, value, Long.parseLong(value)); } public LongValueHttpField(HttpHeader header, String name, long value) { - this(header,name,Long.toString(value),value); + this(header, name, Long.toString(value), value); } - public LongValueHttpField(HttpHeader header,long value) + public LongValueHttpField(HttpHeader header, long value) { - this(header,header.asString(),value); + this(header, header.asString(), value); } @Override diff --git a/jetty-http/src/main/java/org/eclipse/jetty/http/HttpFieldPreEncoder.java b/jetty-http/src/main/java/org/eclipse/jetty/http/HttpFieldPreEncoder.java index a06b4fbf681..c22fc7ae960 100644 --- a/jetty-http/src/main/java/org/eclipse/jetty/http/HttpFieldPreEncoder.java +++ b/jetty-http/src/main/java/org/eclipse/jetty/http/HttpFieldPreEncoder.java @@ -16,21 +16,22 @@ // ======================================================================== // - package org.eclipse.jetty.http; - -/* ------------------------------------------------------------ */ -/** Interface to pre-encode HttpFields. Used by {@link PreEncodedHttpField} +/** + * Interface to pre-encode HttpFields. Used by {@link PreEncodedHttpField} */ public interface HttpFieldPreEncoder { - /* ------------------------------------------------------------ */ - /** The major version this encoder is for. Both HTTP/1.0 and HTTP/1.1 + + /** + * The major version this encoder is for. Both HTTP/1.0 and HTTP/1.1 * use the same field encoding, so the {@link HttpVersion#HTTP_1_0} should * be return for all HTTP/1.x encodings. + * * @return The major version this encoder is for. */ HttpVersion getHttpVersion(); + byte[] getEncodedField(HttpHeader header, String headerString, String value); } diff --git a/jetty-http/src/main/java/org/eclipse/jetty/http/HttpFields.java b/jetty-http/src/main/java/org/eclipse/jetty/http/HttpFields.java index 32dda0fd27c..55d6a4dc5eb 100644 --- a/jetty-http/src/main/java/org/eclipse/jetty/http/HttpFields.java +++ b/jetty-http/src/main/java/org/eclipse/jetty/http/HttpFields.java @@ -37,7 +37,6 @@ import org.eclipse.jetty.util.QuotedStringTokenizer; import org.eclipse.jetty.util.log.Log; import org.eclipse.jetty.util.log.Logger; - /** * HTTP Fields. A collection of HTTP header and or Trailer fields. * @@ -45,7 +44,6 @@ import org.eclipse.jetty.util.log.Logger; * single thread. * *

    The cookie handling provided by this class is guided by the Servlet specification and RFC6265. - * */ public class HttpFields implements Iterable { @@ -69,7 +67,7 @@ public class HttpFields implements Iterable */ public HttpFields(int capacity) { - _fields=new HttpField[capacity]; + _fields = new HttpField[capacity]; } /** @@ -79,8 +77,8 @@ public class HttpFields implements Iterable */ public HttpFields(HttpFields fields) { - _fields=Arrays.copyOf(fields._fields,fields._fields.length); - _size=fields._size; + _fields = Arrays.copyOf(fields._fields, fields._fields.length); + _size = fields._size; } public int size() @@ -106,24 +104,26 @@ public class HttpFields implements Iterable /** * Get Collection of header names. + * * @return the unique set of field names. */ public Set getFieldNamesCollection() { Set set = null; - for (int i=0;i<_size;i++) + for (int i = 0; i < _size; i++) { - HttpField f=_fields[i]; - if (set==null) + HttpField f = _fields[i]; + if (set == null) set = new HashSet<>(); set.add(f.getName()); } - return set==null?Collections.emptySet():set; + return set == null ? Collections.emptySet() : set; } /** * Get enumeration of header _names. Returns an enumeration of strings representing the header * _names for this request. + * * @return an enumeration of field names */ public Enumeration getFieldNames() @@ -133,22 +133,23 @@ public class HttpFields implements Iterable /** * Get a Field by index. + * * @param index the field index * @return A Field value or null if the Field value has not been set */ public HttpField getField(int index) { - if (index>=_size) + if (index >= _size) throw new NoSuchElementException(); return _fields[index]; } public HttpField getField(HttpHeader header) { - for (int i=0;i<_size;i++) + for (int i = 0; i < _size; i++) { - HttpField f=_fields[i]; - if (f.getHeader()==header) + HttpField f = _fields[i]; + if (f.getHeader() == header) return f; } return null; @@ -156,9 +157,9 @@ public class HttpFields implements Iterable public HttpField getField(String name) { - for (int i=0;i<_size;i++) + for (int i = 0; i < _size; i++) { - HttpField f=_fields[i]; + HttpField f = _fields[i]; if (f.getName().equalsIgnoreCase(name)) return f; } @@ -168,25 +169,25 @@ public class HttpFields implements Iterable public List getFields(HttpHeader header) { List fields = null; - for (int i=0;i<_size;i++) + for (int i = 0; i < _size; i++) { - HttpField f=_fields[i]; - if (f.getHeader()==header) + HttpField f = _fields[i]; + if (f.getHeader() == header) { - if (fields==null) + if (fields == null) fields = new ArrayList<>(); fields.add(f); } } - return fields==null?Collections.emptyList():fields; + return fields == null ? Collections.emptyList() : fields; } public boolean contains(HttpField field) { - for (int i=_size;i-->0;) + for (int i = _size; i-- > 0; ) { - HttpField f=_fields[i]; - if (f.isSameName(field) && (f.equals(field)||f.contains(field.getValue()))) + HttpField f = _fields[i]; + if (f.isSameName(field) && (f.equals(field) || f.contains(field.getValue()))) return true; } return false; @@ -194,10 +195,10 @@ public class HttpFields implements Iterable public boolean contains(HttpHeader header, String value) { - for (int i=_size;i-->0;) + for (int i = _size; i-- > 0; ) { - HttpField f=_fields[i]; - if (f.getHeader()==header && f.contains(value)) + HttpField f = _fields[i]; + if (f.getHeader() == header && f.contains(value)) return true; } return false; @@ -205,9 +206,9 @@ public class HttpFields implements Iterable public boolean contains(String name, String value) { - for (int i=_size;i-->0;) + for (int i = _size; i-- > 0; ) { - HttpField f=_fields[i]; + HttpField f = _fields[i]; if (f.getName().equalsIgnoreCase(name) && f.contains(value)) return true; } @@ -216,10 +217,10 @@ public class HttpFields implements Iterable public boolean contains(HttpHeader header) { - for (int i=_size;i-->0;) + for (int i = _size; i-- > 0; ) { - HttpField f=_fields[i]; - if (f.getHeader()==header) + HttpField f = _fields[i]; + if (f.getHeader() == header) return true; } return false; @@ -227,9 +228,9 @@ public class HttpFields implements Iterable public boolean containsKey(String name) { - for (int i=_size;i-->0;) + for (int i = _size; i-- > 0; ) { - HttpField f=_fields[i]; + HttpField f = _fields[i]; if (f.getName().equalsIgnoreCase(name)) return true; } @@ -238,10 +239,10 @@ public class HttpFields implements Iterable public String get(HttpHeader header) { - for (int i=0;i<_size;i++) + for (int i = 0; i < _size; i++) { - HttpField f=_fields[i]; - if (f.getHeader()==header) + HttpField f = _fields[i]; + if (f.getHeader() == header) return f.getValue(); } return null; @@ -249,9 +250,9 @@ public class HttpFields implements Iterable public String get(String header) { - for (int i=0;i<_size;i++) + for (int i = 0; i < _size; i++) { - HttpField f=_fields[i]; + HttpField f = _fields[i]; if (f.getName().equalsIgnoreCase(header)) return f.getValue(); } @@ -261,13 +262,13 @@ public class HttpFields implements Iterable /** * Get multiple header of the same name * - * @return List the values * @param header the header + * @return List the values */ public List getValuesList(HttpHeader header) { final List list = new ArrayList<>(); - for (int i=0;i<_size;i++) + for (int i = 0; i < _size; i++) { HttpField f = _fields[i]; if (f.getHeader() == header) @@ -279,13 +280,13 @@ public class HttpFields implements Iterable /** * Get multiple header of the same name * - * @return List the header values * @param name the case-insensitive field name + * @return List the header values */ public List getValuesList(String name) { final List list = new ArrayList<>(); - for (int i=0;i<_size;i++) + for (int i = 0; i < _size; i++) { HttpField f = _fields[i]; if (f.getName().equalsIgnoreCase(name)) @@ -294,32 +295,32 @@ public class HttpFields implements Iterable return list; } - /** * Add comma separated values, but only if not already * present. + * * @param header The header to add the value(s) to * @param values The value(s) to add * @return True if headers were modified */ - public boolean addCSV(HttpHeader header,String... values) + public boolean addCSV(HttpHeader header, String... values) { QuotedCSV existing = null; - for (int i=0;i<_size;i++) + for (int i = 0; i < _size; i++) { HttpField f = _fields[i]; - if (f.getHeader()==header) + if (f.getHeader() == header) { - if (existing==null) + if (existing == null) existing = new QuotedCSV(false); existing.addValue(f.getValue()); } } - String value = addCSV(existing,values); - if (value!=null) + String value = addCSV(existing, values); + if (value != null) { - add(header,value); + add(header, value); return true; } return false; @@ -328,27 +329,28 @@ public class HttpFields implements Iterable /** * Add comma separated values, but only if not already * present. + * * @param name The header to add the value(s) to * @param values The value(s) to add * @return True if headers were modified */ - public boolean addCSV(String name,String... values) + public boolean addCSV(String name, String... values) { QuotedCSV existing = null; - for (int i=0;i<_size;i++) + for (int i = 0; i < _size; i++) { HttpField f = _fields[i]; if (f.getName().equalsIgnoreCase(name)) { - if (existing==null) + if (existing == null) existing = new QuotedCSV(false); existing.addValue(f.getValue()); } } - String value = addCSV(existing,values); - if (value!=null) + String value = addCSV(existing, values); + if (value != null) { - add(name,value); + add(name, value); return true; } return false; @@ -358,11 +360,11 @@ public class HttpFields implements Iterable { // remove any existing values from the new values boolean add = true; - if (existing!=null && !existing.isEmpty()) + if (existing != null && !existing.isEmpty()) { add = false; - for (int i=values.length;i-->0;) + for (int i = values.length; i-- > 0; ) { String unquoted = QuotedCSV.unquote(values[i]); if (existing.getValues().contains(unquoted)) @@ -375,15 +377,15 @@ public class HttpFields implements Iterable if (add) { StringBuilder value = new StringBuilder(); - for (String v:values) + for (String v : values) { - if (v==null) + if (v == null) continue; - if (value.length()>0) + if (value.length() > 0) value.append(", "); value.append(v); } - if (value.length()>0) + if (value.length() > 0) return value.toString(); } @@ -394,58 +396,58 @@ public class HttpFields implements Iterable * Get multiple field values of the same name, split * as a {@link QuotedCSV} * - * @return List the values with OWS stripped * @param header The header * @param keepQuotes True if the fields are kept quoted + * @return List the values with OWS stripped */ - public List getCSV(HttpHeader header,boolean keepQuotes) + public List getCSV(HttpHeader header, boolean keepQuotes) { QuotedCSV values = null; for (HttpField f : this) { - if (f.getHeader()==header) + if (f.getHeader() == header) { - if (values==null) + if (values == null) values = new QuotedCSV(keepQuotes); values.addValue(f.getValue()); } } - return values==null?Collections.emptyList():values.getValues(); + return values == null ? Collections.emptyList() : values.getValues(); } /** * Get multiple field values of the same name * as a {@link QuotedCSV} * - * @return List the values with OWS stripped * @param name the case-insensitive field name * @param keepQuotes True if the fields are kept quoted + * @return List the values with OWS stripped */ - public List getCSV(String name,boolean keepQuotes) + public List getCSV(String name, boolean keepQuotes) { QuotedCSV values = null; for (HttpField f : this) { if (f.getName().equalsIgnoreCase(name)) { - if (values==null) + if (values == null) values = new QuotedCSV(keepQuotes); values.addValue(f.getValue()); } } - return values==null?Collections.emptyList():values.getValues(); + return values == null ? Collections.emptyList() : values.getValues(); } /** * Get multiple field values of the same name, split and * sorted as a {@link QuotedQualityCSV} * - * @return List the values in quality order with the q param and OWS stripped * @param header The header + * @return List the values in quality order with the q param and OWS stripped */ public List getQualityCSV(HttpHeader header) { - return getQualityCSV(header,null); + return getQualityCSV(header, null); } /** @@ -461,23 +463,23 @@ public class HttpFields implements Iterable QuotedQualityCSV values = null; for (HttpField f : this) { - if (f.getHeader()==header) + if (f.getHeader() == header) { - if (values==null) + if (values == null) values = new QuotedQualityCSV(secondaryOrdering); values.addValue(f.getValue()); } } - return values==null?Collections.emptyList():values.getValues(); + return values == null ? Collections.emptyList() : values.getValues(); } /** * Get multiple field values of the same name, split and * sorted as a {@link QuotedQualityCSV} * - * @return List the values in quality order with the q param and OWS stripped * @param name the case-insensitive field name + * @return List the values in quality order with the q param and OWS stripped */ public List getQualityCSV(String name) { @@ -486,46 +488,46 @@ public class HttpFields implements Iterable { if (f.getName().equalsIgnoreCase(name)) { - if (values==null) + if (values == null) values = new QuotedQualityCSV(); values.addValue(f.getValue()); } } - return values==null?Collections.emptyList():values.getValues(); + return values == null ? Collections.emptyList() : values.getValues(); } /** * Get multi headers * - * @return Enumeration of the values * @param name the case-insensitive field name + * @return Enumeration of the values */ public Enumeration getValues(final String name) { - for (int i=0;i<_size;i++) + for (int i = 0; i < _size; i++) { final HttpField f = _fields[i]; - if (f.getName().equalsIgnoreCase(name) && f.getValue()!=null) + if (f.getName().equalsIgnoreCase(name) && f.getValue() != null) { - final int first=i; + final int first = i; return new Enumeration() { - HttpField field=f; - int i = first+1; + HttpField field = f; + int i = first + 1; @Override public boolean hasMoreElements() { - if (field==null) + if (field == null) { - while (i<_size) + while (i < _size) { - field=_fields[i++]; - if (field.getName().equalsIgnoreCase(name) && field.getValue()!=null) + field = _fields[i++]; + if (field.getName().equalsIgnoreCase(name) && field.getValue() != null) return true; } - field=null; + field = null; return false; } return true; @@ -536,8 +538,8 @@ public class HttpFields implements Iterable { if (hasMoreElements()) { - String value=field.getValue(); - field=null; + String value = field.getValue(); + field = null; return value; } throw new NoSuchElementException(); @@ -546,26 +548,26 @@ public class HttpFields implements Iterable } } - List empty=Collections.emptyList(); + List empty = Collections.emptyList(); return Collections.enumeration(empty); } public void put(HttpField field) { - boolean put=false; - for (int i=_size;i-->0;) + boolean put = false; + for (int i = _size; i-- > 0; ) { - HttpField f=_fields[i]; + HttpField f = _fields[i]; if (f.isSameName(field)) { if (put) { - System.arraycopy(_fields,i+1,_fields,i,--_size-i); + System.arraycopy(_fields, i + 1, _fields, i, --_size - i); } else { - _fields[i]=field; - put=true; + _fields[i] = field; + put = true; } } } @@ -589,7 +591,7 @@ public class HttpFields implements Iterable public void put(HttpHeader header, HttpHeaderValue value) { - put(header,value.toString()); + put(header, value.toString()); } /** @@ -616,8 +618,10 @@ public class HttpFields implements Iterable { remove(name); for (String v : list) - if (v!=null) - add(name,v); + { + if (v != null) + add(name, v); + } } /** @@ -638,7 +642,7 @@ public class HttpFields implements Iterable public void add(HttpHeader header, HttpHeaderValue value) { - add(header,value.toString()); + add(header, value.toString()); } /** @@ -650,7 +654,8 @@ public class HttpFields implements Iterable */ public void add(HttpHeader header, String value) { - if (value == null) throw new IllegalArgumentException("null value"); + if (value == null) + throw new IllegalArgumentException("null value"); HttpField field = new HttpField(header, value); add(field); @@ -664,14 +669,14 @@ public class HttpFields implements Iterable */ public HttpField remove(HttpHeader name) { - HttpField removed=null; - for (int i=_size;i-->0;) + HttpField removed = null; + for (int i = _size; i-- > 0; ) { - HttpField f=_fields[i]; - if (f.getHeader()==name) + HttpField f = _fields[i]; + if (f.getHeader() == name) { - removed=f; - System.arraycopy(_fields,i+1,_fields,i,--_size-i); + removed = f; + System.arraycopy(_fields, i + 1, _fields, i, --_size - i); } } return removed; @@ -685,14 +690,14 @@ public class HttpFields implements Iterable */ public HttpField remove(String name) { - HttpField removed=null; - for (int i=_size;i-->0;) + HttpField removed = null; + for (int i = _size; i-- > 0; ) { - HttpField f=_fields[i]; + HttpField f = _fields[i]; if (f.getName().equalsIgnoreCase(name)) { - removed=f; - System.arraycopy(_fields,i+1,_fields,i,--_size-i); + removed = f; + System.arraycopy(_fields, i + 1, _fields, i, --_size - i); } } return removed; @@ -704,12 +709,12 @@ public class HttpFields implements Iterable * * @param name the case-insensitive field name * @return the value of the field as a long - * @exception NumberFormatException If bad long found + * @throws NumberFormatException If bad long found */ public long getLongField(String name) throws NumberFormatException { HttpField field = getField(name); - return field==null?-1L:field.getLongValue(); + return field == null ? -1L : field.getLongValue(); } /** @@ -730,12 +735,11 @@ public class HttpFields implements Iterable return -1; final long date = DateParser.parseDate(val); - if (date==-1) + if (date == -1) throw new IllegalArgumentException("Cannot convert date: " + val); return date; } - /** * Sets the value of an long field. * @@ -760,7 +764,6 @@ public class HttpFields implements Iterable put(name, v); } - /** * Sets the value of a date field. * @@ -769,7 +772,7 @@ public class HttpFields implements Iterable */ public void putDateField(HttpHeader name, long date) { - String d=DateGenerator.formatDate(date); + String d = DateGenerator.formatDate(date); put(name, d); } @@ -781,7 +784,7 @@ public class HttpFields implements Iterable */ public void putDateField(String name, long date) { - String d=DateGenerator.formatDate(date); + String d = DateGenerator.formatDate(date); put(name, d); } @@ -793,16 +796,18 @@ public class HttpFields implements Iterable */ public void addDateField(String name, long date) { - String d=DateGenerator.formatDate(date); - add(name,d); + String d = DateGenerator.formatDate(date); + add(name, d); } @Override public int hashCode() { - int hash=0; - for (HttpField field:_fields) - hash+=field.hashCode(); + int hash = 0; + for (HttpField field : _fields) + { + hash += field.hashCode(); + } return hash; } @@ -820,7 +825,8 @@ public class HttpFields implements Iterable if (size() != that.size()) return false; - loop: for (HttpField fi : this) + loop: + for (HttpField fi : this) { for (HttpField fa : that) { @@ -843,10 +849,12 @@ public class HttpFields implements Iterable if (field != null) { String tmp = field.getName(); - if (tmp != null) buffer.append(tmp); + if (tmp != null) + buffer.append(tmp); buffer.append(": "); tmp = field.getValue(); - if (tmp != null) buffer.append(tmp); + if (tmp != null) + buffer.append(tmp); buffer.append("\r\n"); } } @@ -862,23 +870,25 @@ public class HttpFields implements Iterable public void clear() { - _size=0; + _size = 0; } public void add(HttpField field) { - if (field!=null) + if (field != null) { - if (_size==_fields.length) - _fields=Arrays.copyOf(_fields,_size*2); - _fields[_size++]=field; + if (_size == _fields.length) + _fields = Arrays.copyOf(_fields, _size * 2); + _fields[_size++] = field; } } public void addAll(HttpFields fields) { - for (int i=0;i */ public void add(HttpFields fields) { - if (fields == null) return; + if (fields == null) + return; Enumeration e = fields.getFieldNames(); while (e.hasMoreElements()) @@ -897,7 +908,9 @@ public class HttpFields implements Iterable String name = e.nextElement(); Enumeration values = fields.getValues(name); while (values.hasMoreElements()) + { add(name, values.nextElement()); + } } } @@ -916,10 +929,12 @@ public class HttpFields implements Iterable */ public static String stripParameters(String value) { - if (value == null) return null; + if (value == null) + return null; int i = value.indexOf(';'); - if (i < 0) return value; + if (i < 0) + return value; return value.substring(0, i).trim(); } @@ -937,13 +952,16 @@ public class HttpFields implements Iterable * @param parameters A map to populate with the parameters, or null * @return The value. */ - public static String valueParameters(String value, Map parameters) + public static String valueParameters(String value, Map parameters) { - if (value == null) return null; + if (value == null) + return null; int i = value.indexOf(';'); - if (i < 0) return value; - if (parameters == null) return value.substring(0, i).trim(); + if (i < 0) + return value; + if (parameters == null) + return value.substring(0, i).trim(); StringTokenizer tok1 = new QuotedStringTokenizer(value.substring(i), ";", false, true); while (tok1.hasMoreTokens()) @@ -954,7 +972,8 @@ public class HttpFields implements Iterable { String paramName = tok2.nextToken(); String paramVal = null; - if (tok2.hasMoreTokens()) paramVal = tok2.nextToken(); + if (tok2.hasMoreTokens()) + paramVal = tok2.nextToken(); parameters.put(paramName, paramVal); } } @@ -965,7 +984,7 @@ public class HttpFields implements Iterable private class ListItr implements ListIterator { int _cursor; // index of next element to return - int _current =-1; + int _current = -1; @Override public boolean hasNext() @@ -985,19 +1004,19 @@ public class HttpFields implements Iterable @Override public void remove() { - if (_current <0) + if (_current < 0) throw new IllegalStateException(); _size--; - System.arraycopy(_fields, _current +1,_fields, _current,_size- _current); - _fields[_size]=null; - _cursor= _current; - _current =-1; + System.arraycopy(_fields, _current + 1, _fields, _current, _size - _current); + _fields[_size] = null; + _cursor = _current; + _current = -1; } @Override public boolean hasPrevious() { - return _cursor>0; + return _cursor > 0; } @Override @@ -1012,19 +1031,19 @@ public class HttpFields implements Iterable @Override public int nextIndex() { - return _cursor+1; + return _cursor + 1; } @Override public int previousIndex() { - return _cursor-1; + return _cursor - 1; } @Override public void set(HttpField field) { - if (_current <0) + if (_current < 0) throw new IllegalStateException(); _fields[_current] = field; } @@ -1032,10 +1051,10 @@ public class HttpFields implements Iterable @Override public void add(HttpField field) { - _fields = Arrays.copyOf(_fields,_fields.length+1); - System.arraycopy(_fields,_cursor,_fields,_cursor+1,_size++); + _fields = Arrays.copyOf(_fields, _fields.length + 1); + System.arraycopy(_fields, _cursor, _fields, _cursor + 1, _size++); _fields[_cursor++] = field; - _current =-1; + _current = -1; } } } diff --git a/jetty-http/src/main/java/org/eclipse/jetty/http/HttpGenerator.java b/jetty-http/src/main/java/org/eclipse/jetty/http/HttpGenerator.java index 33b6d48cd44..f55569858c1 100644 --- a/jetty-http/src/main/java/org/eclipse/jetty/http/HttpGenerator.java +++ b/jetty-http/src/main/java/org/eclipse/jetty/http/HttpGenerator.java @@ -44,27 +44,33 @@ import static org.eclipse.jetty.http.HttpStatus.INTERNAL_SERVER_ERROR_500; */ public class HttpGenerator { - private final static Logger LOG = Log.getLogger(HttpGenerator.class); + private static final Logger LOG = Log.getLogger(HttpGenerator.class); - public final static boolean __STRICT=Boolean.getBoolean("org.eclipse.jetty.http.HttpGenerator.STRICT"); + public static final boolean __STRICT = Boolean.getBoolean("org.eclipse.jetty.http.HttpGenerator.STRICT"); - private final static byte[] __colon_space = new byte[] {':',' '}; - public static final MetaData.Response CONTINUE_100_INFO = new MetaData.Response(HttpVersion.HTTP_1_1,100,null,null,-1); - public static final MetaData.Response PROGRESS_102_INFO = new MetaData.Response(HttpVersion.HTTP_1_1,102,null,null,-1); - public final static MetaData.Response RESPONSE_500_INFO = - new MetaData.Response(HttpVersion.HTTP_1_1,INTERNAL_SERVER_ERROR_500,null,new HttpFields(){{put(HttpHeader.CONNECTION,HttpHeaderValue.CLOSE);}},0); + private static final byte[] __colon_space = new byte[]{':', ' '}; + public static final MetaData.Response CONTINUE_100_INFO = new MetaData.Response(HttpVersion.HTTP_1_1, 100, null, null, -1); + public static final MetaData.Response PROGRESS_102_INFO = new MetaData.Response(HttpVersion.HTTP_1_1, 102, null, null, -1); + public static final MetaData.Response RESPONSE_500_INFO = + new MetaData.Response(HttpVersion.HTTP_1_1, INTERNAL_SERVER_ERROR_500, null, new HttpFields() + { + { + put(HttpHeader.CONNECTION, HttpHeaderValue.CLOSE); + } + }, 0); // states - public enum State - { + public enum State + { START, COMMITTED, COMPLETING, COMPLETING_1XX, END } - public enum Result - { + + public enum Result + { NEED_CHUNK, // Need a small chunk buffer of CHUNK_SIZE NEED_INFO, // Need the request/response metadata info NEED_HEADER, // Need a buffer to build HTTP headers into @@ -84,104 +90,90 @@ public class HttpGenerator private long _contentPrepared = 0; private boolean _noContentResponse = false; private Boolean _persistent = null; - private Supplier _trailers = null; + private Supplier _trailers = null; private final int _send; - private final static int SEND_SERVER = 0x01; - private final static int SEND_XPOWEREDBY = 0x02; - private final static Trie __assumedContentMethods = new ArrayTrie<>(8); + private static final int SEND_SERVER = 0x01; + private static final int SEND_XPOWEREDBY = 0x02; + private static final Trie ASSUMED_CONTENT_METHODS = new ArrayTrie<>(8); + static { - __assumedContentMethods.put(HttpMethod.POST.asString(),Boolean.TRUE); - __assumedContentMethods.put(HttpMethod.PUT.asString(),Boolean.TRUE); - } - - /* ------------------------------------------------------------------------------- */ - public static void setJettyVersion(String serverVersion) - { - SEND[SEND_SERVER] = StringUtil.getBytes("Server: " + serverVersion + "\015\012"); - SEND[SEND_XPOWEREDBY] = StringUtil.getBytes("X-Powered-By: " + serverVersion + "\015\012"); - SEND[SEND_SERVER | SEND_XPOWEREDBY] = StringUtil.getBytes("Server: " + serverVersion + "\015\012X-Powered-By: " + - serverVersion + "\015\012"); + ASSUMED_CONTENT_METHODS.put(HttpMethod.POST.asString(), Boolean.TRUE); + ASSUMED_CONTENT_METHODS.put(HttpMethod.PUT.asString(), Boolean.TRUE); + } + + public static void setJettyVersion(String serverVersion) + { + SEND[SEND_SERVER] = StringUtil.getBytes("Server: " + serverVersion + "\r\n"); + SEND[SEND_XPOWEREDBY] = StringUtil.getBytes("X-Powered-By: " + serverVersion + "\r\n"); + SEND[SEND_SERVER | SEND_XPOWEREDBY] = StringUtil.getBytes("Server: " + serverVersion + "\r\nX-Powered-By: " + serverVersion + "\r\n"); } - /* ------------------------------------------------------------------------------- */ // data private boolean _needCRLF = false; - /* ------------------------------------------------------------------------------- */ public HttpGenerator() { - this(false,false); + this(false, false); } - /* ------------------------------------------------------------------------------- */ - public HttpGenerator(boolean sendServerVersion,boolean sendXPoweredBy) + public HttpGenerator(boolean sendServerVersion, boolean sendXPoweredBy) { - _send=(sendServerVersion?SEND_SERVER:0) | (sendXPoweredBy?SEND_XPOWEREDBY:0); + _send = (sendServerVersion ? SEND_SERVER : 0) | (sendXPoweredBy ? SEND_XPOWEREDBY : 0); } - /* ------------------------------------------------------------------------------- */ public void reset() { _state = State.START; _endOfContent = EndOfContent.UNKNOWN_CONTENT; - _noContentResponse=false; + _noContentResponse = false; _persistent = null; _contentPrepared = 0; _needCRLF = false; _trailers = null; } - /* ------------------------------------------------------------ */ public State getState() { return _state; } - /* ------------------------------------------------------------ */ public boolean isState(State state) { return _state == state; } - /* ------------------------------------------------------------ */ public boolean isIdle() { return _state == State.START; } - /* ------------------------------------------------------------ */ public boolean isEnd() { return _state == State.END; } - /* ------------------------------------------------------------ */ public boolean isCommitted() { return _state.ordinal() >= State.COMMITTED.ordinal(); } - /* ------------------------------------------------------------ */ public boolean isChunking() { - return _endOfContent==EndOfContent.CHUNKED_CONTENT; + return _endOfContent == EndOfContent.CHUNKED_CONTENT; } - /* ------------------------------------------------------------ */ public boolean isNoContent() { return _noContentResponse; } - /* ------------------------------------------------------------ */ public void setPersistent(boolean persistent) { - _persistent=persistent; + _persistent = persistent; } - /* ------------------------------------------------------------ */ /** * @return true if known to be persistent */ @@ -190,50 +182,46 @@ public class HttpGenerator return Boolean.TRUE.equals(_persistent); } - /* ------------------------------------------------------------ */ public boolean isWritten() { - return _contentPrepared>0; + return _contentPrepared > 0; } - /* ------------------------------------------------------------ */ public long getContentPrepared() { return _contentPrepared; } - /* ------------------------------------------------------------ */ public void abort() { - _persistent=false; - _state=State.END; - _endOfContent=null; + _persistent = false; + _state = State.END; + _endOfContent = null; } - /* ------------------------------------------------------------ */ public Result generateRequest(MetaData.Request info, ByteBuffer header, ByteBuffer chunk, ByteBuffer content, boolean last) throws IOException { - switch(_state) + switch (_state) { case START: { - if (info==null) + if (info == null) return Result.NEED_INFO; - if (header==null) + if (header == null) return Result.NEED_HEADER; // prepare the header - int pos=BufferUtil.flipToFill(header); + int pos = BufferUtil.flipToFill(header); try { // generate ResponseLine - generateRequestLine(info,header); + generateRequestLine(info, header); - if (info.getHttpVersion()==HttpVersion.HTTP_0_9) - throw new BadMessageException(INTERNAL_SERVER_ERROR_500,"HTTP/0.9 not supported"); - - generateHeaders(info,header,content,last); + if (info.getHttpVersion() == HttpVersion.HTTP_0_9) + throw new BadMessageException(INTERNAL_SERVER_ERROR_500, "HTTP/0.9 not supported"); + + generateHeaders(info, header, content, last); boolean expect100 = info.getFields().contains(HttpHeader.EXPECT, HttpHeaderValue.CONTINUE.asString()); @@ -245,43 +233,43 @@ public class HttpGenerator { // handle the content. int len = BufferUtil.length(content); - if (len>0) + if (len > 0) { - _contentPrepared+=len; + _contentPrepared += len; if (isChunking()) - prepareChunk(header,len); + prepareChunk(header, len); } - _state = last?State.COMPLETING:State.COMMITTED; + _state = last ? State.COMPLETING : State.COMMITTED; } return Result.FLUSH; } - catch(BadMessageException e) + catch (BadMessageException e) { throw e; } - catch(BufferOverflowException e) + catch (BufferOverflowException e) { - throw new BadMessageException(INTERNAL_SERVER_ERROR_500,"Request header too large",e); + throw new BadMessageException(INTERNAL_SERVER_ERROR_500, "Request header too large", e); } - catch(Exception e) + catch (Exception e) { - throw new BadMessageException(INTERNAL_SERVER_ERROR_500,e.getMessage(),e); + throw new BadMessageException(INTERNAL_SERVER_ERROR_500, e.getMessage(), e); } finally { - BufferUtil.flipToFlush(header,pos); + BufferUtil.flipToFlush(header, pos); } } case COMMITTED: { - return committed(chunk,content,last); + return committed(chunk, content, last); } case COMPLETING: { - return completing(chunk,content); + return completing(chunk, content); } case END: @@ -298,33 +286,33 @@ public class HttpGenerator } } - private Result committed( ByteBuffer chunk, ByteBuffer content, boolean last) + private Result committed(ByteBuffer chunk, ByteBuffer content, boolean last) { int len = BufferUtil.length(content); // handle the content. - if (len>0) + if (len > 0) { if (isChunking()) { - if (chunk==null) + if (chunk == null) return Result.NEED_CHUNK; BufferUtil.clearToFill(chunk); - prepareChunk(chunk,len); - BufferUtil.flipToFlush(chunk,0); + prepareChunk(chunk, len); + BufferUtil.flipToFlush(chunk, 0); } - _contentPrepared+=len; + _contentPrepared += len; } if (last) { - _state=State.COMPLETING; - return len>0?Result.FLUSH:Result.CONTINUE; + _state = State.COMPLETING; + return len > 0 ? Result.FLUSH : Result.CONTINUE; } - return len>0?Result.FLUSH:Result.DONE; + return len > 0 ? Result.FLUSH : Result.DONE; } - - private Result completing( ByteBuffer chunk, ByteBuffer content) + + private Result completing(ByteBuffer chunk, ByteBuffer content) { if (BufferUtil.hasContent(content)) { @@ -335,121 +323,119 @@ public class HttpGenerator if (isChunking()) { - if (_trailers!=null) + if (_trailers != null) { // Do we need a chunk buffer? - if (chunk==null || chunk.capacity()<=CHUNK_SIZE) + if (chunk == null || chunk.capacity() <= CHUNK_SIZE) return Result.NEED_CHUNK_TRAILER; - + HttpFields trailers = _trailers.get(); - if (trailers!=null) + if (trailers != null) { // Write the last chunk BufferUtil.clearToFill(chunk); - generateTrailers(chunk,trailers); - BufferUtil.flipToFlush(chunk,0); - _endOfContent=EndOfContent.UNKNOWN_CONTENT; + generateTrailers(chunk, trailers); + BufferUtil.flipToFlush(chunk, 0); + _endOfContent = EndOfContent.UNKNOWN_CONTENT; return Result.FLUSH; } } // Do we need a chunk buffer? - if (chunk==null) + if (chunk == null) return Result.NEED_CHUNK; // Write the last chunk BufferUtil.clearToFill(chunk); - prepareChunk(chunk,0); - BufferUtil.flipToFlush(chunk,0); - _endOfContent=EndOfContent.UNKNOWN_CONTENT; - return Result.FLUSH; + prepareChunk(chunk, 0); + BufferUtil.flipToFlush(chunk, 0); + _endOfContent = EndOfContent.UNKNOWN_CONTENT; + return Result.FLUSH; } - _state=State.END; - return Boolean.TRUE.equals(_persistent)?Result.DONE:Result.SHUTDOWN_OUT; - + _state = State.END; + return Boolean.TRUE.equals(_persistent) ? Result.DONE : Result.SHUTDOWN_OUT; } - - /* ------------------------------------------------------------ */ + public Result generateResponse(MetaData.Response info, boolean head, ByteBuffer header, ByteBuffer chunk, ByteBuffer content, boolean last) throws IOException { - switch(_state) + switch (_state) { case START: { - if (info==null) + if (info == null) return Result.NEED_INFO; - HttpVersion version=info.getHttpVersion(); - if (version==null) - throw new BadMessageException(INTERNAL_SERVER_ERROR_500,"No version"); - - if (version==HttpVersion.HTTP_0_9) + HttpVersion version = info.getHttpVersion(); + if (version == null) + throw new BadMessageException(INTERNAL_SERVER_ERROR_500, "No version"); + + if (version == HttpVersion.HTTP_0_9) { _persistent = false; - _endOfContent=EndOfContent.EOF_CONTENT; + _endOfContent = EndOfContent.EOF_CONTENT; if (BufferUtil.hasContent(content)) - _contentPrepared+=content.remaining(); - _state = last?State.COMPLETING:State.COMMITTED; + _contentPrepared += content.remaining(); + _state = last ? State.COMPLETING : State.COMMITTED; return Result.FLUSH; } - + // Do we need a response header - if (header==null) + if (header == null) return Result.NEED_HEADER; // prepare the header - int pos=BufferUtil.flipToFill(header); + int pos = BufferUtil.flipToFill(header); try - { + { // generate ResponseLine - generateResponseLine(info,header); + generateResponseLine(info, header); // Handle 1xx and no content responses - int status=info.getStatus(); - if (status>=100 && status<200 ) + int status = info.getStatus(); + if (status >= 100 && status < 200) { - _noContentResponse=true; + _noContentResponse = true; - if (status!=HttpStatus.SWITCHING_PROTOCOLS_101 ) + if (status != HttpStatus.SWITCHING_PROTOCOLS_101) { header.put(HttpTokens.CRLF); - _state=State.COMPLETING_1XX; + _state = State.COMPLETING_1XX; return Result.FLUSH; } } - else if (status==HttpStatus.NO_CONTENT_204 || status==HttpStatus.NOT_MODIFIED_304) + else if (status == HttpStatus.NO_CONTENT_204 || status == HttpStatus.NOT_MODIFIED_304) { - _noContentResponse=true; + _noContentResponse = true; } - generateHeaders(info,header,content,last); + generateHeaders(info, header, content, last); // handle the content. int len = BufferUtil.length(content); - if (len>0) + if (len > 0) { - _contentPrepared+=len; + _contentPrepared += len; if (isChunking() && !head) - prepareChunk(header,len); + prepareChunk(header, len); } - _state = last?State.COMPLETING:State.COMMITTED; + _state = last ? State.COMPLETING : State.COMMITTED; } - catch(BadMessageException e) + catch (BadMessageException e) { throw e; } - catch(BufferOverflowException e) + catch (BufferOverflowException e) { - throw new BadMessageException(INTERNAL_SERVER_ERROR_500,"Response header too large",e); + throw new BadMessageException(INTERNAL_SERVER_ERROR_500, "Response header too large", e); } - catch(Exception e) + catch (Exception e) { - throw new BadMessageException(INTERNAL_SERVER_ERROR_500,e.getMessage(),e); + throw new BadMessageException(INTERNAL_SERVER_ERROR_500, e.getMessage(), e); } finally { - BufferUtil.flipToFlush(header,pos); + BufferUtil.flipToFlush(header, pos); } return Result.FLUSH; @@ -457,7 +443,7 @@ public class HttpGenerator case COMMITTED: { - return committed(chunk,content,last); + return committed(chunk, content, last); } case COMPLETING_1XX: @@ -468,7 +454,7 @@ public class HttpGenerator case COMPLETING: { - return completing(chunk,content); + return completing(chunk, content); } case END: @@ -485,7 +471,6 @@ public class HttpGenerator } } - /* ------------------------------------------------------------ */ private void prepareChunk(ByteBuffer chunk, int remaining) { // if we need CRLF add this to header @@ -493,20 +478,19 @@ public class HttpGenerator BufferUtil.putCRLF(chunk); // Add the chunk size to the header - if (remaining>0) + if (remaining > 0) { BufferUtil.putHexInt(chunk, remaining); BufferUtil.putCRLF(chunk); - _needCRLF=true; + _needCRLF = true; } else { chunk.put(LAST_CHUNK); - _needCRLF=false; + _needCRLF = false; } } - - /* ------------------------------------------------------------ */ + private void generateTrailers(ByteBuffer buffer, HttpFields trailer) { // if we need CRLF add this to header @@ -516,18 +500,17 @@ public class HttpGenerator // Add the chunk size to the header buffer.put(ZERO_CHUNK); - int n=trailer.size(); - for (int f=0;f1024) - reason=reason.substring(0,1024); - byte[] _bytes = StringUtil.getBytes(reason); + if (reason.length() > 1024) + reason = reason.substring(0, 1024); + byte[] bytes = StringUtil.getBytes(reason); - for (int i=_bytes.length;i-->0;) - if (_bytes[i]=='\r' || _bytes[i]=='\n') - _bytes[i]='?'; - return _bytes; + for (int i = bytes.length; i-- > 0; ) + { + if (bytes[i] == '\r' || bytes[i] == '\n') + bytes[i] = '?'; + } + return bytes; } - /* ------------------------------------------------------------ */ - private void generateHeaders(MetaData info,ByteBuffer header,ByteBuffer content,boolean last) + private void generateHeaders(MetaData info, ByteBuffer header, ByteBuffer content, boolean last) { - final MetaData.Request request=(info instanceof MetaData.Request)?(MetaData.Request)info:null; - final MetaData.Response response=(info instanceof MetaData.Response)?(MetaData.Response)info:null; - + final MetaData.Request request = (info instanceof MetaData.Request) ? (MetaData.Request)info : null; + final MetaData.Response response = (info instanceof MetaData.Response) ? (MetaData.Response)info : null; + if (LOG.isDebugEnabled()) { - LOG.debug("generateHeaders {} last={} content={}",info,last,BufferUtil.toDetailString(content)); + LOG.debug("generateHeaders {} last={} content={}", info, last, BufferUtil.toDetailString(content)); LOG.debug(info.getFields().toString()); } - + // default field values - int send=_send; - HttpField transfer_encoding=null; + int send = _send; + HttpField transferEncoding = null; boolean http11 = info.getHttpVersion() == HttpVersion.HTTP_1_1; boolean close = false; - _trailers = http11?info.getTrailerSupplier():null; - boolean chunked_hint = _trailers!=null; - boolean content_type = false; - long content_length = info.getContentLength(); - boolean content_length_field = false; + _trailers = http11 ? info.getTrailerSupplier() : null; + boolean chunkedHint = _trailers != null; + boolean contentType = false; + long contentLength = info.getContentLength(); + boolean contentLengthField = false; // Generate fields HttpFields fields = info.getFields(); if (fields != null) { - int n=fields.size(); - for (int f=0;f0 || content_length>0) + if (_contentPrepared > 0 || contentLength > 0) { - if (_contentPrepared==0 && last) + if (_contentPrepared == 0 && last) { // TODO discard content for backward compatibility with 9.3 releases // TODO review if it is still needed in 9.4 or can we just throw. content.clear(); - content_length=0; + contentLength = 0; } else - throw new BadMessageException(INTERNAL_SERVER_ERROR_500,"Content for no content response"); + throw new BadMessageException(INTERNAL_SERVER_ERROR_500, "Content for no content response"); } } // Else if we are HTTP/1.1 and the content length is unknown and we are either persistent // or it is a request with content (which cannot EOF) or the app has requested chunking - else if (http11 && (chunked_hint || content_length<0 && (_persistent || assumed_content_request))) + else if (http11 && (chunkedHint || contentLength < 0 && (_persistent || assumedContentRequest))) { // we use chunking _endOfContent = EndOfContent.CHUNKED_CONTENT; // try to use user supplied encoding as it may have other values. - if (transfer_encoding == null) + if (transferEncoding == null) header.put(TRANSFER_ENCODING_CHUNKED); - else if (transfer_encoding.toString().endsWith(HttpHeaderValue.CHUNKED.toString())) + else if (transferEncoding.toString().endsWith(HttpHeaderValue.CHUNKED.toString())) { - putTo(transfer_encoding,header); - transfer_encoding = null; + putTo(transferEncoding, header); + transferEncoding = null; } - else if (!chunked_hint) + else if (!chunkedHint) { - putTo(new HttpField(HttpHeader.TRANSFER_ENCODING,transfer_encoding.getValue()+",chunked"),header); - transfer_encoding = null; + putTo(new HttpField(HttpHeader.TRANSFER_ENCODING, transferEncoding.getValue() + ",chunked"), header); + transferEncoding = null; } else - throw new BadMessageException(INTERNAL_SERVER_ERROR_500,"Bad Transfer-Encoding"); + throw new BadMessageException(INTERNAL_SERVER_ERROR_500, "Bad Transfer-Encoding"); } // Else if we known the content length and are a request or a persistent response, - else if (content_length>=0 && (request!=null || _persistent)) + else if (contentLength >= 0 && (request != null || _persistent)) { // Use the content length _endOfContent = EndOfContent.CONTENT_LENGTH; - putContentLength(header,content_length); + putContentLength(header, contentLength); } // Else if we are a response - else if (response!=null) + else if (response != null) { // We must use EOF - even if we were trying to be persistent _endOfContent = EndOfContent.EOF_CONTENT; - _persistent=false; - if (content_length>=0 && ( content_length> 0 || assumed_content || content_length_field )) - putContentLength(header,content_length); - + _persistent = false; + if (contentLength >= 0 && (contentLength > 0 || assumedContent || contentLengthField)) + putContentLength(header, contentLength); + if (http11 && !close) header.put(CONNECTION_CLOSE); } @@ -763,41 +745,40 @@ public class HttpGenerator else { // with no way to indicate body length - throw new BadMessageException(INTERNAL_SERVER_ERROR_500,"Unknown content length for request"); + throw new BadMessageException(INTERNAL_SERVER_ERROR_500, "Unknown content length for request"); } if (LOG.isDebugEnabled()) LOG.debug(_endOfContent.toString()); - + // Add transfer encoding if it is not chunking - if (transfer_encoding!=null) + if (transferEncoding != null) { - if (chunked_hint) + if (chunkedHint) { - String v = transfer_encoding.getValue(); + String v = transferEncoding.getValue(); int c = v.lastIndexOf(','); - if (c>0 && v.lastIndexOf(HttpHeaderValue.CHUNKED.toString(),c)>c) - putTo(new HttpField(HttpHeader.TRANSFER_ENCODING,v.substring(0,c).trim()),header); + if (c > 0 && v.lastIndexOf(HttpHeaderValue.CHUNKED.toString(), c) > c) + putTo(new HttpField(HttpHeader.TRANSFER_ENCODING, v.substring(0, c).trim()), header); } else { - putTo(transfer_encoding,header); + putTo(transferEncoding, header); } } - + // Send server? - int status=response!=null?response.getStatus():-1; - if (status>199) + int status = response != null ? response.getStatus() : -1; + if (status > 199) header.put(SEND[send]); // end the header. - header.put(HttpTokens.CRLF); + header.put(HttpTokens.CRLF); } - /* ------------------------------------------------------------------------------- */ - private static void putContentLength(ByteBuffer header,long contentLength) + private static void putContentLength(ByteBuffer header, long contentLength) { - if (contentLength==0) + if (contentLength == 0) header.put(CONTENT_LENGTH_0); else { @@ -806,46 +787,38 @@ public class HttpGenerator header.put(HttpTokens.CRLF); } } - - /* ------------------------------------------------------------------------------- */ + public static byte[] getReasonBuffer(int code) { - PreparedResponse status = code<__preprepared.length?__preprepared[code]:null; - if (status!=null) + PreparedResponse status = code < __preprepared.length ? __preprepared[code] : null; + if (status != null) return status._reason; return null; } - /* ------------------------------------------------------------------------------- */ @Override public String toString() { return String.format("%s@%x{s=%s}", - getClass().getSimpleName(), - hashCode(), - _state); + getClass().getSimpleName(), + hashCode(), + _state); } - /* ------------------------------------------------------------------------------- */ - /* ------------------------------------------------------------------------------- */ - /* ------------------------------------------------------------------------------- */ // common _content - private static final byte[] ZERO_CHUNK = { (byte) '0', (byte) '\015', (byte) '\012'}; - private static final byte[] LAST_CHUNK = { (byte) '0', (byte) '\015', (byte) '\012', (byte) '\015', (byte) '\012'}; - private static final byte[] CONTENT_LENGTH_0 = StringUtil.getBytes("Content-Length: 0\015\012"); - private static final byte[] CONNECTION_CLOSE = StringUtil.getBytes("Connection: close\015\012"); - private static final byte[] HTTP_1_1_SPACE = StringUtil.getBytes(HttpVersion.HTTP_1_1+" "); - private static final byte[] TRANSFER_ENCODING_CHUNKED = StringUtil.getBytes("Transfer-Encoding: chunked\015\012"); + private static final byte[] ZERO_CHUNK = {(byte)'0', (byte)'\r', (byte)'\n'}; + private static final byte[] LAST_CHUNK = {(byte)'0', (byte)'\r', (byte)'\n', (byte)'\r', (byte)'\n'}; + private static final byte[] CONTENT_LENGTH_0 = StringUtil.getBytes("Content-Length: 0\r\n"); + private static final byte[] CONNECTION_CLOSE = StringUtil.getBytes("Connection: close\r\n"); + private static final byte[] HTTP_1_1_SPACE = StringUtil.getBytes(HttpVersion.HTTP_1_1 + " "); + private static final byte[] TRANSFER_ENCODING_CHUNKED = StringUtil.getBytes("Transfer-Encoding: chunked\r\n"); private static final byte[][] SEND = new byte[][]{ - new byte[0], - StringUtil.getBytes("Server: Jetty(10.x.x)\015\012"), - StringUtil.getBytes("X-Powered-By: Jetty(10.x.x)\015\012"), - StringUtil.getBytes("Server: Jetty(10.x.x)\015\012X-Powered-By: Jetty(10.x.x)\015\012") + new byte[0], + StringUtil.getBytes("Server: Jetty(10.x.x)\r\n"), + StringUtil.getBytes("X-Powered-By: Jetty(10.x.x)\r\n"), + StringUtil.getBytes("Server: Jetty(10.x.x)\r\nX-Powered-By: Jetty(10.x.x)\r\n") }; - /* ------------------------------------------------------------------------------- */ - /* ------------------------------------------------------------------------------- */ - /* ------------------------------------------------------------------------------- */ // Build cache of response lines for status private static class PreparedResponse { @@ -853,61 +826,65 @@ public class HttpGenerator byte[] _schemeCode; byte[] _responseLine; } - private static final PreparedResponse[] __preprepared = new PreparedResponse[HttpStatus.MAX_CODE+1]; + + private static final PreparedResponse[] __preprepared = new PreparedResponse[HttpStatus.MAX_CODE + 1]; + static { - int versionLength=HttpVersion.HTTP_1_1.toString().length(); + int versionLength = HttpVersion.HTTP_1_1.toString().length(); - for (int i=0;i<__preprepared.length;i++) + for (int i = 0; i < __preprepared.length; i++) { HttpStatus.Code code = HttpStatus.getCode(i); - if (code==null) + if (code == null) continue; - String reason=code.getMessage(); - byte[] line=new byte[versionLength+5+reason.length()+2]; - HttpVersion.HTTP_1_1.toBuffer().get(line,0,versionLength); - line[versionLength+0]=' '; - line[versionLength+1]=(byte)('0'+i/100); - line[versionLength+2]=(byte)('0'+(i%100)/10); - line[versionLength+3]=(byte)('0'+(i%10)); - line[versionLength+4]=' '; - for (int j=0;j0xff || c=='\r' || c=='\n'|| c==':') + if (c < 0 || c > 0xff || c == '\r' || c == '\n' || c == ':') buffer.put((byte)'?'); else - buffer.put((byte)(0xff&c)); + buffer.put((byte)(0xff & c)); } } - private static void putSanitisedValue(String s,ByteBuffer buffer) + private static void putSanitisedValue(String s, ByteBuffer buffer) { - int l=s.length(); - for (int i=0;i0xff || c=='\r' || c=='\n') + if (c < 0 || c > 0xff || c == '\r' || c == '\n') buffer.put((byte)' '); else - buffer.put((byte)(0xff&c)); + buffer.put((byte)(0xff & c)); } } @@ -915,21 +892,21 @@ public class HttpGenerator { if (field instanceof PreEncodedHttpField) { - ((PreEncodedHttpField)field).putTo(bufferInFillMode,HttpVersion.HTTP_1_0); + ((PreEncodedHttpField)field).putTo(bufferInFillMode, HttpVersion.HTTP_1_0); } else { - HttpHeader header=field.getHeader(); - if (header!=null) + HttpHeader header = field.getHeader(); + if (header != null) { bufferInFillMode.put(header.getBytesColonSpace()); - putSanitisedValue(field.getValue(),bufferInFillMode); + putSanitisedValue(field.getValue(), bufferInFillMode); } else { - putSanitisedName(field.getName(),bufferInFillMode); + putSanitisedName(field.getName(), bufferInFillMode); bufferInFillMode.put(__colon_space); - putSanitisedValue(field.getValue(),bufferInFillMode); + putSanitisedValue(field.getValue(), bufferInFillMode); } BufferUtil.putCRLF(bufferInFillMode); @@ -941,7 +918,7 @@ public class HttpGenerator for (HttpField field : fields) { if (field != null) - putTo(field,bufferInFillMode); + putTo(field, bufferInFillMode); } BufferUtil.putCRLF(bufferInFillMode); } diff --git a/jetty-http/src/main/java/org/eclipse/jetty/http/HttpHeader.java b/jetty-http/src/main/java/org/eclipse/jetty/http/HttpHeader.java index ac6bf2be8da..826e0cc3d45 100644 --- a/jetty-http/src/main/java/org/eclipse/jetty/http/HttpHeader.java +++ b/jetty-http/src/main/java/org/eclipse/jetty/http/HttpHeader.java @@ -24,17 +24,17 @@ import org.eclipse.jetty.util.ArrayTrie; import org.eclipse.jetty.util.StringUtil; import org.eclipse.jetty.util.Trie; - public enum HttpHeader { - /* ------------------------------------------------------------ */ - /** General Fields. + + /** + * General Fields. */ CONNECTION("Connection"), CACHE_CONTROL("Cache-Control"), DATE("Date"), PRAGMA("Pragma"), - PROXY_CONNECTION ("Proxy-Connection"), + PROXY_CONNECTION("Proxy-Connection"), TRAILER("Trailer"), TRANSFER_ENCODING("Transfer-Encoding"), UPGRADE("Upgrade"), @@ -42,8 +42,8 @@ public enum HttpHeader WARNING("Warning"), NEGOTIATE("Negotiate"), - /* ------------------------------------------------------------ */ - /** Entity Fields. + /** + * Entity Fields. */ ALLOW("Allow"), CONTENT_ENCODING("Content-Encoding"), @@ -56,8 +56,8 @@ public enum HttpHeader EXPIRES("Expires"), LAST_MODIFIED("Last-Modified"), - /* ------------------------------------------------------------ */ - /** Request Fields. + /** + * Request Fields. */ ACCEPT("Accept"), ACCEPT_CHARSET("Accept-Charset"), @@ -87,8 +87,8 @@ public enum HttpHeader X_FORWARDED_SERVER("X-Forwarded-Server"), X_FORWARDED_HOST("X-Forwarded-Host"), - /* ------------------------------------------------------------ */ - /** Response Fields. + /** + * Response Fields. */ ACCEPT_RANGES("Accept-Ranges"), AGE("Age"), @@ -101,8 +101,8 @@ public enum HttpHeader VARY("Vary"), WWW_AUTHENTICATE("WWW-Authenticate"), - /* ------------------------------------------------------------ */ - /** WebSocket Fields. + /** + * WebSocket Fields. */ ORIGIN("Origin"), SEC_WEBSOCKET_KEY("Sec-WebSocket-Key"), @@ -111,92 +111,85 @@ public enum HttpHeader SEC_WEBSOCKET_SUBPROTOCOL("Sec-WebSocket-Protocol"), SEC_WEBSOCKET_ACCEPT("Sec-WebSocket-Accept"), - /* ------------------------------------------------------------ */ - /** Other Fields. + /** + * Other Fields. */ COOKIE("Cookie"), SET_COOKIE("Set-Cookie"), SET_COOKIE2("Set-Cookie2"), MIME_VERSION("MIME-Version"), IDENTITY("identity"), - + X_POWERED_BY("X-Powered-By"), HTTP2_SETTINGS("HTTP2-Settings"), STRICT_TRANSPORT_SECURITY("Strict-Transport-Security"), - - /* ------------------------------------------------------------ */ - /** HTTP2 Fields. + + /** + * HTTP2 Fields. */ C_METHOD(":method"), C_SCHEME(":scheme"), C_AUTHORITY(":authority"), C_PATH(":path"), C_STATUS(":status"), - + UNKNOWN("::UNKNOWN::"); + public static final Trie CACHE = new ArrayTrie<>(630); - /* ------------------------------------------------------------ */ - public final static Trie CACHE= new ArrayTrie<>(630); static { for (HttpHeader header : HttpHeader.values()) - if (header!=UNKNOWN) - if (!CACHE.put(header.toString(),header)) + { + if (header != UNKNOWN) + if (!CACHE.put(header.toString(), header)) throw new IllegalStateException(); + } } - + private final String _string; private final byte[] _bytes; private final byte[] _bytesColonSpace; private final ByteBuffer _buffer; - /* ------------------------------------------------------------ */ HttpHeader(String s) { - _string=s; - _bytes=StringUtil.getBytes(s); - _bytesColonSpace=StringUtil.getBytes(s+": "); - _buffer=ByteBuffer.wrap(_bytes); + _string = s; + _bytes = StringUtil.getBytes(s); + _bytesColonSpace = StringUtil.getBytes(s + ": "); + _buffer = ByteBuffer.wrap(_bytes); } - /* ------------------------------------------------------------ */ public ByteBuffer toBuffer() { return _buffer.asReadOnlyBuffer(); } - /* ------------------------------------------------------------ */ public byte[] getBytes() { return _bytes; } - /* ------------------------------------------------------------ */ public byte[] getBytesColonSpace() { return _bytesColonSpace; } - /* ------------------------------------------------------------ */ public boolean is(String s) { - return _string.equalsIgnoreCase(s); + return _string.equalsIgnoreCase(s); } - /* ------------------------------------------------------------ */ public String asString() { return _string; } - - /* ------------------------------------------------------------ */ + @Override public String toString() { return _string; } - } diff --git a/jetty-http/src/main/java/org/eclipse/jetty/http/HttpHeaderValue.java b/jetty-http/src/main/java/org/eclipse/jetty/http/HttpHeaderValue.java index e5f10b04605..996b070cdd5 100644 --- a/jetty-http/src/main/java/org/eclipse/jetty/http/HttpHeaderValue.java +++ b/jetty-http/src/main/java/org/eclipse/jetty/http/HttpHeaderValue.java @@ -25,9 +25,8 @@ import org.eclipse.jetty.util.ArrayTrie; import org.eclipse.jetty.util.BufferUtil; import org.eclipse.jetty.util.Trie; - /** - * + * */ public enum HttpHeaderValue { @@ -44,60 +43,55 @@ public enum HttpHeaderValue UPGRADE("Upgrade"), UNKNOWN("::UNKNOWN::"); - /* ------------------------------------------------------------ */ - public final static Trie CACHE= new ArrayTrie(); + public static final Trie CACHE = new ArrayTrie(); + static { for (HttpHeaderValue value : HttpHeaderValue.values()) - if (value!=UNKNOWN) - CACHE.put(value.toString(),value); + { + if (value != UNKNOWN) + CACHE.put(value.toString(), value); + } } private final String _string; private final ByteBuffer _buffer; - /* ------------------------------------------------------------ */ HttpHeaderValue(String s) { - _string=s; - _buffer=BufferUtil.toBuffer(s); + _string = s; + _buffer = BufferUtil.toBuffer(s); } - /* ------------------------------------------------------------ */ public ByteBuffer toBuffer() { return _buffer.asReadOnlyBuffer(); } - /* ------------------------------------------------------------ */ public boolean is(String s) { return _string.equalsIgnoreCase(s); } - - /* ------------------------------------------------------------ */ + public String asString() { return _string; } - /* ------------------------------------------------------------ */ @Override public String toString() { return _string; } - /* ------------------------------------------------------------ */ private static EnumSet __known = - EnumSet.of(HttpHeader.CONNECTION, - HttpHeader.TRANSFER_ENCODING, - HttpHeader.CONTENT_ENCODING); + EnumSet.of(HttpHeader.CONNECTION, + HttpHeader.TRANSFER_ENCODING, + HttpHeader.CONTENT_ENCODING); - /* ------------------------------------------------------------ */ public static boolean hasKnownValues(HttpHeader header) { - if (header==null) + if (header == null) return false; return __known.contains(header); } diff --git a/jetty-http/src/main/java/org/eclipse/jetty/http/HttpMethod.java b/jetty-http/src/main/java/org/eclipse/jetty/http/HttpMethod.java index e529eff2c51..741be954df5 100644 --- a/jetty-http/src/main/java/org/eclipse/jetty/http/HttpMethod.java +++ b/jetty-http/src/main/java/org/eclipse/jetty/http/HttpMethod.java @@ -25,9 +25,8 @@ import org.eclipse.jetty.util.ArrayTrie; import org.eclipse.jetty.util.StringUtil; import org.eclipse.jetty.util.Trie; - -/* ------------------------------------------------------------------------------- */ /** + * */ public enum HttpMethod { @@ -43,9 +42,9 @@ public enum HttpMethod PROXY, PRI; - /* ------------------------------------------------------------ */ /** * Optimized lookup to find a method name and trailing space in a byte array. + * * @param bytes Array containing ISO-8859-1 characters * @param position The first valid index * @param limit The first non valid index @@ -53,51 +52,51 @@ public enum HttpMethod */ public static HttpMethod lookAheadGet(byte[] bytes, final int position, int limit) { - int length=limit-position; - if (length<4) + int length = limit - position; + if (length < 4) return null; - switch(bytes[position]) + switch (bytes[position]) { case 'G': - if (bytes[position+1]=='E' && bytes[position+2]=='T' && bytes[position+3]==' ') + if (bytes[position + 1] == 'E' && bytes[position + 2] == 'T' && bytes[position + 3] == ' ') return GET; break; case 'P': - if (bytes[position+1]=='O' && bytes[position+2]=='S' && bytes[position+3]=='T' && length>=5 && bytes[position+4]==' ') + if (bytes[position + 1] == 'O' && bytes[position + 2] == 'S' && bytes[position + 3] == 'T' && length >= 5 && bytes[position + 4] == ' ') return POST; - if (bytes[position+1]=='R' && bytes[position+2]=='O' && bytes[position+3]=='X' && length>=6 && bytes[position+4]=='Y' && bytes[position+5]==' ') + if (bytes[position + 1] == 'R' && bytes[position + 2] == 'O' && bytes[position + 3] == 'X' && length >= 6 && bytes[position + 4] == 'Y' && bytes[position + 5] == ' ') return PROXY; - if (bytes[position+1]=='U' && bytes[position+2]=='T' && bytes[position+3]==' ') + if (bytes[position + 1] == 'U' && bytes[position + 2] == 'T' && bytes[position + 3] == ' ') return PUT; - if (bytes[position+1]=='R' && bytes[position+2]=='I' && bytes[position+3]==' ') + if (bytes[position + 1] == 'R' && bytes[position + 2] == 'I' && bytes[position + 3] == ' ') return PRI; break; case 'H': - if (bytes[position+1]=='E' && bytes[position+2]=='A' && bytes[position+3]=='D' && length>=5 && bytes[position+4]==' ') + if (bytes[position + 1] == 'E' && bytes[position + 2] == 'A' && bytes[position + 3] == 'D' && length >= 5 && bytes[position + 4] == ' ') return HEAD; break; case 'O': - if (bytes[position+1]=='P' && bytes[position+2]=='T' && bytes[position+3]=='I' && length>=8 && - bytes[position+4]=='O' && bytes[position+5]=='N' && bytes[position+6]=='S' && bytes[position+7]==' ' ) + if (bytes[position + 1] == 'P' && bytes[position + 2] == 'T' && bytes[position + 3] == 'I' && length >= 8 && + bytes[position + 4] == 'O' && bytes[position + 5] == 'N' && bytes[position + 6] == 'S' && bytes[position + 7] == ' ') return OPTIONS; break; case 'D': - if (bytes[position+1]=='E' && bytes[position+2]=='L' && bytes[position+3]=='E' && length>=7 && - bytes[position+4]=='T' && bytes[position+5]=='E' && bytes[position+6]==' ' ) + if (bytes[position + 1] == 'E' && bytes[position + 2] == 'L' && bytes[position + 3] == 'E' && length >= 7 && + bytes[position + 4] == 'T' && bytes[position + 5] == 'E' && bytes[position + 6] == ' ') return DELETE; break; case 'T': - if (bytes[position+1]=='R' && bytes[position+2]=='A' && bytes[position+3]=='C' && length>=6 && - bytes[position+4]=='E' && bytes[position+5]==' ' ) + if (bytes[position + 1] == 'R' && bytes[position + 2] == 'A' && bytes[position + 3] == 'C' && length >= 6 && + bytes[position + 4] == 'E' && bytes[position + 5] == ' ') return TRACE; break; case 'C': - if (bytes[position+1]=='O' && bytes[position+2]=='N' && bytes[position+3]=='N' && length>=8 && - bytes[position+4]=='E' && bytes[position+5]=='C' && bytes[position+6]=='T' && bytes[position+7]==' ' ) + if (bytes[position + 1] == 'O' && bytes[position + 2] == 'N' && bytes[position + 3] == 'N' && length >= 8 && + bytes[position + 4] == 'E' && bytes[position + 5] == 'C' && bytes[position + 6] == 'T' && bytes[position + 7] == ' ') return CONNECT; break; case 'M': - if (bytes[position+1]=='O' && bytes[position+2]=='V' && bytes[position+3]=='E' && length>=5 && bytes[position+4]==' ') + if (bytes[position + 1] == 'O' && bytes[position + 2] == 'V' && bytes[position + 3] == 'E' && length >= 5 && bytes[position + 4] == ' ') return MOVE; break; @@ -107,85 +106,83 @@ public enum HttpMethod return null; } - /* ------------------------------------------------------------ */ /** * Optimized lookup to find a method name and trailing space in a byte array. + * * @param buffer buffer containing ISO-8859-1 characters, it is not modified. * @return A HttpMethod if a match or null if no easy match. */ public static HttpMethod lookAheadGet(ByteBuffer buffer) { if (buffer.hasArray()) - return lookAheadGet(buffer.array(),buffer.arrayOffset()+buffer.position(),buffer.arrayOffset()+buffer.limit()); - + return lookAheadGet(buffer.array(), buffer.arrayOffset() + buffer.position(), buffer.arrayOffset() + buffer.limit()); + int l = buffer.remaining(); - if (l>=4) + if (l >= 4) { - HttpMethod m = CACHE.getBest(buffer,0,l); - if (m!=null) + HttpMethod m = CACHE.getBest(buffer, 0, l); + if (m != null) { int ml = m.asString().length(); - if (l>ml && buffer.get(buffer.position()+ml)==' ') + if (l > ml && buffer.get(buffer.position() + ml) == ' ') return m; } } return null; } - /* ------------------------------------------------------------ */ - public final static Trie INSENSITIVE_CACHE= new ArrayTrie<>(); + public static final Trie INSENSITIVE_CACHE = new ArrayTrie<>(); + static { for (HttpMethod method : HttpMethod.values()) - INSENSITIVE_CACHE.put(method.toString(),method); + { + INSENSITIVE_CACHE.put(method.toString(), method); + } } - /* ------------------------------------------------------------ */ - public final static Trie CACHE= new ArrayTernaryTrie<>(false); + public static final Trie CACHE = new ArrayTernaryTrie<>(false); + static { for (HttpMethod method : HttpMethod.values()) - CACHE.put(method.toString(),method); + { + CACHE.put(method.toString(), method); + } } - /* ------------------------------------------------------------ */ private final ByteBuffer _buffer; private final byte[] _bytes; - /* ------------------------------------------------------------ */ HttpMethod() { - _bytes=StringUtil.getBytes(toString()); - _buffer=ByteBuffer.wrap(_bytes); + _bytes = StringUtil.getBytes(toString()); + _buffer = ByteBuffer.wrap(_bytes); } - /* ------------------------------------------------------------ */ public byte[] getBytes() { return _bytes; } - /* ------------------------------------------------------------ */ public boolean is(String s) { return toString().equalsIgnoreCase(s); } - /* ------------------------------------------------------------ */ public ByteBuffer asBuffer() { return _buffer.asReadOnlyBuffer(); } - /* ------------------------------------------------------------ */ public String asString() { return toString(); } - /* ------------------------------------------------------------ */ /** * Converts the given String parameter to an HttpMethod + * * @param method the String to get the equivalent HttpMethod from * @return the HttpMethod or null if the parameter method is unknown */ diff --git a/jetty-http/src/main/java/org/eclipse/jetty/http/HttpParser.java b/jetty-http/src/main/java/org/eclipse/jetty/http/HttpParser.java index 17e60d78e6f..7e02a2e1180 100644 --- a/jetty-http/src/main/java/org/eclipse/jetty/http/HttpParser.java +++ b/jetty-http/src/main/java/org/eclipse/jetty/http/HttpParser.java @@ -41,9 +41,8 @@ import static org.eclipse.jetty.http.HttpCompliance.Violation.NO_COLON_AFTER_FIE import static org.eclipse.jetty.http.HttpCompliance.Violation.TRANSFER_ENCODING_WITH_CONTENT_LENGTH; import static org.eclipse.jetty.http.HttpCompliance.Violation.WHITESPACE_AFTER_FIELD_NAME; - -/* ------------------------------------------------------------ */ -/** A Parser for 1.0 and 1.1 as defined by RFC7230 +/** + * A Parser for 1.0 and 1.1 as defined by RFC7230 *

    * This parser parses HTTP client and server messages from buffers * passed in the {@link #parseNext(ByteBuffer)} method. The parsed @@ -84,27 +83,28 @@ import static org.eclipse.jetty.http.HttpCompliance.Violation.WHITESPACE_AFTER_F * exact case of header names, bypassing the header caches, which are case insensitive, * otherwise equivalent to RFC2616 *

    + * * @see RFC 7230 */ public class HttpParser { public static final Logger LOG = Log.getLogger(HttpParser.class); - public final static int INITIAL_URI_LENGTH=256; - private final static int MAX_CHUNK_LENGTH=Integer.MAX_VALUE/16-16; + public static final int INITIAL_URI_LENGTH = 256; + private static final int MAX_CHUNK_LENGTH = Integer.MAX_VALUE / 16 - 16; /** * Cache of common {@link HttpField}s including:
      *
    • Common static combinations such as:
        - *
      • Connection: close - *
      • Accept-Encoding: gzip - *
      • Content-Length: 0 + *
      • Connection: close + *
      • Accept-Encoding: gzip + *
      • Content-Length: 0 *
      *
    • Combinations of Content-Type header for common mime types by common charsets *
    • Most common headers with null values so that a lookup will at least * determine the header name even if the name:value combination is not cached *
    */ - public final static Trie CACHE = new ArrayTrie<>(2048); + public static final Trie CACHE = new ArrayTrie<>(2048); // States public enum FieldState @@ -115,7 +115,7 @@ public class HttpParser IN_VALUE, WS_AFTER_NAME, } - + // States public enum State { @@ -142,10 +142,10 @@ public class HttpParser CLOSED // The associated stream/endpoint is at EOF } - private final static EnumSet __idleStates = EnumSet.of(State.START,State.END,State.CLOSE,State.CLOSED); - private final static EnumSet __completeStates = EnumSet.of(State.END,State.CLOSE,State.CLOSED); + private static final EnumSet __idleStates = EnumSet.of(State.START, State.END, State.CLOSE, State.CLOSED); + private static final EnumSet __completeStates = EnumSet.of(State.END, State.CLOSE, State.CLOSED); - private final boolean DEBUG=LOG.isDebugEnabled(); // Cache debug to help branch prediction + private final boolean debugEnabled = LOG.isDebugEnabled(); // Cache debug to help branch prediction private final HttpHandler _handler; private final RequestHandler _requestHandler; private final ResponseHandler _responseHandler; @@ -161,14 +161,13 @@ public class HttpParser private boolean _host; private boolean _headerComplete; - /* ------------------------------------------------------------------------------- */ - private volatile State _state=State.START; - private volatile FieldState _fieldState=FieldState.FIELD; + private volatile State _state = State.START; + private volatile FieldState _fieldState = FieldState.FIELD; private volatile boolean _eof; private HttpMethod _method; private String _methodString; private HttpVersion _version; - private Utf8StringBuilder _uri=new Utf8StringBuilder(INITIAL_URI_LENGTH); // Tune? + private Utf8StringBuilder _uri = new Utf8StringBuilder(INITIAL_URI_LENGTH); // Tune? private EndOfContent _endOfContent; private boolean _hasContentLength; private long _contentLength = -1; @@ -181,55 +180,59 @@ public class HttpParser private Trie _fieldCache; private int _length; - private final StringBuilder _string=new StringBuilder(); + private final StringBuilder _string = new StringBuilder(); static { - CACHE.put(new HttpField(HttpHeader.CONNECTION,HttpHeaderValue.CLOSE)); - CACHE.put(new HttpField(HttpHeader.CONNECTION,HttpHeaderValue.KEEP_ALIVE)); - CACHE.put(new HttpField(HttpHeader.CONNECTION,HttpHeaderValue.UPGRADE)); - CACHE.put(new HttpField(HttpHeader.ACCEPT_ENCODING,"gzip")); - CACHE.put(new HttpField(HttpHeader.ACCEPT_ENCODING,"gzip, deflate")); - CACHE.put(new HttpField(HttpHeader.ACCEPT_ENCODING,"gzip, deflate, br")); - CACHE.put(new HttpField(HttpHeader.ACCEPT_ENCODING,"gzip,deflate,sdch")); - CACHE.put(new HttpField(HttpHeader.ACCEPT_LANGUAGE,"en-US,en;q=0.5")); - CACHE.put(new HttpField(HttpHeader.ACCEPT_LANGUAGE,"en-GB,en-US;q=0.8,en;q=0.6")); - CACHE.put(new HttpField(HttpHeader.ACCEPT_LANGUAGE,"en-AU,en;q=0.9,it-IT;q=0.8,it;q=0.7,en-GB;q=0.6,en-US;q=0.5")); - CACHE.put(new HttpField(HttpHeader.ACCEPT_CHARSET,"ISO-8859-1,utf-8;q=0.7,*;q=0.3")); - CACHE.put(new HttpField(HttpHeader.ACCEPT,"*/*")); - CACHE.put(new HttpField(HttpHeader.ACCEPT,"image/png,image/*;q=0.8,*/*;q=0.5")); - CACHE.put(new HttpField(HttpHeader.ACCEPT,"text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8")); - CACHE.put(new HttpField(HttpHeader.ACCEPT,"text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8")); - CACHE.put(new HttpField(HttpHeader.ACCEPT_RANGES,HttpHeaderValue.BYTES)); - CACHE.put(new HttpField(HttpHeader.PRAGMA,"no-cache")); - CACHE.put(new HttpField(HttpHeader.CACHE_CONTROL,"private, no-cache, no-cache=Set-Cookie, proxy-revalidate")); - CACHE.put(new HttpField(HttpHeader.CACHE_CONTROL,"no-cache")); - CACHE.put(new HttpField(HttpHeader.CACHE_CONTROL,"max-age=0")); - CACHE.put(new HttpField(HttpHeader.CONTENT_LENGTH,"0")); - CACHE.put(new HttpField(HttpHeader.CONTENT_ENCODING,"gzip")); - CACHE.put(new HttpField(HttpHeader.CONTENT_ENCODING,"deflate")); - CACHE.put(new HttpField(HttpHeader.TRANSFER_ENCODING,"chunked")); - CACHE.put(new HttpField(HttpHeader.EXPIRES,"Fri, 01 Jan 1990 00:00:00 GMT")); + CACHE.put(new HttpField(HttpHeader.CONNECTION, HttpHeaderValue.CLOSE)); + CACHE.put(new HttpField(HttpHeader.CONNECTION, HttpHeaderValue.KEEP_ALIVE)); + CACHE.put(new HttpField(HttpHeader.CONNECTION, HttpHeaderValue.UPGRADE)); + CACHE.put(new HttpField(HttpHeader.ACCEPT_ENCODING, "gzip")); + CACHE.put(new HttpField(HttpHeader.ACCEPT_ENCODING, "gzip, deflate")); + CACHE.put(new HttpField(HttpHeader.ACCEPT_ENCODING, "gzip, deflate, br")); + CACHE.put(new HttpField(HttpHeader.ACCEPT_ENCODING, "gzip,deflate,sdch")); + CACHE.put(new HttpField(HttpHeader.ACCEPT_LANGUAGE, "en-US,en;q=0.5")); + CACHE.put(new HttpField(HttpHeader.ACCEPT_LANGUAGE, "en-GB,en-US;q=0.8,en;q=0.6")); + CACHE.put(new HttpField(HttpHeader.ACCEPT_LANGUAGE, "en-AU,en;q=0.9,it-IT;q=0.8,it;q=0.7,en-GB;q=0.6,en-US;q=0.5")); + CACHE.put(new HttpField(HttpHeader.ACCEPT_CHARSET, "ISO-8859-1,utf-8;q=0.7,*;q=0.3")); + CACHE.put(new HttpField(HttpHeader.ACCEPT, "*/*")); + CACHE.put(new HttpField(HttpHeader.ACCEPT, "image/png,image/*;q=0.8,*/*;q=0.5")); + CACHE.put(new HttpField(HttpHeader.ACCEPT, "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8")); + CACHE.put(new HttpField(HttpHeader.ACCEPT, "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8")); + CACHE.put(new HttpField(HttpHeader.ACCEPT_RANGES, HttpHeaderValue.BYTES)); + CACHE.put(new HttpField(HttpHeader.PRAGMA, "no-cache")); + CACHE.put(new HttpField(HttpHeader.CACHE_CONTROL, "private, no-cache, no-cache=Set-Cookie, proxy-revalidate")); + CACHE.put(new HttpField(HttpHeader.CACHE_CONTROL, "no-cache")); + CACHE.put(new HttpField(HttpHeader.CACHE_CONTROL, "max-age=0")); + CACHE.put(new HttpField(HttpHeader.CONTENT_LENGTH, "0")); + CACHE.put(new HttpField(HttpHeader.CONTENT_ENCODING, "gzip")); + CACHE.put(new HttpField(HttpHeader.CONTENT_ENCODING, "deflate")); + CACHE.put(new HttpField(HttpHeader.TRANSFER_ENCODING, "chunked")); + CACHE.put(new HttpField(HttpHeader.EXPIRES, "Fri, 01 Jan 1990 00:00:00 GMT")); // Add common Content types as fields - for (String type : new String[]{"text/plain","text/html","text/xml","text/json","application/json","application/x-www-form-urlencoded"}) + for (String type : new String[]{ + "text/plain", "text/html", "text/xml", "text/json", "application/json", "application/x-www-form-urlencoded" + }) { - HttpField field=new PreEncodedHttpField(HttpHeader.CONTENT_TYPE,type); + HttpField field = new PreEncodedHttpField(HttpHeader.CONTENT_TYPE, type); CACHE.put(field); - for (String charset : new String[]{"utf-8","iso-8859-1"}) + for (String charset : new String[]{"utf-8", "iso-8859-1"}) { - CACHE.put(new PreEncodedHttpField(HttpHeader.CONTENT_TYPE,type+";charset="+charset)); - CACHE.put(new PreEncodedHttpField(HttpHeader.CONTENT_TYPE,type+"; charset="+charset)); - CACHE.put(new PreEncodedHttpField(HttpHeader.CONTENT_TYPE,type+";charset="+charset.toUpperCase(Locale.ENGLISH))); - CACHE.put(new PreEncodedHttpField(HttpHeader.CONTENT_TYPE,type+"; charset="+charset.toUpperCase(Locale.ENGLISH))); + CACHE.put(new PreEncodedHttpField(HttpHeader.CONTENT_TYPE, type + ";charset=" + charset)); + CACHE.put(new PreEncodedHttpField(HttpHeader.CONTENT_TYPE, type + "; charset=" + charset)); + CACHE.put(new PreEncodedHttpField(HttpHeader.CONTENT_TYPE, type + ";charset=" + charset.toUpperCase(Locale.ENGLISH))); + CACHE.put(new PreEncodedHttpField(HttpHeader.CONTENT_TYPE, type + "; charset=" + charset.toUpperCase(Locale.ENGLISH))); } } // Add headers with null values so HttpParser can avoid looking up name again for unknown values - for (HttpHeader h:HttpHeader.values()) - if (!CACHE.put(new HttpField(h,(String)null))) + for (HttpHeader h : HttpHeader.values()) + { + if (!CACHE.put(new HttpField(h, (String)null))) throw new IllegalStateException("CACHE FULL"); + } } private static HttpCompliance compliance() @@ -237,60 +240,51 @@ public class HttpParser return HttpCompliance.RFC7230; } - /* ------------------------------------------------------------------------------- */ public HttpParser(RequestHandler handler) { - this(handler,-1,compliance()); + this(handler, -1, compliance()); } - /* ------------------------------------------------------------------------------- */ public HttpParser(ResponseHandler handler) { - this(handler,-1,compliance()); + this(handler, -1, compliance()); } - /* ------------------------------------------------------------------------------- */ - public HttpParser(RequestHandler handler,int maxHeaderBytes) + public HttpParser(RequestHandler handler, int maxHeaderBytes) { - this(handler,maxHeaderBytes,compliance()); + this(handler, maxHeaderBytes, compliance()); } - /* ------------------------------------------------------------------------------- */ - public HttpParser(ResponseHandler handler,int maxHeaderBytes) + public HttpParser(ResponseHandler handler, int maxHeaderBytes) { - this(handler,maxHeaderBytes,compliance()); + this(handler, maxHeaderBytes, compliance()); } - /* ------------------------------------------------------------------------------- */ - public HttpParser(RequestHandler handler,HttpCompliance compliance) + public HttpParser(RequestHandler handler, HttpCompliance compliance) { - this(handler,-1,compliance); + this(handler, -1, compliance); } - /* ------------------------------------------------------------------------------- */ - public HttpParser(RequestHandler handler,int maxHeaderBytes,HttpCompliance compliance) + public HttpParser(RequestHandler handler, int maxHeaderBytes, HttpCompliance compliance) { - this(handler,null,maxHeaderBytes,compliance==null?compliance():compliance); + this(handler, null, maxHeaderBytes, compliance == null ? compliance() : compliance); } - /* ------------------------------------------------------------------------------- */ - public HttpParser(ResponseHandler handler,int maxHeaderBytes,HttpCompliance compliance) + public HttpParser(ResponseHandler handler, int maxHeaderBytes, HttpCompliance compliance) { - this(null,handler,maxHeaderBytes,compliance==null?compliance():compliance); + this(null, handler, maxHeaderBytes, compliance == null ? compliance() : compliance); } - /* ------------------------------------------------------------------------------- */ - private HttpParser(RequestHandler requestHandler,ResponseHandler responseHandler,int maxHeaderBytes,HttpCompliance compliance) + private HttpParser(RequestHandler requestHandler, ResponseHandler responseHandler, int maxHeaderBytes, HttpCompliance compliance) { - _handler=requestHandler!=null?requestHandler:responseHandler; - _requestHandler=requestHandler; - _responseHandler=responseHandler; - _maxHeaderBytes=maxHeaderBytes; - _complianceMode =compliance; - _complianceListener =(ComplianceViolation.Listener)(_handler instanceof ComplianceViolation.Listener?_handler:null); + _handler = requestHandler != null ? requestHandler : responseHandler; + _requestHandler = requestHandler; + _responseHandler = responseHandler; + _maxHeaderBytes = maxHeaderBytes; + _complianceMode = compliance; + _complianceListener = (ComplianceViolation.Listener)(_handler instanceof ComplianceViolation.Listener ? _handler : null); } - /* ------------------------------------------------------------------------------- */ public HttpHandler getHandler() { return _handler; @@ -301,144 +295,128 @@ public class HttpParser if (violation.isAllowedBy(_complianceMode)) reportComplianceViolation(violation, violation.getDescription()); else - throw new BadMessageException(HttpStatus.BAD_REQUEST_400,violation.getDescription()); + throw new BadMessageException(HttpStatus.BAD_REQUEST_400, violation.getDescription()); } - /* ------------------------------------------------------------------------------- */ protected void reportComplianceViolation(Violation violation) { - reportComplianceViolation(violation,violation.getDescription()); + reportComplianceViolation(violation, violation.getDescription()); } - /* ------------------------------------------------------------------------------- */ protected void reportComplianceViolation(Violation violation, String reason) { - if (_complianceListener !=null) - _complianceListener.onComplianceViolation(_complianceMode,violation,reason); + if (_complianceListener != null) + _complianceListener.onComplianceViolation(_complianceMode, violation, reason); } - /* ------------------------------------------------------------------------------- */ protected String caseInsensitiveHeader(String orig, String normative) { if (CASE_SENSITIVE_FIELD_NAME.isAllowedBy(_complianceMode)) return normative; if (!orig.equals(normative)) - reportComplianceViolation(CASE_SENSITIVE_FIELD_NAME,orig); + reportComplianceViolation(CASE_SENSITIVE_FIELD_NAME, orig); return orig; } - - /* ------------------------------------------------------------------------------- */ + public long getContentLength() { return _contentLength; } - /* ------------------------------------------------------------ */ public long getContentRead() { return _contentPosition; } - /* ------------------------------------------------------------ */ - /** Set if a HEAD response is expected + /** + * Set if a HEAD response is expected + * * @param head true if head response is expected */ public void setHeadResponse(boolean head) { - _headResponse=head; + _headResponse = head; } - /* ------------------------------------------------------------------------------- */ protected void setResponseStatus(int status) { - _responseStatus=status; + _responseStatus = status; } - /* ------------------------------------------------------------------------------- */ public State getState() { return _state; } - /* ------------------------------------------------------------------------------- */ public boolean inContentState() { - return _state.ordinal()>=State.CONTENT.ordinal() && _state.ordinal()= State.CONTENT.ordinal() && _state.ordinal() < State.END.ordinal(); } - /* ------------------------------------------------------------------------------- */ public boolean inHeaderState() { return _state.ordinal() < State.CONTENT.ordinal(); } - /* ------------------------------------------------------------------------------- */ public boolean isChunking() { - return _endOfContent==EndOfContent.CHUNKED_CONTENT; + return _endOfContent == EndOfContent.CHUNKED_CONTENT; } - /* ------------------------------------------------------------ */ public boolean isStart() { return isState(State.START); } - /* ------------------------------------------------------------ */ public boolean isClose() { return isState(State.CLOSE); } - /* ------------------------------------------------------------ */ public boolean isClosed() { return isState(State.CLOSED); } - /* ------------------------------------------------------------ */ public boolean isIdle() { return __idleStates.contains(_state); } - /* ------------------------------------------------------------ */ public boolean isComplete() { return __completeStates.contains(_state); } - /* ------------------------------------------------------------------------------- */ public boolean isState(State state) { return _state == state; } - /* ------------------------------------------------------------------------------- */ private HttpTokens.Token next(ByteBuffer buffer) { byte ch = buffer.get(); HttpTokens.Token t = HttpTokens.TOKENS[0xff & ch]; - - switch(t.getType()) + + switch (t.getType()) { case CNTL: - throw new IllegalCharacterException(_state,t,buffer); + throw new IllegalCharacterException(_state, t, buffer); case LF: - _cr=false; + _cr = false; break; case CR: if (_cr) throw new BadMessageException("Bad EOL"); - _cr=true; + _cr = true; if (buffer.hasRemaining()) { // Don't count the CRs and LFs of the chunked encoding. - if (_maxHeaderBytes>0 && (_state == State.HEADER || _state == State.TRAILER)) + if (_maxHeaderBytes > 0 && (_state == State.HEADER || _state == State.TRAILER)) _headerBytes++; return next(buffer); } @@ -456,7 +434,7 @@ public class HttpParser if (_cr) throw new BadMessageException("Bad EOL"); break; - + default: break; } @@ -464,43 +442,42 @@ public class HttpParser return t; } - /* ------------------------------------------------------------------------------- */ /* Quick lookahead for the start state looking for a request method or a HTTP version, * otherwise skip white space until something else to parse. */ private boolean quickStart(ByteBuffer buffer) { - if (_requestHandler!=null) + if (_requestHandler != null) { _method = HttpMethod.lookAheadGet(buffer); - if (_method!=null) + if (_method != null) { _methodString = _method.asString(); - buffer.position(buffer.position()+_methodString.length()+1); + buffer.position(buffer.position() + _methodString.length() + 1); setState(State.SPACE1); return false; } } - else if (_responseHandler!=null) + else if (_responseHandler != null) { _version = HttpVersion.lookAheadGet(buffer); - if (_version!=null) + if (_version != null) { - buffer.position(buffer.position()+_version.asString().length()+1); + buffer.position(buffer.position() + _version.asString().length() + 1); setState(State.SPACE1); return false; } } // Quick start look - while (_state==State.START && buffer.hasRemaining()) + while (_state == State.START && buffer.hasRemaining()) { HttpTokens.Token t = next(buffer); - if (t==null) + if (t == null) break; - - switch(t.getType()) + + switch (t.getType()) { case ALPHA: case DIGIT: @@ -509,92 +486,87 @@ public class HttpParser { _string.setLength(0); _string.append(t.getChar()); - setState(_requestHandler!=null?State.METHOD:State.RESPONSE_VERSION); + setState(_requestHandler != null ? State.METHOD : State.RESPONSE_VERSION); return false; } case OTEXT: case SPACE: case HTAB: - throw new IllegalCharacterException(_state,t,buffer); - + throw new IllegalCharacterException(_state, t, buffer); + default: break; } // count this white space as a header byte to avoid DOS - if (_maxHeaderBytes>0 && ++_headerBytes>_maxHeaderBytes) + if (_maxHeaderBytes > 0 && ++_headerBytes > _maxHeaderBytes) { - LOG.warn("padding is too large >"+_maxHeaderBytes); + LOG.warn("padding is too large >" + _maxHeaderBytes); throw new BadMessageException(HttpStatus.BAD_REQUEST_400); } } return false; } - /* ------------------------------------------------------------------------------- */ private void setString(String s) { _string.setLength(0); _string.append(s); - _length=s.length(); + _length = s.length(); } - /* ------------------------------------------------------------------------------- */ private String takeString() { _string.setLength(_length); - String s =_string.toString(); + String s = _string.toString(); _string.setLength(0); - _length=-1; + _length = -1; return s; } - - /* ------------------------------------------------------------------------------- */ + private boolean handleHeaderContentMessage() { - boolean handle_header = _handler.headerComplete(); + boolean handleHeader = _handler.headerComplete(); _headerComplete = true; - boolean handle_content = _handler.contentComplete(); - boolean handle_message = _handler.messageComplete(); - return handle_header || handle_content || handle_message; - } - - /* ------------------------------------------------------------------------------- */ - private boolean handleContentMessage() - { - boolean handle_content = _handler.contentComplete(); - boolean handle_message = _handler.messageComplete(); - return handle_content || handle_message; + boolean handleContent = _handler.contentComplete(); + boolean handleMessage = _handler.messageComplete(); + return handleHeader || handleContent || handleMessage; + } + + private boolean handleContentMessage() + { + boolean handleContent = _handler.contentComplete(); + boolean handleMessage = _handler.messageComplete(); + return handleContent || handleMessage; } - /* ------------------------------------------------------------------------------- */ /* Parse a request or response line */ private boolean parseLine(ByteBuffer buffer) { - boolean handle=false; + boolean handle = false; // Process headers - while (_state.ordinal()0 && ++_headerBytes>_maxHeaderBytes) + if (_maxHeaderBytes > 0 && ++_headerBytes > _maxHeaderBytes) { - if (_state==State.URI) + if (_state == State.URI) { - LOG.warn("URI is too large >"+_maxHeaderBytes); + LOG.warn("URI is too large >" + _maxHeaderBytes); throw new BadMessageException(HttpStatus.URI_TOO_LONG_414); } else { - if (_requestHandler!=null) - LOG.warn("request is too large >"+_maxHeaderBytes); + if (_requestHandler != null) + LOG.warn("request is too large >" + _maxHeaderBytes); else - LOG.warn("response is too large >"+_maxHeaderBytes); + LOG.warn("response is too large >" + _maxHeaderBytes); throw new BadMessageException(HttpStatus.REQUEST_HEADER_FIELDS_TOO_LARGE_431); } } @@ -602,32 +574,32 @@ public class HttpParser switch (_state) { case METHOD: - switch(t.getType()) + switch (t.getType()) { case SPACE: - _length=_string.length(); - _methodString=takeString(); + _length = _string.length(); + _methodString = takeString(); if (Violation.CASE_INSENSITIVE_METHOD.isAllowedBy(_complianceMode)) { - HttpMethod method=HttpMethod.INSENSITIVE_CACHE.get(_methodString); - if (method!=null) + HttpMethod method = HttpMethod.INSENSITIVE_CACHE.get(_methodString); + if (method != null) { if (!method.asString().equals(_methodString)) - reportComplianceViolation(Violation.CASE_INSENSITIVE_METHOD,_methodString); + reportComplianceViolation(Violation.CASE_INSENSITIVE_METHOD, _methodString); _methodString = method.asString(); } } else { - HttpMethod method=HttpMethod.CACHE.get(_methodString); - if (method!=null) + HttpMethod method = HttpMethod.CACHE.get(_methodString); + if (method != null) _methodString = method.asString(); } setState(State.SPACE1); break; - + case LF: throw new BadMessageException("No URI"); @@ -638,17 +610,17 @@ public class HttpParser break; default: - throw new IllegalCharacterException(_state,t,buffer); + throw new IllegalCharacterException(_state, t, buffer); } break; case RESPONSE_VERSION: - switch(t.getType()) + switch (t.getType()) { case SPACE: - _length=_string.length(); - String version=takeString(); - _version=HttpVersion.CACHE.get(version); + _length = _string.length(); + String version = takeString(); + _version = HttpVersion.CACHE.get(version); checkVersion(); setState(State.SPACE1); break; @@ -661,27 +633,27 @@ public class HttpParser _string.append(t.getChar()); break; default: - throw new IllegalCharacterException(_state,t,buffer); + throw new IllegalCharacterException(_state, t, buffer); } break; case SPACE1: - switch(t.getType()) + switch (t.getType()) { case SPACE: break; - + case ALPHA: case DIGIT: case TCHAR: case VCHAR: case COLON: - if (_responseHandler!=null) + if (_responseHandler != null) { - if (t.getType()!=HttpTokens.Type.DIGIT) - throw new IllegalCharacterException(_state,t,buffer); + if (t.getType() != HttpTokens.Type.DIGIT) + throw new IllegalCharacterException(_state, t, buffer); setState(State.STATUS); - setResponseStatus(t.getByte()-'0'); + setResponseStatus(t.getByte() - '0'); } else { @@ -690,23 +662,25 @@ public class HttpParser // quick scan for space or EoBuffer if (buffer.hasArray()) { - byte[] array=buffer.array(); - int p=buffer.arrayOffset()+buffer.position(); - int l=buffer.arrayOffset()+buffer.limit(); - int i=p; - while (iHttpTokens.SPACE) - i++; - - int len=i-p; - _headerBytes+=len; - - if (_maxHeaderBytes>0 && ++_headerBytes>_maxHeaderBytes) + byte[] array = buffer.array(); + int p = buffer.arrayOffset() + buffer.position(); + int l = buffer.arrayOffset() + buffer.limit(); + int i = p; + while (i < l && array[i] > HttpTokens.SPACE) { - LOG.warn("URI is too large >"+_maxHeaderBytes); + i++; + } + + int len = i - p; + _headerBytes += len; + + if (_maxHeaderBytes > 0 && ++_headerBytes > _maxHeaderBytes) + { + LOG.warn("URI is too large >" + _maxHeaderBytes); throw new BadMessageException(HttpStatus.URI_TOO_LONG_414); } - _uri.append(array,p-1,len+1); - buffer.position(i-buffer.arrayOffset()); + _uri.append(array, p - 1, len + 1); + buffer.position(i - buffer.arrayOffset()); } else _uri.append(t.getByte()); @@ -714,44 +688,44 @@ public class HttpParser break; default: - throw new BadMessageException(HttpStatus.BAD_REQUEST_400,_requestHandler!=null?"No URI":"No Status"); + throw new BadMessageException(HttpStatus.BAD_REQUEST_400, _requestHandler != null ? "No URI" : "No Status"); } break; case STATUS: - switch(t.getType()) + switch (t.getType()) { case SPACE: setState(State.SPACE2); break; - + case DIGIT: - _responseStatus=_responseStatus*10+(t.getByte()-'0'); - if (_responseStatus>=1000) + _responseStatus = _responseStatus * 10 + (t.getByte() - '0'); + if (_responseStatus >= 1000) throw new BadMessageException("Bad status"); break; - + case LF: setState(State.HEADER); handle |= _responseHandler.startResponse(_version, _responseStatus, null); break; - + default: - throw new IllegalCharacterException(_state,t,buffer); + throw new IllegalCharacterException(_state, t, buffer); } break; case URI: - switch(t.getType()) + switch (t.getType()) { case SPACE: setState(State.SPACE2); break; - + case LF: // HTTP/0.9 checkViolation(Violation.HTTP_0_9); - handle=_requestHandler.startRequest(_methodString,_uri.toString(), HttpVersion.HTTP_0_9); + handle = _requestHandler.startRequest(_methodString, _uri.toString(), HttpVersion.HTTP_0_9); setState(State.END); BufferUtil.clear(buffer); handle |= handleHeaderContentMessage(); @@ -765,14 +739,14 @@ public class HttpParser case OTEXT: _uri.append(t.getByte()); break; - + default: - throw new IllegalCharacterException(_state,t,buffer); + throw new IllegalCharacterException(_state, t, buffer); } break; case SPACE2: - switch(t.getType()) + switch (t.getType()) { case SPACE: break; @@ -784,9 +758,9 @@ public class HttpParser case COLON: _string.setLength(0); _string.append(t.getChar()); - if (_responseHandler!=null) + if (_responseHandler != null) { - _length=1; + _length = 1; setState(State.REASON); } else @@ -795,28 +769,28 @@ public class HttpParser // try quick look ahead for HTTP Version HttpVersion version; - if (buffer.position()>0 && buffer.hasArray()) - version=HttpVersion.lookAheadGet(buffer.array(),buffer.arrayOffset()+buffer.position()-1,buffer.arrayOffset()+buffer.limit()); + if (buffer.position() > 0 && buffer.hasArray()) + version = HttpVersion.lookAheadGet(buffer.array(), buffer.arrayOffset() + buffer.position() - 1, buffer.arrayOffset() + buffer.limit()); else - version=HttpVersion.CACHE.getBest(buffer,0,buffer.remaining()); + version = HttpVersion.CACHE.getBest(buffer, 0, buffer.remaining()); - if (version!=null) + if (version != null) { - int pos = buffer.position()+version.asString().length()-1; - if (pos=HttpVersion.HTTP_1_1.getVersion() && _handler.getHeaderCacheSize()>0) + if (_fieldCache == null && _version.getVersion() >= HttpVersion.HTTP_1_1.getVersion() && _handler.getHeaderCacheSize() > 0) { - int header_cache = _handler.getHeaderCacheSize(); - _fieldCache=new ArrayTernaryTrie<>(header_cache); + int headerCache = _handler.getHeaderCacheSize(); + _fieldCache = new ArrayTernaryTrie<>(headerCache); } setState(State.HEADER); - handle |= _requestHandler.startRequest(_methodString,_uri.toString(), _version); + handle |= _requestHandler.startRequest(_methodString, _uri.toString(), _version); continue; case ALPHA: @@ -878,17 +852,17 @@ public class HttpParser case COLON: _string.append(t.getChar()); break; - + default: - throw new IllegalCharacterException(_state,t,buffer); + throw new IllegalCharacterException(_state, t, buffer); } break; case REASON: - switch(t.getType()) + switch (t.getType()) { case LF: - String reason=takeString(); + String reason = takeString(); setState(State.HEADER); handle |= _responseHandler.startResponse(_version, _responseStatus, reason); continue; @@ -900,16 +874,16 @@ public class HttpParser case COLON: case OTEXT: // TODO should this be UTF8 _string.append(t.getChar()); - _length=_string.length(); + _length = _string.length(); break; - + case SPACE: case HTAB: _string.append(t.getChar()); break; - + default: - throw new IllegalCharacterException(_state,t,buffer); + throw new IllegalCharacterException(_state, t, buffer); } break; @@ -921,32 +895,32 @@ public class HttpParser return handle; } - private void checkVersion() + private void checkVersion() { - if (_version==null) - throw new BadMessageException(HttpStatus.BAD_REQUEST_400,"Unknown Version"); - - if (_version.getVersion()<10 || _version.getVersion()>20) - throw new BadMessageException(HttpStatus.BAD_REQUEST_400,"Bad Version"); + if (_version == null) + throw new BadMessageException(HttpStatus.BAD_REQUEST_400, "Unknown Version"); + + if (_version.getVersion() < 10 || _version.getVersion() > 20) + throw new BadMessageException(HttpStatus.BAD_REQUEST_400, "Bad Version"); } private void parsedHeader() { // handler last header if any. Delayed to here just in case there was a continuation line (above) - if (_headerString!=null || _valueString!=null) + if (_headerString != null || _valueString != null) { // Handle known headers - if (_header!=null) + if (_header != null) { - boolean add_to_connection_trie=false; + boolean addToConnectionTrie = false; switch (_header) { case CONTENT_LENGTH: if (_hasContentLength) { checkViolation(MULTIPLE_CONTENT_LENGTHS); - if (convertContentLength(_valueString)!=_contentLength) - throw new BadMessageException(HttpStatus.BAD_REQUEST_400,MULTIPLE_CONTENT_LENGTHS.getDescription()); + if (convertContentLength(_valueString) != _contentLength) + throw new BadMessageException(HttpStatus.BAD_REQUEST_400, MULTIPLE_CONTENT_LENGTHS.getDescription()); } _hasContentLength = true; @@ -955,11 +929,11 @@ public class HttpParser if (_endOfContent != EndOfContent.CHUNKED_CONTENT) { - _contentLength=convertContentLength(_valueString); + _contentLength = convertContentLength(_valueString); if (_contentLength <= 0) - _endOfContent=EndOfContent.NO_CONTENT; + _endOfContent = EndOfContent.NO_CONTENT; else - _endOfContent=EndOfContent.CONTENT_LENGTH; + _endOfContent = EndOfContent.CONTENT_LENGTH; } break; @@ -969,39 +943,38 @@ public class HttpParser if (HttpHeaderValue.CHUNKED.is(_valueString)) { - _endOfContent=EndOfContent.CHUNKED_CONTENT; - _contentLength=-1; + _endOfContent = EndOfContent.CHUNKED_CONTENT; + _contentLength = -1; } else { List values = new QuotedCSV(_valueString).getValues(); - if (!values.isEmpty() && HttpHeaderValue.CHUNKED.is(values.get(values.size()-1))) + if (!values.isEmpty() && HttpHeaderValue.CHUNKED.is(values.get(values.size() - 1))) { - _endOfContent=EndOfContent.CHUNKED_CONTENT; - _contentLength=-1; + _endOfContent = EndOfContent.CHUNKED_CONTENT; + _contentLength = -1; } else if (values.stream().anyMatch(HttpHeaderValue.CHUNKED::is)) - throw new BadMessageException(HttpStatus.BAD_REQUEST_400,"Bad chunking"); + throw new BadMessageException(HttpStatus.BAD_REQUEST_400, "Bad chunking"); } - - + break; case HOST: - _host=true; - if (!(_field instanceof HostPortHttpField) && _valueString!=null && !_valueString.isEmpty()) + _host = true; + if (!(_field instanceof HostPortHttpField) && _valueString != null && !_valueString.isEmpty()) { - _field=new HostPortHttpField(_header, - CASE_SENSITIVE_FIELD_NAME.isAllowedBy(_complianceMode)?_headerString:_header.asString(), + _field = new HostPortHttpField(_header, + CASE_SENSITIVE_FIELD_NAME.isAllowedBy(_complianceMode) ? _headerString : _header.asString(), _valueString); - add_to_connection_trie=_fieldCache!=null; + addToConnectionTrie = _fieldCache != null; } - break; + break; case CONNECTION: // Don't cache headers if not persistent if (HttpHeaderValue.CLOSE.is(_valueString) || new QuotedCSV(_valueString).getValues().stream().anyMatch(HttpHeaderValue.CLOSE::is)) - _fieldCache=null; + _fieldCache = null; break; case AUTHORIZATION: @@ -1012,79 +985,78 @@ public class HttpParser case COOKIE: case CACHE_CONTROL: case USER_AGENT: - add_to_connection_trie=_fieldCache!=null && _field==null; + addToConnectionTrie = _fieldCache != null && _field == null; break; - default: break; - + default: + break; } - if (add_to_connection_trie && !_fieldCache.isFull() && _header!=null && _valueString!=null) + if (addToConnectionTrie && !_fieldCache.isFull() && _header != null && _valueString != null) { - if (_field==null) - _field=new HttpField(_header,caseInsensitiveHeader(_headerString,_header.asString()),_valueString); + if (_field == null) + _field = new HttpField(_header, caseInsensitiveHeader(_headerString, _header.asString()), _valueString); _fieldCache.put(_field); } } - _handler.parsedHeader(_field!=null?_field:new HttpField(_header,_headerString,_valueString)); + _handler.parsedHeader(_field != null ? _field : new HttpField(_header, _headerString, _valueString)); } - _headerString=_valueString=null; - _header=null; - _field=null; + _headerString = _valueString = null; + _header = null; + _field = null; } private void parsedTrailer() { // handler last header if any. Delayed to here just in case there was a continuation line (above) - if (_headerString!=null || _valueString!=null) - _handler.parsedTrailer(_field!=null?_field:new HttpField(_header,_headerString,_valueString)); + if (_headerString != null || _valueString != null) + _handler.parsedTrailer(_field != null ? _field : new HttpField(_header, _headerString, _valueString)); - _headerString=_valueString=null; - _header=null; - _field=null; + _headerString = _valueString = null; + _header = null; + _field = null; } - + private long convertContentLength(String valueString) { try { return Long.parseLong(valueString); } - catch(NumberFormatException e) + catch (NumberFormatException e) { LOG.ignore(e); - throw new BadMessageException(HttpStatus.BAD_REQUEST_400,"Invalid Content-Length Value",e); + throw new BadMessageException(HttpStatus.BAD_REQUEST_400, "Invalid Content-Length Value", e); } } - /* ------------------------------------------------------------------------------- */ /* * Parse the message headers and return true if the handler has signalled for a return */ protected boolean parseFields(ByteBuffer buffer) { // Process headers - while ((_state==State.HEADER || _state==State.TRAILER) && buffer.hasRemaining()) + while ((_state == State.HEADER || _state == State.TRAILER) && buffer.hasRemaining()) { // process each character HttpTokens.Token t = next(buffer); - if (t==null) + if (t == null) break; - if (_maxHeaderBytes>0 && ++_headerBytes>_maxHeaderBytes) + if (_maxHeaderBytes > 0 && ++_headerBytes > _maxHeaderBytes) { boolean header = _state == State.HEADER; LOG.warn("{} is too large {}>{}", header ? "Header" : "Trailer", _headerBytes, _maxHeaderBytes); - throw new BadMessageException(header ? - HttpStatus.REQUEST_HEADER_FIELDS_TOO_LARGE_431 : - HttpStatus.PAYLOAD_TOO_LARGE_413); + throw new BadMessageException(header + ? HttpStatus.REQUEST_HEADER_FIELDS_TOO_LARGE_431 + : HttpStatus.PAYLOAD_TOO_LARGE_413); } switch (_fieldState) { case FIELD: - switch(t.getType()) + switch (t.getType()) { case COLON: case SPACE: @@ -1093,17 +1065,17 @@ public class HttpParser checkViolation(Violation.MULTILINE_FIELD_VALUE); // header value without name - continuation? - if ( StringUtil.isEmpty(_valueString)) + if (StringUtil.isEmpty(_valueString)) { _string.setLength(0); - _length=0; + _length = 0; } else { setString(_valueString); _string.append(' '); _length++; - _valueString=null; + _valueString = null; } setState(FieldState.VALUE); break; @@ -1112,43 +1084,43 @@ public class HttpParser case LF: { // process previous header - if (_state==State.HEADER) + if (_state == State.HEADER) parsedHeader(); else parsedTrailer(); - _contentPosition=0; + _contentPosition = 0; // End of headers or trailers? - if (_state==State.TRAILER) + if (_state == State.TRAILER) { setState(State.END); return _handler.messageComplete(); } - + // Was there a required host header? - if (!_host && _version==HttpVersion.HTTP_1_1 && _requestHandler!=null) + if (!_host && _version == HttpVersion.HTTP_1_1 && _requestHandler != null) { - throw new BadMessageException(HttpStatus.BAD_REQUEST_400,"No Host"); + throw new BadMessageException(HttpStatus.BAD_REQUEST_400, "No Host"); } // is it a response that cannot have a body? - if (_responseHandler !=null && // response - (_responseStatus == 304 || // not-modified response + if (_responseHandler != null && // response + (_responseStatus == 304 || // not-modified response _responseStatus == 204 || // no-content response _responseStatus < 200)) // 1xx response - _endOfContent=EndOfContent.NO_CONTENT; // ignore any other headers set + _endOfContent = EndOfContent.NO_CONTENT; // ignore any other headers set - // else if we don't know framing + // else if we don't know framing else if (_endOfContent == EndOfContent.UNKNOWN_CONTENT) { - if (_responseStatus == 0 // request - || _responseStatus == 304 // not-modified response - || _responseStatus == 204 // no-content response - || _responseStatus < 200) // 1xx response - _endOfContent=EndOfContent.NO_CONTENT; + if (_responseStatus == 0 || // request + _responseStatus == 304 || // not-modified response + _responseStatus == 204 || // no-content response + _responseStatus < 200) // 1xx response + _endOfContent = EndOfContent.NO_CONTENT; else - _endOfContent=EndOfContent.EOF_CONTENT; + _endOfContent = EndOfContent.EOF_CONTENT; } // How is the message ended? @@ -1157,15 +1129,15 @@ public class HttpParser case EOF_CONTENT: { setState(State.EOF_CONTENT); - boolean handle=_handler.headerComplete(); - _headerComplete=true; + boolean handle = _handler.headerComplete(); + _headerComplete = true; return handle; } case CHUNKED_CONTENT: { setState(State.CHUNKED_CONTENT); - boolean handle=_handler.headerComplete(); - _headerComplete=true; + boolean handle = _handler.headerComplete(); + _headerComplete = true; return handle; } case NO_CONTENT: @@ -1176,8 +1148,8 @@ public class HttpParser default: { setState(State.CONTENT); - boolean handle=_handler.headerComplete(); - _headerComplete=true; + boolean handle = _handler.headerComplete(); + _headerComplete = true; return handle; } } @@ -1188,7 +1160,7 @@ public class HttpParser case TCHAR: { // process previous header - if (_state==State.HEADER) + if (_state == State.HEADER) parsedHeader(); else parsedTrailer(); @@ -1197,63 +1169,63 @@ public class HttpParser if (buffer.hasRemaining()) { // Try a look ahead for the known header name and value. - HttpField cached_field=_fieldCache==null?null:_fieldCache.getBest(buffer,-1,buffer.remaining()); - if (cached_field==null) - cached_field=CACHE.getBest(buffer,-1,buffer.remaining()); + HttpField cachedField = _fieldCache == null ? null : _fieldCache.getBest(buffer, -1, buffer.remaining()); + if (cachedField == null) + cachedField = CACHE.getBest(buffer, -1, buffer.remaining()); - if (cached_field!=null) + if (cachedField != null) { - String n = cached_field.getName(); - String v = cached_field.getValue(); + String n = cachedField.getName(); + String v = cachedField.getValue(); if (CASE_SENSITIVE_FIELD_NAME.isAllowedBy(_complianceMode)) { // Have to get the fields exactly from the buffer to match case - String en = BufferUtil.toString(buffer,buffer.position()-1,n.length(),StandardCharsets.US_ASCII); + String en = BufferUtil.toString(buffer, buffer.position() - 1, n.length(), StandardCharsets.US_ASCII); if (!n.equals(en)) { - reportComplianceViolation(CASE_SENSITIVE_FIELD_NAME,en); + reportComplianceViolation(CASE_SENSITIVE_FIELD_NAME, en); n = en; - cached_field = new HttpField(cached_field.getHeader(),n,v); + cachedField = new HttpField(cachedField.getHeader(), n, v); } } - if (v!=null && _handler.isHeaderCacheCaseSensitive()) + if (v != null && _handler.isHeaderCacheCaseSensitive()) { - String ev = BufferUtil.toString(buffer,buffer.position()+n.length()+1,v.length(),StandardCharsets.ISO_8859_1); + String ev = BufferUtil.toString(buffer, buffer.position() + n.length() + 1, v.length(), StandardCharsets.ISO_8859_1); if (!v.equals(ev)) { v = ev; - cached_field = new HttpField(cached_field.getHeader(),n,v); + cachedField = new HttpField(cachedField.getHeader(), n, v); } } - - _header=cached_field.getHeader(); - _headerString=n; - if (v==null) + _header = cachedField.getHeader(); + _headerString = n; + + if (v == null) { // Header only setState(FieldState.VALUE); _string.setLength(0); - _length=0; - buffer.position(buffer.position()+n.length()+1); + _length = 0; + buffer.position(buffer.position() + n.length() + 1); break; } // Header and value - int pos=buffer.position()+n.length()+v.length()+1; - byte peek=buffer.get(pos); - if (peek==HttpTokens.CARRIAGE_RETURN || peek==HttpTokens.LINE_FEED) + int pos = buffer.position() + n.length() + v.length() + 1; + byte peek = buffer.get(pos); + if (peek == HttpTokens.CARRIAGE_RETURN || peek == HttpTokens.LINE_FEED) { - _field=cached_field; - _valueString=v; + _field = cachedField; + _valueString = v; setState(FieldState.IN_VALUE); - if (peek==HttpTokens.CARRIAGE_RETURN) + if (peek == HttpTokens.CARRIAGE_RETURN) { - _cr=true; - buffer.position(pos+1); + _cr = true; + buffer.position(pos + 1); } else buffer.position(pos); @@ -1270,69 +1242,69 @@ public class HttpParser setState(FieldState.IN_NAME); _string.setLength(0); _string.append(t.getChar()); - _length=1; + _length = 1; } break; - + default: - throw new IllegalCharacterException(_state,t,buffer); + throw new IllegalCharacterException(_state, t, buffer); } break; case IN_NAME: - switch(t.getType()) + switch (t.getType()) { case SPACE: case HTAB: //Ignore trailing whitespaces ? if (WHITESPACE_AFTER_FIELD_NAME.isAllowedBy(_complianceMode)) { - _headerString=takeString(); - reportComplianceViolation(WHITESPACE_AFTER_FIELD_NAME,"Space after "+_headerString); - _header=HttpHeader.CACHE.get(_headerString); - _length=-1; + _headerString = takeString(); + reportComplianceViolation(WHITESPACE_AFTER_FIELD_NAME, "Space after " + _headerString); + _header = HttpHeader.CACHE.get(_headerString); + _length = -1; setState(FieldState.WS_AFTER_NAME); break; } - throw new IllegalCharacterException(_state,t,buffer); - + throw new IllegalCharacterException(_state, t, buffer); + case COLON: - _headerString=takeString(); - _header=HttpHeader.CACHE.get(_headerString); - _length=-1; + _headerString = takeString(); + _header = HttpHeader.CACHE.get(_headerString); + _length = -1; setState(FieldState.VALUE); break; - + case LF: - _headerString=takeString(); - _header=HttpHeader.CACHE.get(_headerString); + _headerString = takeString(); + _header = HttpHeader.CACHE.get(_headerString); _string.setLength(0); - _valueString=""; - _length=-1; + _valueString = ""; + _length = -1; if (NO_COLON_AFTER_FIELD_NAME.isAllowedBy(_complianceMode)) { - reportComplianceViolation(NO_COLON_AFTER_FIELD_NAME,"Field "+_headerString); + reportComplianceViolation(NO_COLON_AFTER_FIELD_NAME, "Field " + _headerString); setState(FieldState.FIELD); break; } - throw new IllegalCharacterException(_state,t,buffer); + throw new IllegalCharacterException(_state, t, buffer); case ALPHA: case DIGIT: case TCHAR: _string.append(t.getChar()); - _length=_string.length(); + _length = _string.length(); break; - + default: - throw new IllegalCharacterException(_state,t,buffer); + throw new IllegalCharacterException(_state, t, buffer); } break; case WS_AFTER_NAME: - switch(t.getType()) + switch (t.getType()) { case SPACE: case HTAB: @@ -1340,29 +1312,29 @@ public class HttpParser case COLON: setState(FieldState.VALUE); - break; - + break; + case LF: if (NO_COLON_AFTER_FIELD_NAME.isAllowedBy(_complianceMode)) { - reportComplianceViolation(NO_COLON_AFTER_FIELD_NAME,"Field "+_headerString); + reportComplianceViolation(NO_COLON_AFTER_FIELD_NAME, "Field " + _headerString); setState(FieldState.FIELD); break; } - throw new IllegalCharacterException(_state,t,buffer); - + throw new IllegalCharacterException(_state, t, buffer); + default: - throw new IllegalCharacterException(_state,t,buffer); + throw new IllegalCharacterException(_state, t, buffer); } break; case VALUE: - switch(t.getType()) + switch (t.getType()) { case LF: _string.setLength(0); - _valueString=""; - _length=-1; + _valueString = ""; + _length = -1; setState(FieldState.FIELD); break; @@ -1378,27 +1350,27 @@ public class HttpParser case COLON: case OTEXT: // TODO review? should this be a utf8 string? _string.append(t.getChar()); - _length=_string.length(); + _length = _string.length(); setState(FieldState.IN_VALUE); break; - + default: - throw new IllegalCharacterException(_state,t,buffer); + throw new IllegalCharacterException(_state, t, buffer); } break; - + case IN_VALUE: - switch(t.getType()) + switch (t.getType()) { case LF: if (_length > 0) { - _valueString=takeString(); - _length=-1; + _valueString = takeString(); + _length = -1; } setState(FieldState.FIELD); break; - + case SPACE: case HTAB: _string.append(t.getChar()); @@ -1411,66 +1383,65 @@ public class HttpParser case COLON: case OTEXT: // TODO review? should this be a utf8 string? _string.append(t.getChar()); - _length=_string.length(); + _length = _string.length(); break; default: - throw new IllegalCharacterException(_state,t,buffer); + throw new IllegalCharacterException(_state, t, buffer); } break; - + default: throw new IllegalStateException(_state.toString()); - } } return false; } - /* ------------------------------------------------------------------------------- */ /** * Parse until next Event. + * * @param buffer the buffer to parse * @return True if an {@link RequestHandler} method was called and it returned true; */ public boolean parseNext(ByteBuffer buffer) { - if (DEBUG) - LOG.debug("parseNext s={} {}",_state,BufferUtil.toDetailString(buffer)); + if (debugEnabled) + LOG.debug("parseNext s={} {}", _state, BufferUtil.toDetailString(buffer)); try { // Start a request/response - if (_state==State.START) + if (_state == State.START) { - _version=null; - _method=null; - _methodString=null; - _endOfContent=EndOfContent.UNKNOWN_CONTENT; - _header=null; + _version = null; + _method = null; + _methodString = null; + _endOfContent = EndOfContent.UNKNOWN_CONTENT; + _header = null; if (quickStart(buffer)) return true; } // Request/response line - if (_state.ordinal()>= State.START.ordinal() && _state.ordinal()= State.START.ordinal() && _state.ordinal() < State.HEADER.ordinal()) { if (parseLine(buffer)) return true; } // parse headers - if (_state== State.HEADER) + if (_state == State.HEADER) { if (parseFields(buffer)) return true; } // parse content - if (_state.ordinal()>= State.CONTENT.ordinal() && _state.ordinal()= State.CONTENT.ordinal() && _state.ordinal() < State.TRAILER.ordinal()) { // Handle HEAD response - if (_responseStatus>0 && _headResponse) + if (_responseStatus > 0 && _headResponse) { setState(State.END); return handleContentMessage(); @@ -1483,18 +1454,20 @@ public class HttpParser } // parse headers - if (_state==State.TRAILER) + if (_state == State.TRAILER) { if (parseFields(buffer)) return true; } // handle end states - if (_state==State.END) + if (_state == State.END) { // eat white space - while (buffer.remaining()>0 && buffer.get(buffer.position())<=HttpTokens.SPACE) + while (buffer.remaining() > 0 && buffer.get(buffer.position()) <= HttpTokens.SPACE) + { buffer.get(); + } } else if (isClose() || isClosed()) { @@ -1504,7 +1477,7 @@ public class HttpParser // Handle EOF if (_eof && !buffer.hasRemaining()) { - switch(_state) + switch (_state) { case CLOSED: break; @@ -1521,7 +1494,7 @@ public class HttpParser case EOF_CONTENT: case TRAILER: - if (_fieldState==FieldState.FIELD) + if (_fieldState == FieldState.FIELD) { // Be forgiving of missing last CRLF setState(State.CLOSED); @@ -1530,7 +1503,7 @@ public class HttpParser setState(State.CLOSED); _handler.earlyEOF(); break; - + case CONTENT: case CHUNKED_CONTENT: case CHUNK_SIZE: @@ -1541,30 +1514,30 @@ public class HttpParser break; default: - if (DEBUG) - LOG.debug("{} EOF in {}",this,_state); + if (debugEnabled) + LOG.debug("{} EOF in {}", this, _state); setState(State.CLOSED); _handler.badMessage(new BadMessageException(HttpStatus.BAD_REQUEST_400)); break; } } } - catch(BadMessageException x) + catch (BadMessageException x) { BufferUtil.clear(buffer); badMessage(x); } - catch(Throwable x) + catch (Throwable x) { BufferUtil.clear(buffer); badMessage(new BadMessageException(HttpStatus.BAD_REQUEST_400, _requestHandler != null ? "Bad Request" : "Bad Response", x)); } return false; } - + protected void badMessage(BadMessageException x) { - if (DEBUG) + if (debugEnabled) LOG.debug("Parse exception: " + this + " for " + _handler, x); setState(State.CLOSE); if (_headerComplete) @@ -1575,10 +1548,10 @@ public class HttpParser protected boolean parseContent(ByteBuffer buffer) { - int remaining=buffer.remaining(); - if (remaining==0 && _state==State.CONTENT) + int remaining = buffer.remaining(); + if (remaining == 0 && _state == State.CONTENT) { - long content=_contentLength - _contentPosition; + long content = _contentLength - _contentPosition; if (content == 0) { setState(State.END); @@ -1588,21 +1561,21 @@ public class HttpParser // Handle _content byte ch; - while (_state.ordinal() < State.TRAILER.ordinal() && remaining>0) + while (_state.ordinal() < State.TRAILER.ordinal() && remaining > 0) { switch (_state) { case EOF_CONTENT: - _contentChunk=buffer.asReadOnlyBuffer(); + _contentChunk = buffer.asReadOnlyBuffer(); _contentPosition += remaining; - buffer.position(buffer.position()+remaining); + buffer.position(buffer.position() + remaining); if (_handler.content(_contentChunk)) return true; break; case CONTENT: { - long content=_contentLength - _contentPosition; + long content = _contentLength - _contentPosition; if (content == 0) { setState(State.END); @@ -1610,23 +1583,23 @@ public class HttpParser } else { - _contentChunk=buffer.asReadOnlyBuffer(); + _contentChunk = buffer.asReadOnlyBuffer(); // limit content by expected size if (remaining > content) { // We can cast remaining to an int as we know that it is smaller than // or equal to length which is already an int. - _contentChunk.limit(_contentChunk.position()+(int)content); + _contentChunk.limit(_contentChunk.position() + (int)content); } _contentPosition += _contentChunk.remaining(); - buffer.position(buffer.position()+_contentChunk.remaining()); + buffer.position(buffer.position() + _contentChunk.remaining()); if (_handler.content(_contentChunk)) return true; - if(_contentPosition == _contentLength) + if (_contentPosition == _contentLength) { setState(State.END); return handleContentMessage(); @@ -1638,31 +1611,31 @@ public class HttpParser case CHUNKED_CONTENT: { HttpTokens.Token t = next(buffer); - if (t==null) + if (t == null) break; - switch(t.getType()) + switch (t.getType()) { case LF: break; - + case DIGIT: - _chunkLength=t.getHexDigit(); - _chunkPosition=0; + _chunkLength = t.getHexDigit(); + _chunkPosition = 0; setState(State.CHUNK_SIZE); break; - + case ALPHA: if (t.isHexDigit()) { - _chunkLength=t.getHexDigit(); - _chunkPosition=0; + _chunkLength = t.getHexDigit(); + _chunkPosition = 0; setState(State.CHUNK_SIZE); break; } - throw new IllegalCharacterException(_state,t,buffer); - + throw new IllegalCharacterException(_state, t, buffer); + default: - throw new IllegalCharacterException(_state,t,buffer); + throw new IllegalCharacterException(_state, t, buffer); } break; } @@ -1670,10 +1643,10 @@ public class HttpParser case CHUNK_SIZE: { HttpTokens.Token t = next(buffer); - if (t==null) + if (t == null) break; - - switch(t.getType()) + + switch (t.getType()) { case LF: if (_chunkLength == 0) @@ -1685,17 +1658,17 @@ public class HttpParser else setState(State.CHUNK); break; - + case SPACE: setState(State.CHUNK_PARAMS); break; - + default: if (t.isHexDigit()) { - if (_chunkLength>MAX_CHUNK_LENGTH) + if (_chunkLength > MAX_CHUNK_LENGTH) throw new BadMessageException(HttpStatus.PAYLOAD_TOO_LARGE_413); - _chunkLength=_chunkLength * 16 + t.getHexDigit(); + _chunkLength = _chunkLength * 16 + t.getHexDigit(); } else { @@ -1708,10 +1681,10 @@ public class HttpParser case CHUNK_PARAMS: { HttpTokens.Token t = next(buffer); - if (t==null) + if (t == null) break; - switch(t.getType()) + switch (t.getType()) { case LF: if (_chunkLength == 0) @@ -1731,22 +1704,22 @@ public class HttpParser case CHUNK: { - int chunk=_chunkLength - _chunkPosition; + int chunk = _chunkLength - _chunkPosition; if (chunk == 0) { setState(State.CHUNKED_CONTENT); } else { - _contentChunk=buffer.asReadOnlyBuffer(); + _contentChunk = buffer.asReadOnlyBuffer(); if (remaining > chunk) - _contentChunk.limit(_contentChunk.position()+chunk); - chunk=_contentChunk.remaining(); + _contentChunk.limit(_contentChunk.position() + chunk); + chunk = _contentChunk.remaining(); _contentPosition += chunk; _chunkPosition += chunk; - buffer.position(buffer.position()+chunk); + buffer.position(buffer.position() + chunk); if (_handler.content(_contentChunk)) return true; } @@ -1761,98 +1734,88 @@ public class HttpParser default: break; - } - remaining=buffer.remaining(); + remaining = buffer.remaining(); } return false; } - /* ------------------------------------------------------------------------------- */ public boolean isAtEOF() { return _eof; } - /* ------------------------------------------------------------------------------- */ - /** Signal that the associated data source is at EOF + /** + * Signal that the associated data source is at EOF */ public void atEOF() { - if (DEBUG) + if (debugEnabled) LOG.debug("atEOF {}", this); - _eof=true; + _eof = true; } - /* ------------------------------------------------------------------------------- */ - /** Request that the associated data source be closed + /** + * Request that the associated data source be closed */ public void close() { - if (DEBUG) + if (debugEnabled) LOG.debug("close {}", this); setState(State.CLOSE); } - /* ------------------------------------------------------------------------------- */ public void reset() { - if (DEBUG) + if (debugEnabled) LOG.debug("reset {}", this); // reset state - if (_state==State.CLOSE || _state==State.CLOSED) + if (_state == State.CLOSE || _state == State.CLOSED) return; setState(State.START); - _endOfContent=EndOfContent.UNKNOWN_CONTENT; - _contentLength=-1; - _hasContentLength=false; - _contentPosition=0; - _responseStatus=0; - _contentChunk=null; - _headerBytes=0; - _host=false; - _headerComplete=false; + _endOfContent = EndOfContent.UNKNOWN_CONTENT; + _contentLength = -1; + _hasContentLength = false; + _contentPosition = 0; + _responseStatus = 0; + _contentChunk = null; + _headerBytes = 0; + _host = false; + _headerComplete = false; } - /* ------------------------------------------------------------------------------- */ protected void setState(State state) { - if (DEBUG) - LOG.debug("{} --> {}",_state,state); - _state=state; + if (debugEnabled) + LOG.debug("{} --> {}", _state, state); + _state = state; } - /* ------------------------------------------------------------------------------- */ protected void setState(FieldState state) { - if (DEBUG) - LOG.debug("{}:{} --> {}",_state,_field!=null?_field:_headerString!=null?_headerString:_string,state); - _fieldState=state; + if (debugEnabled) + LOG.debug("{}:{} --> {}", _state, _field != null ? _field : _headerString != null ? _headerString : _string, state); + _fieldState = state; } - /* ------------------------------------------------------------------------------- */ public Trie getFieldCache() { return _fieldCache; } - /* ------------------------------------------------------------------------------- */ @Override public String toString() { return String.format("%s{s=%s,%d of %d}", - getClass().getSimpleName(), - _state, - _contentPosition, - _contentLength); + getClass().getSimpleName(), + _state, + _contentPosition, + _contentLength); } - /* ------------------------------------------------------------ */ - /* ------------------------------------------------------------ */ - /* ------------------------------------------------------------ */ /* Event Handler interface * These methods return true if the caller should process the events * so far received (eg return from parseNext and call HttpChannel.handle). @@ -1872,61 +1835,61 @@ public class HttpParser /** * This is the method called by parser when a HTTP Header name and value is found + * * @param field The field parsed */ void parsedHeader(HttpField field); /** * This is the method called by parser when a HTTP Trailer name and value is found + * * @param field The field parsed */ - default void parsedTrailer(HttpField field) {} + default void parsedTrailer(HttpField field) + { + } - /* ------------------------------------------------------------ */ - /** Called to signal that an EOF was received unexpectedly + /** + * Called to signal that an EOF was received unexpectedly * during the parsing of a HTTP message */ void earlyEOF(); - /* ------------------------------------------------------------ */ - /** Called to signal that a bad HTTP message has been received. + /** + * Called to signal that a bad HTTP message has been received. + * * @param failure the failure with the bad message information */ default void badMessage(BadMessageException failure) { } - /* ------------------------------------------------------------ */ - /** @return the size in bytes of the per parser header cache + /** + * @return the size in bytes of the per parser header cache */ int getHeaderCacheSize(); boolean isHeaderCacheCaseSensitive(); } - /* ------------------------------------------------------------------------------- */ - /* ------------------------------------------------------------------------------- */ - /* ------------------------------------------------------------------------------- */ public interface RequestHandler extends HttpHandler { /** * This is the method called by parser when the HTTP request line is parsed + * * @param method The method * @param uri The raw bytes of the URI. These are copied into a ByteBuffer that will not be changed until this parser is reset and reused. * @param version the http version in use * @return true if handling parsing should return. */ boolean startRequest(String method, String uri, HttpVersion version); - } - /* ------------------------------------------------------------------------------- */ - /* ------------------------------------------------------------------------------- */ - /* ------------------------------------------------------------------------------- */ public interface ResponseHandler extends HttpHandler { /** * This is the method called by parser when the HTTP request line is parsed + * * @param version the http version in use * @param status the response status * @param reason the response reason phrase @@ -1935,15 +1898,14 @@ public class HttpParser boolean startResponse(HttpVersion version, int status, String reason); } - /* ------------------------------------------------------------------------------- */ @SuppressWarnings("serial") private static class IllegalCharacterException extends BadMessageException { - private IllegalCharacterException(State state,HttpTokens.Token token,ByteBuffer buffer) + private IllegalCharacterException(State state, HttpTokens.Token token, ByteBuffer buffer) { - super(400,String.format("Illegal character %s",token)); + super(400, String.format("Illegal character %s", token)); if (LOG.isDebugEnabled()) - LOG.debug(String.format("Illegal character %s in state=%s for buffer %s",token,state,BufferUtil.toDetailString(buffer))); + LOG.debug(String.format("Illegal character %s in state=%s for buffer %s", token, state, BufferUtil.toDetailString(buffer))); } } } diff --git a/jetty-http/src/main/java/org/eclipse/jetty/http/HttpScheme.java b/jetty-http/src/main/java/org/eclipse/jetty/http/HttpScheme.java index 31039ea6f39..9340fb6f974 100644 --- a/jetty-http/src/main/java/org/eclipse/jetty/http/HttpScheme.java +++ b/jetty-http/src/main/java/org/eclipse/jetty/http/HttpScheme.java @@ -24,8 +24,8 @@ import org.eclipse.jetty.util.ArrayTrie; import org.eclipse.jetty.util.BufferUtil; import org.eclipse.jetty.util.Trie; -/* ------------------------------------------------------------------------------- */ /** + * */ public enum HttpScheme { @@ -34,34 +34,33 @@ public enum HttpScheme WS("ws"), WSS("wss"); - /* ------------------------------------------------------------ */ - public final static Trie CACHE= new ArrayTrie(); + public static final Trie CACHE = new ArrayTrie(); + static { for (HttpScheme version : HttpScheme.values()) - CACHE.put(version.asString(),version); + { + CACHE.put(version.asString(), version); + } } private final String _string; private final ByteBuffer _buffer; - /* ------------------------------------------------------------ */ HttpScheme(String s) { - _string=s; - _buffer=BufferUtil.toBuffer(s); + _string = s; + _buffer = BufferUtil.toBuffer(s); } - /* ------------------------------------------------------------ */ public ByteBuffer asByteBuffer() { return _buffer.asReadOnlyBuffer(); } - /* ------------------------------------------------------------ */ public boolean is(String s) { - return s!=null && _string.equalsIgnoreCase(s); + return s != null && _string.equalsIgnoreCase(s); } public String asString() @@ -69,11 +68,9 @@ public enum HttpScheme return _string; } - /* ------------------------------------------------------------ */ @Override public String toString() { return _string; } - } diff --git a/jetty-http/src/main/java/org/eclipse/jetty/http/HttpStatus.java b/jetty-http/src/main/java/org/eclipse/jetty/http/HttpStatus.java index 0796e96b4d3..58d2a98f4bd 100644 --- a/jetty-http/src/main/java/org/eclipse/jetty/http/HttpStatus.java +++ b/jetty-http/src/main/java/org/eclipse/jetty/http/HttpStatus.java @@ -22,77 +22,78 @@ package org.eclipse.jetty.http; *

    * Http Status Codes *

    + * * @see IANA HTTP Status Code Registry */ public class HttpStatus { - public final static int CONTINUE_100 = 100; - public final static int SWITCHING_PROTOCOLS_101 = 101; - public final static int PROCESSING_102 = 102; + public static final int CONTINUE_100 = 100; + public static final int SWITCHING_PROTOCOLS_101 = 101; + public static final int PROCESSING_102 = 102; - public final static int OK_200 = 200; - public final static int CREATED_201 = 201; - public final static int ACCEPTED_202 = 202; - public final static int NON_AUTHORITATIVE_INFORMATION_203 = 203; - public final static int NO_CONTENT_204 = 204; - public final static int RESET_CONTENT_205 = 205; - public final static int PARTIAL_CONTENT_206 = 206; - public final static int MULTI_STATUS_207 = 207; + public static final int OK_200 = 200; + public static final int CREATED_201 = 201; + public static final int ACCEPTED_202 = 202; + public static final int NON_AUTHORITATIVE_INFORMATION_203 = 203; + public static final int NO_CONTENT_204 = 204; + public static final int RESET_CONTENT_205 = 205; + public static final int PARTIAL_CONTENT_206 = 206; + public static final int MULTI_STATUS_207 = 207; - public final static int MULTIPLE_CHOICES_300 = 300; - public final static int MOVED_PERMANENTLY_301 = 301; - public final static int MOVED_TEMPORARILY_302 = 302; - public final static int FOUND_302 = 302; - public final static int SEE_OTHER_303 = 303; - public final static int NOT_MODIFIED_304 = 304; - public final static int USE_PROXY_305 = 305; - public final static int TEMPORARY_REDIRECT_307 = 307; - public final static int PERMANENT_REDIRECT_308 = 308; + public static final int MULTIPLE_CHOICES_300 = 300; + public static final int MOVED_PERMANENTLY_301 = 301; + public static final int MOVED_TEMPORARILY_302 = 302; + public static final int FOUND_302 = 302; + public static final int SEE_OTHER_303 = 303; + public static final int NOT_MODIFIED_304 = 304; + public static final int USE_PROXY_305 = 305; + public static final int TEMPORARY_REDIRECT_307 = 307; + public static final int PERMANENT_REDIRECT_308 = 308; - public final static int BAD_REQUEST_400 = 400; - public final static int UNAUTHORIZED_401 = 401; - public final static int PAYMENT_REQUIRED_402 = 402; - public final static int FORBIDDEN_403 = 403; - public final static int NOT_FOUND_404 = 404; - public final static int METHOD_NOT_ALLOWED_405 = 405; - public final static int NOT_ACCEPTABLE_406 = 406; - public final static int PROXY_AUTHENTICATION_REQUIRED_407 = 407; - public final static int REQUEST_TIMEOUT_408 = 408; - public final static int CONFLICT_409 = 409; - public final static int GONE_410 = 410; - public final static int LENGTH_REQUIRED_411 = 411; - public final static int PRECONDITION_FAILED_412 = 412; - public final static int PAYLOAD_TOO_LARGE_413 = 413; - public final static int URI_TOO_LONG_414 = 414; - public final static int UNSUPPORTED_MEDIA_TYPE_415 = 415; - public final static int RANGE_NOT_SATISFIABLE_416 = 416; - public final static int EXPECTATION_FAILED_417 = 417; - public final static int IM_A_TEAPOT_418 = 418; - public final static int ENHANCE_YOUR_CALM_420 = 420; - public final static int MISDIRECTED_REQUEST_421 = 421; - public final static int UNPROCESSABLE_ENTITY_422 = 422; - public final static int LOCKED_423 = 423; - public final static int FAILED_DEPENDENCY_424 = 424; - public final static int UPGRADE_REQUIRED_426 = 426; - public final static int PRECONDITION_REQUIRED_428 = 428; - public final static int TOO_MANY_REQUESTS_429 = 429; - public final static int REQUEST_HEADER_FIELDS_TOO_LARGE_431 = 431; - public final static int UNAVAILABLE_FOR_LEGAL_REASONS_451 = 451; + public static final int BAD_REQUEST_400 = 400; + public static final int UNAUTHORIZED_401 = 401; + public static final int PAYMENT_REQUIRED_402 = 402; + public static final int FORBIDDEN_403 = 403; + public static final int NOT_FOUND_404 = 404; + public static final int METHOD_NOT_ALLOWED_405 = 405; + public static final int NOT_ACCEPTABLE_406 = 406; + public static final int PROXY_AUTHENTICATION_REQUIRED_407 = 407; + public static final int REQUEST_TIMEOUT_408 = 408; + public static final int CONFLICT_409 = 409; + public static final int GONE_410 = 410; + public static final int LENGTH_REQUIRED_411 = 411; + public static final int PRECONDITION_FAILED_412 = 412; + public static final int PAYLOAD_TOO_LARGE_413 = 413; + public static final int URI_TOO_LONG_414 = 414; + public static final int UNSUPPORTED_MEDIA_TYPE_415 = 415; + public static final int RANGE_NOT_SATISFIABLE_416 = 416; + public static final int EXPECTATION_FAILED_417 = 417; + public static final int IM_A_TEAPOT_418 = 418; + public static final int ENHANCE_YOUR_CALM_420 = 420; + public static final int MISDIRECTED_REQUEST_421 = 421; + public static final int UNPROCESSABLE_ENTITY_422 = 422; + public static final int LOCKED_423 = 423; + public static final int FAILED_DEPENDENCY_424 = 424; + public static final int UPGRADE_REQUIRED_426 = 426; + public static final int PRECONDITION_REQUIRED_428 = 428; + public static final int TOO_MANY_REQUESTS_429 = 429; + public static final int REQUEST_HEADER_FIELDS_TOO_LARGE_431 = 431; + public static final int UNAVAILABLE_FOR_LEGAL_REASONS_451 = 451; + + public static final int INTERNAL_SERVER_ERROR_500 = 500; + public static final int NOT_IMPLEMENTED_501 = 501; + public static final int BAD_GATEWAY_502 = 502; + public static final int SERVICE_UNAVAILABLE_503 = 503; + public static final int GATEWAY_TIMEOUT_504 = 504; + public static final int HTTP_VERSION_NOT_SUPPORTED_505 = 505; + public static final int INSUFFICIENT_STORAGE_507 = 507; + public static final int LOOP_DETECTED_508 = 508; + public static final int NOT_EXTENDED_510 = 510; + public static final int NETWORK_AUTHENTICATION_REQUIRED_511 = 511; - public final static int INTERNAL_SERVER_ERROR_500 = 500; - public final static int NOT_IMPLEMENTED_501 = 501; - public final static int BAD_GATEWAY_502 = 502; - public final static int SERVICE_UNAVAILABLE_503 = 503; - public final static int GATEWAY_TIMEOUT_504 = 504; - public final static int HTTP_VERSION_NOT_SUPPORTED_505 = 505; - public final static int INSUFFICIENT_STORAGE_507 = 507; - public final static int LOOP_DETECTED_508 = 508; - public final static int NOT_EXTENDED_510 = 510; - public final static int NETWORK_AUTHENTICATION_REQUIRED_511 = 511; - public static final int MAX_CODE = 511; - private static final Code[] codeMap = new Code[MAX_CODE+1]; + private static final Code[] codeMap = new Code[MAX_CODE + 1]; static { @@ -102,14 +103,12 @@ public class HttpStatus } } - public enum Code { CONTINUE(CONTINUE_100, "Continue"), SWITCHING_PROTOCOLS(SWITCHING_PROTOCOLS_101, "Switching Protocols"), PROCESSING(PROCESSING_102, "Processing"), - OK(OK_200, "OK"), CREATED(CREATED_201, "Created"), ACCEPTED(ACCEPTED_202, "Accepted"), @@ -171,16 +170,16 @@ public class HttpStatus LOOP_DETECTED(LOOP_DETECTED_508, "Loop Detected"), NOT_EXTENDED(NOT_EXTENDED_510, "Not Extended"), NETWORK_AUTHENTICATION_REQUIRED(NETWORK_AUTHENTICATION_REQUIRED_511, "Network Authentication Required"), - + ; - + private final int _code; private final String _message; private Code(int code, String message) { this._code = code; - _message=message; + _message = message; } public int getCode() @@ -193,7 +192,6 @@ public class HttpStatus return _message; } - public boolean equals(int code) { return (this._code == code); @@ -202,7 +200,7 @@ public class HttpStatus @Override public String toString() { - return String.format("[%03d %s]",this._code,this.getMessage()); + return String.format("[%03d %s]", this._code, this.getMessage()); } /** @@ -213,7 +211,7 @@ public class HttpStatus * HTTP/1.1. * * @return true if within range of codes that belongs to - * Informational messages. + * Informational messages. */ public boolean isInformational() { @@ -228,7 +226,7 @@ public class HttpStatus * HTTP/1.1. * * @return true if within range of codes that belongs to - * Success messages. + * Success messages. */ public boolean isSuccess() { @@ -243,7 +241,7 @@ public class HttpStatus * HTTP/1.1. * * @return true if within range of codes that belongs to - * Redirection messages. + * Redirection messages. */ public boolean isRedirection() { @@ -258,7 +256,7 @@ public class HttpStatus * HTTP/1.1. * * @return true if within range of codes that belongs to - * Client Error messages. + * Client Error messages. */ public boolean isClientError() { @@ -273,7 +271,7 @@ public class HttpStatus * HTTP/1.1. * * @return true if within range of codes that belongs to - * Server Error messages. + * Server Error messages. */ public boolean isServerError() { @@ -281,12 +279,10 @@ public class HttpStatus } } - /** * Get the HttpStatusCode for a specific code * - * @param code - * the code to lookup. + * @param code the code to lookup. * @return the {@link HttpStatus} if found, or null if not found. */ public static Code getCode(int code) @@ -301,10 +297,9 @@ public class HttpStatus /** * Get the status message for a specific code. * - * @param code - * the code to look up + * @param code the code to look up * @return the specific message, or the code number itself if code - * does not match known list. + * does not match known list. */ public static String getMessage(int code) { @@ -325,10 +320,9 @@ public class HttpStatus * href="http://tools.ietf.org/html/rfc1945">RFC 1945 - HTTP/1.0, and RFC 7231 - HTTP/1.1. * - * @param code - * the code to test. + * @param code the code to test. * @return true if within range of codes that belongs to - * Informational messages. + * Informational messages. */ public static boolean isInformational(int code) { @@ -341,10 +335,9 @@ public class HttpStatus * href="http://tools.ietf.org/html/rfc1945">RFC 1945 - HTTP/1.0, and RFC 7231 - HTTP/1.1. * - * @param code - * the code to test. + * @param code the code to test. * @return true if within range of codes that belongs to - * Success messages. + * Success messages. */ public static boolean isSuccess(int code) { @@ -357,10 +350,9 @@ public class HttpStatus * href="http://tools.ietf.org/html/rfc1945">RFC 1945 - HTTP/1.0, and RFC 7231 - HTTP/1.1. * - * @param code - * the code to test. + * @param code the code to test. * @return true if within range of codes that belongs to - * Redirection messages. + * Redirection messages. */ public static boolean isRedirection(int code) { @@ -373,10 +365,9 @@ public class HttpStatus * href="http://tools.ietf.org/html/rfc1945">RFC 1945 - HTTP/1.0, and RFC 7231 - HTTP/1.1. * - * @param code - * the code to test. + * @param code the code to test. * @return true if within range of codes that belongs to - * Client Error messages. + * Client Error messages. */ public static boolean isClientError(int code) { @@ -389,10 +380,9 @@ public class HttpStatus * href="http://tools.ietf.org/html/rfc1945">RFC 1945 - HTTP/1.0, and RFC 7231 - HTTP/1.1. * - * @param code - * the code to test. + * @param code the code to test. * @return true if within range of codes that belongs to - * Server Error messages. + * Server Error messages. */ public static boolean isServerError(int code) { diff --git a/jetty-http/src/main/java/org/eclipse/jetty/http/HttpTokens.java b/jetty-http/src/main/java/org/eclipse/jetty/http/HttpTokens.java index 352a6e5cb12..61cdadd6193 100644 --- a/jetty-http/src/main/java/org/eclipse/jetty/http/HttpTokens.java +++ b/jetty-http/src/main/java/org/eclipse/jetty/http/HttpTokens.java @@ -25,18 +25,20 @@ import org.eclipse.jetty.util.TypeUtil; */ public class HttpTokens { - static final byte COLON= (byte)':'; - static final byte TAB= 0x09; - static final byte LINE_FEED= 0x0A; - static final byte CARRIAGE_RETURN= 0x0D; - static final byte SPACE= 0x20; - static final byte[] CRLF = {CARRIAGE_RETURN,LINE_FEED}; + static final byte COLON = (byte)':'; + static final byte TAB = 0x09; + static final byte LINE_FEED = 0x0A; + static final byte CARRIAGE_RETURN = 0x0D; + static final byte SPACE = 0x20; + static final byte[] CRLF = {CARRIAGE_RETURN, LINE_FEED}; - public enum EndOfContent { UNKNOWN_CONTENT,NO_CONTENT,EOF_CONTENT,CONTENT_LENGTH,CHUNKED_CONTENT } + public enum EndOfContent + { + UNKNOWN_CONTENT, NO_CONTENT, EOF_CONTENT, CONTENT_LENGTH, CHUNKED_CONTENT + } - - public enum Type - { + public enum Type + { CNTL, // Control characters excluding LF, CR HTAB, // Horizontal tab LF, // Line feed @@ -49,21 +51,21 @@ public class HttpTokens VCHAR, // Visible characters excluding COLON,DIGIT,ALPHA OTEXT // Obsolete text } - + public static class Token { private final Type _type; private final byte _b; private final char _c; private final int _x; - + private Token(byte b, Type type) { _type = type; _b = b; - _c = (char)(0xff&b); - char lc = (_c>='A' & _c<='Z')?((char)(_c-'A'+'a')):_c; - _x = (_type==Type.DIGIT || _type==Type.ALPHA && lc>='a' && lc<='f')?TypeUtil.convertHexDigit(b):-1; + _c = (char)(0xff & b); + char lc = (_c >= 'A' & _c <= 'Z') ? ((char)(_c - 'A' + 'a')) : _c; + _x = (_type == Type.DIGIT || _type == Type.ALPHA && lc >= 'a' && lc <= 'f') ? TypeUtil.convertHexDigit(b) : -1; } public Type getType() @@ -80,21 +82,21 @@ public class HttpTokens { return _c; } - + public boolean isHexDigit() { - return _x>=0; + return _x >= 0; } - + public int getHexDigit() { return _x; } - + @Override public String toString() { - switch(_type) + switch (_type) { case SPACE: case COLON: @@ -102,26 +104,25 @@ public class HttpTokens case DIGIT: case TCHAR: case VCHAR: - return _type+"='"+_c+"'"; - + return _type + "='" + _c + "'"; + case CR: return "CR=\\r"; - + case LF: return "LF=\\n"; - + default: - return String.format("%s=0x%x",_type,_b); + return String.format("%s=0x%x", _type, _b); } } - } - - public final static Token[] TOKENS = new Token[256]; + + public static final Token[] TOKENS = new Token[256]; static { - for (int b=0; b<256; b++) + for (int b = 0; b < 256; b++) { // token = 1*tchar // tchar = "!" / "#" / "$" / "%" / "&" / "'" / "*" @@ -134,56 +135,56 @@ public class HttpTokens // comment = "(" *( ctext / quoted-pair / comment ) ")" // ctext = HTAB / SP / %x21-27 / %x2A-5B / %x5D-7E / obs-text // quoted-pair = "\" ( HTAB / SP / VCHAR / obs-text ) - + switch (b) { - case LINE_FEED: - TOKENS[b] = new Token((byte)b,Type.LF); + case LINE_FEED: + TOKENS[b] = new Token((byte)b, Type.LF); break; - case CARRIAGE_RETURN: - TOKENS[b] = new Token((byte)b,Type.CR); + case CARRIAGE_RETURN: + TOKENS[b] = new Token((byte)b, Type.CR); break; - case SPACE: - TOKENS[b] = new Token((byte)b,Type.SPACE); + case SPACE: + TOKENS[b] = new Token((byte)b, Type.SPACE); break; - case TAB: - TOKENS[b] = new Token((byte)b,Type.HTAB); + case TAB: + TOKENS[b] = new Token((byte)b, Type.HTAB); break; - case COLON: - TOKENS[b] = new Token((byte)b,Type.COLON); + case COLON: + TOKENS[b] = new Token((byte)b, Type.COLON); break; - - case '!': - case '#': - case '$': - case '%': - case '&': - case '\'': - case '*': - case '+': - case '-': - case '.': - case '^': - case '_': - case '`': - case '|': - case '~': - TOKENS[b] = new Token((byte)b,Type.TCHAR); + + case '!': + case '#': + case '$': + case '%': + case '&': + case '\'': + case '*': + case '+': + case '-': + case '.': + case '^': + case '_': + case '`': + case '|': + case '~': + TOKENS[b] = new Token((byte)b, Type.TCHAR); break; - + default: - if (b>=0x30 &&b<=0x39) // DIGIT - TOKENS[b] = new Token((byte)b,Type.DIGIT); - else if (b>=0x41 &&b<=0x5A) // ALPHA (uppercase) - TOKENS[b] = new Token((byte)b,Type.ALPHA); - else if (b>=0x61 &&b<=0x7A) // ALPHA (lowercase) - TOKENS[b] = new Token((byte)b,Type.ALPHA); - else if (b>=0x21 &&b<=0x7E) // Visible - TOKENS[b] = new Token((byte)b,Type.VCHAR); - else if (b>=0x80) // OBS - TOKENS[b] = new Token((byte)b,Type.OTEXT); + if (b >= 0x30 && b <= 0x39) // DIGIT + TOKENS[b] = new Token((byte)b, Type.DIGIT); + else if (b >= 0x41 && b <= 0x5A) // ALPHA (uppercase) + TOKENS[b] = new Token((byte)b, Type.ALPHA); + else if (b >= 0x61 && b <= 0x7A) // ALPHA (lowercase) + TOKENS[b] = new Token((byte)b, Type.ALPHA); + else if (b >= 0x21 && b <= 0x7E) // Visible + TOKENS[b] = new Token((byte)b, Type.VCHAR); + else if (b >= 0x80) // OBS + TOKENS[b] = new Token((byte)b, Type.OTEXT); else - TOKENS[b] = new Token((byte)b,Type.CNTL); + TOKENS[b] = new Token((byte)b, Type.CNTL); } } } diff --git a/jetty-http/src/main/java/org/eclipse/jetty/http/HttpURI.java b/jetty-http/src/main/java/org/eclipse/jetty/http/HttpURI.java index 0a7a6f6ec3d..72c9bc8ed4c 100644 --- a/jetty-http/src/main/java/org/eclipse/jetty/http/HttpURI.java +++ b/jetty-http/src/main/java/org/eclipse/jetty/http/HttpURI.java @@ -29,9 +29,8 @@ import org.eclipse.jetty.util.TypeUtil; import org.eclipse.jetty.util.URIUtil; import org.eclipse.jetty.util.UrlEncoded; - -/* ------------------------------------------------------------ */ -/** Http URI. +/** + * Http URI. * Parse a HTTP URI from a string or byte array. Given a URI * http://user@host:port/path/info;param?query#fragment * this class will split it into the following undecoded optional elements:
      @@ -44,25 +43,29 @@ import org.eclipse.jetty.util.UrlEncoded; *
    • {@link #getQuery()} - query
    • *
    • {@link #getFragment()} - fragment
    • *
    - * + * *

    Any parameters will be returned from {@link #getPath()}, but are excluded from the - * return value of {@link #getDecodedPath()}. If there are multiple parameters, the + * return value of {@link #getDecodedPath()}. If there are multiple parameters, the * {@link #getParam()} method returns only the last one. */ public class HttpURI { - private enum State { - START, - HOST_OR_PATH, - SCHEME_OR_PATH, - HOST, - IPV6, - PORT, - PATH, - PARAM, - QUERY, - FRAGMENT, - ASTERISK}; + private enum State + { + START, + HOST_OR_PATH, + SCHEME_OR_PATH, + HOST, + IPV6, + PORT, + PATH, + PARAM, + QUERY, + FRAGMENT, + ASTERISK + } + + ; private String _scheme; private String _user; @@ -72,14 +75,14 @@ public class HttpURI private String _param; private String _query; private String _fragment; - + String _uri; String _decodedPath; - /* ------------------------------------------------------------ */ /** * Construct a normalized URI. * Port is not set if it is the default port. + * * @param scheme the URI scheme * @param host the URI hose * @param port the URI port @@ -91,19 +94,17 @@ public class HttpURI */ public static HttpURI createHttpURI(String scheme, String host, int port, String path, String param, String query, String fragment) { - if (port==80 && HttpScheme.HTTP.is(scheme)) - port=0; - if (port==443 && HttpScheme.HTTPS.is(scheme)) - port=0; - return new HttpURI(scheme,host,port,path,param,query,fragment); + if (port == 80 && HttpScheme.HTTP.is(scheme)) + port = 0; + if (port == 443 && HttpScheme.HTTPS.is(scheme)) + port = 0; + return new HttpURI(scheme, host, port, path, param, query, fragment); } - - /* ------------------------------------------------------------ */ + public HttpURI() { } - /* ------------------------------------------------------------ */ public HttpURI(String scheme, String host, int port, String path, String param, String query, String fragment) { _scheme = scheme; @@ -115,33 +116,30 @@ public class HttpURI _fragment = fragment; } - /* ------------------------------------------------------------ */ public HttpURI(HttpURI uri) { - this(uri._scheme,uri._host,uri._port,uri._path,uri._param,uri._query,uri._fragment); - _uri=uri._uri; - } - - /* ------------------------------------------------------------ */ - public HttpURI(String uri) - { - _port=-1; - parse(State.START,uri); + this(uri._scheme, uri._host, uri._port, uri._path, uri._param, uri._query, uri._fragment); + _uri = uri._uri; + } + + public HttpURI(String uri) + { + _port = -1; + parse(State.START, uri); } - /* ------------------------------------------------------------ */ public HttpURI(URI uri) { - _uri=null; - - _scheme=uri.getScheme(); - _host=uri.getHost(); - if (_host==null && uri.getRawSchemeSpecificPart().startsWith("//")) - _host=""; - _port=uri.getPort(); + _uri = null; + + _scheme = uri.getScheme(); + _host = uri.getHost(); + if (_host == null && uri.getRawSchemeSpecificPart().startsWith("//")) + _host = ""; + _port = uri.getPort(); _user = uri.getUserInfo(); - _path=uri.getRawPath(); - + _path = uri.getRawPath(); + _decodedPath = uri.getPath(); if (_decodedPath != null) { @@ -149,114 +147,109 @@ public class HttpURI if (p >= 0) _param = _decodedPath.substring(p + 1); } - _query=uri.getRawQuery(); - _fragment=uri.getFragment(); - - _decodedPath=null; + _query = uri.getRawQuery(); + _fragment = uri.getFragment(); + + _decodedPath = null; } - /* ------------------------------------------------------------ */ public HttpURI(String scheme, String host, int port, String pathQuery) { - _uri=null; - - _scheme=scheme; - _host=host; - _port=port; + _uri = null; - parse(State.PATH,pathQuery); - + _scheme = scheme; + _host = host; + _port = port; + + parse(State.PATH, pathQuery); } - /* ------------------------------------------------------------ */ public void parse(String uri) { clear(); - _uri=uri; - parse(State.START,uri); + _uri = uri; + parse(State.START, uri); } - /* ------------------------------------------------------------ */ /** * Parse according to https://tools.ietf.org/html/rfc7230#section-5.3 + * * @param method the request method * @param uri the request uri */ - public void parseRequestTarget(String method,String uri) + public void parseRequestTarget(String method, String uri) { clear(); - _uri=uri; + _uri = uri; if (HttpMethod.CONNECT.is(method)) - _path=uri; + _path = uri; else - parse(uri.startsWith("/")?State.PATH:State.START,uri); + parse(uri.startsWith("/") ? State.PATH : State.START, uri); } - /* ------------------------------------------------------------ */ public void parse(String uri, int offset, int length) { clear(); - int end=offset+length; - _uri=uri.substring(offset,end); - parse(State.START,uri); + int end = offset + length; + _uri = uri.substring(offset, end); + parse(State.START, uri); } - /* ------------------------------------------------------------ */ private void parse(State state, final String uri) { - boolean encoded=false; - int end=uri.length(); - int mark=0; - int path_mark=0; - char last='/'; - for (int i=0; i mark) - _host=uri.substring(mark,i); - mark=i+1; - state=State.PORT; + _host = uri.substring(mark, i); + mark = i + 1; + state = State.PORT; break; case '@': - if (_user!=null) + if (_user != null) throw new IllegalArgumentException("Bad authority"); - _user=uri.substring(mark,i); - mark=i+1; + _user = uri.substring(mark, i); + mark = i + 1; break; - + case '[': - state=State.IPV6; + state = State.IPV6; break; } break; @@ -380,16 +373,16 @@ public class HttpURI throw new IllegalArgumentException("No closing ']' for ipv6 in " + uri); case ']': c = uri.charAt(++i); - _host=uri.substring(mark,i); + _host = uri.substring(mark, i); if (c == ':') { - mark=i+1; - state=State.PORT; + mark = i + 1; + state = State.PORT; } else { - path_mark=mark=i; - state=State.PATH; + pathMark = mark = i; + state = State.PATH; } break; } @@ -399,20 +392,20 @@ public class HttpURI case PORT: { - if (c=='@') + if (c == '@') { - if (_user!=null) + if (_user != null) throw new IllegalArgumentException("Bad authority"); // It wasn't a port, but a password! - _user=_host+":"+uri.substring(mark,i); - mark=i+1; - state=State.HOST; + _user = _host + ":" + uri.substring(mark, i); + mark = i + 1; + state = State.HOST; } - else if (c=='/') + else if (c == '/') { - _port=TypeUtil.parseInt(uri,mark,i-mark,10); - path_mark=mark=i; - state=State.PATH; + _port = TypeUtil.parseInt(uri, mark, i - mark, 10); + pathMark = mark = i; + state = State.PATH; } break; } @@ -422,56 +415,53 @@ public class HttpURI switch (c) { case ';': - mark=i+1; - state=State.PARAM; + mark = i + 1; + state = State.PARAM; break; case '?': - _path=uri.substring(path_mark,i); - mark=i+1; - state=State.QUERY; + _path = uri.substring(pathMark, i); + mark = i + 1; + state = State.QUERY; break; case '#': - _path=uri.substring(path_mark,i); - mark=i+1; - state=State.FRAGMENT; + _path = uri.substring(pathMark, i); + mark = i + 1; + state = State.FRAGMENT; break; case '%': - encoded=true; + encoded = true; break; case '.': - if ('/'==last) - encoded=true; + if ('/' == last) + encoded = true; } break; } - - - case PARAM: { switch (c) { case '?': - _path=uri.substring(path_mark,i); - _param=uri.substring(mark,i); - mark=i+1; - state=State.QUERY; + _path = uri.substring(pathMark, i); + _param = uri.substring(mark, i); + mark = i + 1; + state = State.QUERY; break; case '#': - _path=uri.substring(path_mark,i); - _param=uri.substring(mark,i); - mark=i+1; - state=State.FRAGMENT; + _path = uri.substring(pathMark, i); + _param = uri.substring(mark, i); + mark = i + 1; + state = State.FRAGMENT; break; case '/': - encoded=true; + encoded = true; // ignore internal params - state=State.PATH; + state = State.PATH; break; case ';': // multiple parameters - mark=i+1; + mark = i + 1; break; } break; @@ -479,11 +469,11 @@ public class HttpURI case QUERY: { - if (c=='#') + if (c == '#') { - _query=uri.substring(mark,i); - mark=i+1; - state=State.FRAGMENT; + _query = uri.substring(mark, i); + mark = i + 1; + state = State.FRAGMENT; } break; } @@ -492,97 +482,92 @@ public class HttpURI { throw new IllegalArgumentException("Bad character '*'"); } - + case FRAGMENT: { - _fragment=uri.substring(mark,end); - i=end; + _fragment = uri.substring(mark, end); + i = end; break; } } - last=c; + last = c; } - - switch(state) + switch (state) { case START: break; case SCHEME_OR_PATH: - _path=uri.substring(mark,end); + _path = uri.substring(mark, end); break; case HOST_OR_PATH: - _path=uri.substring(mark,end); + _path = uri.substring(mark, end); break; - + case HOST: - if(end>mark) - _host=uri.substring(mark,end); + if (end > mark) + _host = uri.substring(mark, end); break; - + case IPV6: throw new IllegalArgumentException("No closing ']' for ipv6 in " + uri); case PORT: - _port=TypeUtil.parseInt(uri,mark,end-mark,10); + _port = TypeUtil.parseInt(uri, mark, end - mark, 10); break; - + case ASTERISK: break; - + case FRAGMENT: - _fragment=uri.substring(mark,end); + _fragment = uri.substring(mark, end); break; - + case PARAM: - _path=uri.substring(path_mark,end); - _param=uri.substring(mark,end); + _path = uri.substring(pathMark, end); + _param = uri.substring(mark, end); break; - + case PATH: - _path=uri.substring(path_mark,end); + _path = uri.substring(pathMark, end); break; - + case QUERY: - _query=uri.substring(mark,end); + _query = uri.substring(mark, end); break; } - + if (!encoded) { - if (_param==null) - _decodedPath=_path; + if (_param == null) + _decodedPath = _path; else - _decodedPath=_path.substring(0,_path.length()-_param.length()-1); + _decodedPath = _path.substring(0, _path.length() - _param.length() - 1); } } - /* ------------------------------------------------------------ */ public String getScheme() { return _scheme; } - /* ------------------------------------------------------------ */ public String getHost() { // Return null for empty host to retain compatibility with java.net.URI - if (_host!=null && _host.isEmpty()) + if (_host != null && _host.isEmpty()) return null; return _host; } - /* ------------------------------------------------------------ */ public int getPort() { return _port; } - /* ------------------------------------------------------------ */ /** * The parsed Path. - * + * * @return the path as parsed on valid URI. null for invalid URI. */ public String getPath() @@ -590,97 +575,86 @@ public class HttpURI return _path; } - /* ------------------------------------------------------------ */ public String getDecodedPath() { - if (_decodedPath==null && _path!=null) - _decodedPath=URIUtil.canonicalPath(URIUtil.decodePath(_path)); + if (_decodedPath == null && _path != null) + _decodedPath = URIUtil.canonicalPath(URIUtil.decodePath(_path)); return _decodedPath; } - /* ------------------------------------------------------------ */ public String getParam() { return _param; } - /* ------------------------------------------------------------ */ public String getQuery() { return _query; } - /* ------------------------------------------------------------ */ public boolean hasQuery() { - return _query!=null && !_query.isEmpty(); + return _query != null && !_query.isEmpty(); } - /* ------------------------------------------------------------ */ public String getFragment() { return _fragment; } - /* ------------------------------------------------------------ */ public void decodeQueryTo(MultiMap parameters) { - if (_query==null) + if (_query == null) return; - UrlEncoded.decodeUtf8To(_query,parameters); + UrlEncoded.decodeUtf8To(_query, parameters); } - /* ------------------------------------------------------------ */ public void decodeQueryTo(MultiMap parameters, String encoding) throws UnsupportedEncodingException { - decodeQueryTo(parameters,Charset.forName(encoding)); + decodeQueryTo(parameters, Charset.forName(encoding)); } - /* ------------------------------------------------------------ */ public void decodeQueryTo(MultiMap parameters, Charset encoding) throws UnsupportedEncodingException { - if (_query==null) + if (_query == null) return; - if (encoding==null || StandardCharsets.UTF_8.equals(encoding)) - UrlEncoded.decodeUtf8To(_query,parameters); + if (encoding == null || StandardCharsets.UTF_8.equals(encoding)) + UrlEncoded.decodeUtf8To(_query, parameters); else - UrlEncoded.decodeTo(_query,parameters,encoding); + UrlEncoded.decodeTo(_query, parameters, encoding); } - /* ------------------------------------------------------------ */ public void clear() { - _uri=null; + _uri = null; - _scheme=null; - _host=null; - _port=-1; - _path=null; - _param=null; - _query=null; - _fragment=null; + _scheme = null; + _host = null; + _port = -1; + _path = null; + _param = null; + _query = null; + _fragment = null; - _decodedPath=null; + _decodedPath = null; } - /* ------------------------------------------------------------ */ public boolean isAbsolute() { - return _scheme!=null && !_scheme.isEmpty(); + return _scheme != null && !_scheme.isEmpty(); } - - /* ------------------------------------------------------------ */ + @Override public String toString() { - if (_uri==null) + if (_uri == null) { StringBuilder out = new StringBuilder(); - - if (_scheme!=null) + + if (_scheme != null) out.append(_scheme).append(':'); - + if (_host != null) { out.append("//"); @@ -688,138 +662,124 @@ public class HttpURI out.append(_user).append('@'); out.append(_host); } - - if (_port>0) + + if (_port > 0) out.append(':').append(_port); - - if (_path!=null) + + if (_path != null) out.append(_path); - - if (_query!=null) + + if (_query != null) out.append('?').append(_query); - - if (_fragment!=null) + + if (_fragment != null) out.append('#').append(_fragment); - - if (out.length()>0) - _uri=out.toString(); + + if (out.length() > 0) + _uri = out.toString(); else - _uri=""; + _uri = ""; } return _uri; } - /* ------------------------------------------------------------ */ @Override public boolean equals(Object o) { - if (o==this) + if (o == this) return true; if (!(o instanceof HttpURI)) return false; return toString().equals(o.toString()); } - /* ------------------------------------------------------------ */ public void setScheme(String scheme) { - _scheme=scheme; - _uri=null; + _scheme = scheme; + _uri = null; } - - /* ------------------------------------------------------------ */ + /** * @param host the host * @param port the port */ public void setAuthority(String host, int port) { - _host=host; - _port=port; - _uri=null; + _host = host; + _port = port; + _uri = null; } - /* ------------------------------------------------------------ */ /** * @param path the path */ public void setPath(String path) { - _uri=null; - _path=path; - _decodedPath=null; + _uri = null; + _path = path; + _decodedPath = null; } - - /* ------------------------------------------------------------ */ + /** * @param path the decoded path */ public void setDecodedPath(String path) { - _uri=null; - _path=URIUtil.encodePath(path); - _decodedPath=path; + _uri = null; + _path = URIUtil.encodePath(path); + _decodedPath = path; } - /* ------------------------------------------------------------ */ public void setPathQuery(String path) { - _uri=null; - _path=null; - _decodedPath=null; - _param=null; - _fragment=null; - if (path!=null) - parse(State.PATH,path); - } - - /* ------------------------------------------------------------ */ - public void setQuery(String query) - { - _query=query; - _uri=null; + _uri = null; + _path = null; + _decodedPath = null; + _param = null; + _fragment = null; + if (path != null) + parse(State.PATH, path); + } + + public void setQuery(String query) + { + _query = query; + _uri = null; } - /* ------------------------------------------------------------ */ public URI toURI() { try { - return new URI(_scheme,null,_host,_port,_path,_query==null?null:UrlEncoded.decodeString(_query),_fragment); + return new URI(_scheme, null, _host, _port, _path, _query == null ? null : UrlEncoded.decodeString(_query), _fragment); } - catch(URISyntaxException x) + catch (URISyntaxException x) { throw new RuntimeException(x); } } - /* ------------------------------------------------------------ */ public String getPathQuery() { - if (_query==null) + if (_query == null) return _path; - return _path+"?"+_query; + return _path + "?" + _query; } - /* ------------------------------------------------------------ */ public boolean hasAuthority() { - return _host!=null; + return _host != null; } - /* ------------------------------------------------------------ */ public String getAuthority() { - if (_port>0) - return _host+":"+_port; + if (_port > 0) + return _host + ":" + _port; return _host; } - - /* ------------------------------------------------------------ */ + public String getUser() { return _user; } - - } diff --git a/jetty-http/src/main/java/org/eclipse/jetty/http/HttpVersion.java b/jetty-http/src/main/java/org/eclipse/jetty/http/HttpVersion.java index 9a9faf7c479..762372ef5cc 100644 --- a/jetty-http/src/main/java/org/eclipse/jetty/http/HttpVersion.java +++ b/jetty-http/src/main/java/org/eclipse/jetty/http/HttpVersion.java @@ -24,26 +24,26 @@ import org.eclipse.jetty.util.ArrayTrie; import org.eclipse.jetty.util.StringUtil; import org.eclipse.jetty.util.Trie; - -/* ------------------------------------------------------------------------------- */ public enum HttpVersion { - HTTP_0_9("HTTP/0.9",9), - HTTP_1_0("HTTP/1.0",10), - HTTP_1_1("HTTP/1.1",11), - HTTP_2("HTTP/2.0",20); + HTTP_0_9("HTTP/0.9", 9), + HTTP_1_0("HTTP/1.0", 10), + HTTP_1_1("HTTP/1.1", 11), + HTTP_2("HTTP/2.0", 20); + + public static final Trie CACHE = new ArrayTrie(); - /* ------------------------------------------------------------ */ - public final static Trie CACHE= new ArrayTrie(); static { for (HttpVersion version : HttpVersion.values()) - CACHE.put(version.toString(),version); + { + CACHE.put(version.toString(), version); + } } - /* ------------------------------------------------------------ */ - /** + /** * Optimised lookup to find a Http Version and whitespace in a byte array. + * * @param bytes Array containing ISO-8859-1 characters * @param position The first valid index * @param limit The first non valid index @@ -51,18 +51,18 @@ public enum HttpVersion */ public static HttpVersion lookAheadGet(byte[] bytes, int position, int limit) { - int length=limit-position; - if (length<9) + int length = limit - position; + if (length < 9) return null; - if (bytes[position+4]=='/' && bytes[position+6]=='.' && Character.isWhitespace((char)bytes[position+8]) && - ((bytes[position]=='H' && bytes[position+1]=='T' && bytes[position+2]=='T' && bytes[position+3]=='P') || - (bytes[position]=='h' && bytes[position+1]=='t' && bytes[position+2]=='t' && bytes[position+3]=='p'))) + if (bytes[position + 4] == '/' && bytes[position + 6] == '.' && Character.isWhitespace((char)bytes[position + 8]) && + ((bytes[position] == 'H' && bytes[position + 1] == 'T' && bytes[position + 2] == 'T' && bytes[position + 3] == 'P') || + (bytes[position] == 'h' && bytes[position + 1] == 't' && bytes[position + 2] == 't' && bytes[position + 3] == 'p'))) { - switch(bytes[position+5]) + switch (bytes[position + 5]) { case '1': - switch(bytes[position+7]) + switch (bytes[position + 7]) { case '0': return HTTP_1_0; @@ -71,7 +71,7 @@ public enum HttpVersion } break; case '2': - switch(bytes[position+7]) + switch (bytes[position + 7]) { case '0': return HTTP_2; @@ -79,69 +79,61 @@ public enum HttpVersion break; } } - + return null; } - /* ------------------------------------------------------------ */ - /** + /** * Optimised lookup to find a HTTP Version and trailing white space in a byte array. + * * @param buffer buffer containing ISO-8859-1 characters * @return A HttpVersion if a match or null if no easy match. */ public static HttpVersion lookAheadGet(ByteBuffer buffer) { if (buffer.hasArray()) - return lookAheadGet(buffer.array(),buffer.arrayOffset()+buffer.position(),buffer.arrayOffset()+buffer.limit()); + return lookAheadGet(buffer.array(), buffer.arrayOffset() + buffer.position(), buffer.arrayOffset() + buffer.limit()); return null; } - - + private final String _string; private final byte[] _bytes; private final ByteBuffer _buffer; private final int _version; - /* ------------------------------------------------------------ */ - HttpVersion(String s,int version) + HttpVersion(String s, int version) { - _string=s; - _bytes=StringUtil.getBytes(s); - _buffer=ByteBuffer.wrap(_bytes); - _version=version; + _string = s; + _bytes = StringUtil.getBytes(s); + _buffer = ByteBuffer.wrap(_bytes); + _version = version; } - /* ------------------------------------------------------------ */ public byte[] toBytes() { return _bytes; } - /* ------------------------------------------------------------ */ public ByteBuffer toBuffer() { return _buffer.asReadOnlyBuffer(); } - /* ------------------------------------------------------------ */ public int getVersion() { return _version; } - /* ------------------------------------------------------------ */ public boolean is(String s) { - return _string.equalsIgnoreCase(s); + return _string.equalsIgnoreCase(s); } - - /* ------------------------------------------------------------ */ + public String asString() { return _string; } - - /* ------------------------------------------------------------ */ + @Override public String toString() { @@ -150,6 +142,7 @@ public enum HttpVersion /** * Case insensitive fromString() conversion + * * @param version the String to convert to enum constant * @return the enum constant or null if version unknown */ @@ -158,16 +151,20 @@ public enum HttpVersion return CACHE.get(version); } - /* ------------------------------------------------------------ */ public static HttpVersion fromVersion(int version) { - switch(version) + switch (version) { - case 9: return HttpVersion.HTTP_0_9; - case 10: return HttpVersion.HTTP_1_0; - case 11: return HttpVersion.HTTP_1_1; - case 20: return HttpVersion.HTTP_2; - default: throw new IllegalArgumentException(); + case 9: + return HttpVersion.HTTP_0_9; + case 10: + return HttpVersion.HTTP_1_0; + case 11: + return HttpVersion.HTTP_1_1; + case 20: + return HttpVersion.HTTP_2; + default: + throw new IllegalArgumentException(); } } } diff --git a/jetty-http/src/main/java/org/eclipse/jetty/http/MetaData.java b/jetty-http/src/main/java/org/eclipse/jetty/http/MetaData.java index 11ad1149340..cc9cac1d6ed 100644 --- a/jetty-http/src/main/java/org/eclipse/jetty/http/MetaData.java +++ b/jetty-http/src/main/java/org/eclipse/jetty/http/MetaData.java @@ -125,7 +125,9 @@ public class MetaData implements Iterable { StringBuilder out = new StringBuilder(); for (HttpField field : this) + { out.append(field).append(System.lineSeparator()); + } return out.toString(); } @@ -153,31 +155,31 @@ public class MetaData implements Iterable public Request(String method, HttpScheme scheme, HostPortHttpField hostPort, String uri, HttpVersion version, HttpFields fields) { - this(method, new HttpURI(scheme == null ? null : scheme.asString(), - hostPort==null?null:hostPort.getHost(), - hostPort==null?-1:hostPort.getPort(), + this(method, new HttpURI(scheme == null ? null : scheme.asString(), + hostPort == null ? null : hostPort.getHost(), + hostPort == null ? -1 : hostPort.getPort(), uri), version, fields); } public Request(String method, HttpScheme scheme, HostPortHttpField hostPort, String uri, HttpVersion version, HttpFields fields, long contentLength) { - this(method, new HttpURI(scheme==null?null:scheme.asString(), - hostPort==null?null:hostPort.getHost(), - hostPort==null?-1:hostPort.getPort(), + this(method, new HttpURI(scheme == null ? null : scheme.asString(), + hostPort == null ? null : hostPort.getHost(), + hostPort == null ? -1 : hostPort.getPort(), uri), version, fields, contentLength); } public Request(String method, String scheme, HostPortHttpField hostPort, String uri, HttpVersion version, HttpFields fields, long contentLength) { this(method, new HttpURI(scheme, - hostPort==null?null:hostPort.getHost(), - hostPort==null?-1:hostPort.getPort(), + hostPort == null ? null : hostPort.getHost(), + hostPort == null ? -1 : hostPort.getPort(), uri), version, fields, contentLength); } public Request(Request request) { - this(request.getMethod(),new HttpURI(request.getURI()), request.getHttpVersion(), new HttpFields(request.getFields()), request.getContentLength()); + this(request.getMethod(), new HttpURI(request.getURI()), request.getHttpVersion(), new HttpFields(request.getFields()), request.getContentLength()); } @Override @@ -240,7 +242,7 @@ public class MetaData implements Iterable { HttpFields fields = getFields(); return String.format("%s{u=%s,%s,h=%d,cl=%d}", - getMethod(), getURI(), getHttpVersion(), fields == null ? -1 : fields.size(), getContentLength()); + getMethod(), getURI(), getHttpVersion(), fields == null ? -1 : fields.size(), getContentLength()); } } diff --git a/jetty-http/src/main/java/org/eclipse/jetty/http/MimeTypes.java b/jetty-http/src/main/java/org/eclipse/jetty/http/MimeTypes.java index 94674a9b72a..4f3bf0b69df 100644 --- a/jetty-http/src/main/java/org/eclipse/jetty/http/MimeTypes.java +++ b/jetty-http/src/main/java/org/eclipse/jetty/http/MimeTypes.java @@ -39,20 +39,18 @@ import org.eclipse.jetty.util.Trie; import org.eclipse.jetty.util.log.Log; import org.eclipse.jetty.util.log.Logger; - -/* ------------------------------------------------------------ */ -/** MIME Type enum and utilities - * +/** + * MIME Type enum and utilities */ public class MimeTypes { - /* ------------------------------------------------------------ */ + private static final Logger LOG = Log.getLogger(MimeTypes.class); - private static final Trie TYPES= new ArrayTrie(512); - private static final Map __dftMimeMap = new HashMap(); - private static final Map __inferredEncodings = new HashMap(); - private static final Map __assumedEncodings = new HashMap(); - + private static final Trie TYPES = new ArrayTrie(512); + private static final Map __dftMimeMap = new HashMap(); + private static final Map __inferredEncodings = new HashMap(); + private static final Map __assumedEncodings = new HashMap(); + public enum Type { FORM_ENCODED("application/x-www-form-urlencoded"), @@ -63,26 +61,24 @@ public class MimeTypes TEXT_HTML("text/html"), TEXT_PLAIN("text/plain"), TEXT_XML("text/xml"), - TEXT_JSON("text/json",StandardCharsets.UTF_8), - APPLICATION_JSON("application/json",StandardCharsets.UTF_8), + TEXT_JSON("text/json", StandardCharsets.UTF_8), + APPLICATION_JSON("application/json", StandardCharsets.UTF_8), - TEXT_HTML_8859_1("text/html;charset=iso-8859-1",TEXT_HTML), - TEXT_HTML_UTF_8("text/html;charset=utf-8",TEXT_HTML), + TEXT_HTML_8859_1("text/html;charset=iso-8859-1", TEXT_HTML), + TEXT_HTML_UTF_8("text/html;charset=utf-8", TEXT_HTML), - TEXT_PLAIN_8859_1("text/plain;charset=iso-8859-1",TEXT_PLAIN), - TEXT_PLAIN_UTF_8("text/plain;charset=utf-8",TEXT_PLAIN), + TEXT_PLAIN_8859_1("text/plain;charset=iso-8859-1", TEXT_PLAIN), + TEXT_PLAIN_UTF_8("text/plain;charset=utf-8", TEXT_PLAIN), - TEXT_XML_8859_1("text/xml;charset=iso-8859-1",TEXT_XML), - TEXT_XML_UTF_8("text/xml;charset=utf-8",TEXT_XML), + TEXT_XML_8859_1("text/xml;charset=iso-8859-1", TEXT_XML), + TEXT_XML_UTF_8("text/xml;charset=utf-8", TEXT_XML), - TEXT_JSON_8859_1("text/json;charset=iso-8859-1",TEXT_JSON), - TEXT_JSON_UTF_8("text/json;charset=utf-8",TEXT_JSON), + TEXT_JSON_8859_1("text/json;charset=iso-8859-1", TEXT_JSON), + TEXT_JSON_UTF_8("text/json;charset=utf-8", TEXT_JSON), - APPLICATION_JSON_8859_1("application/json;charset=iso-8859-1",APPLICATION_JSON), - APPLICATION_JSON_UTF_8("application/json;charset=utf-8",APPLICATION_JSON); + APPLICATION_JSON_8859_1("application/json;charset=iso-8859-1", APPLICATION_JSON), + APPLICATION_JSON_UTF_8("application/json;charset=utf-8", APPLICATION_JSON); - - /* ------------------------------------------------------------ */ private final String _string; private final Type _base; private final ByteBuffer _buffer; @@ -91,118 +87,106 @@ public class MimeTypes private final boolean _assumedCharset; private final HttpField _field; - /* ------------------------------------------------------------ */ Type(String s) { - _string=s; - _buffer=BufferUtil.toBuffer(s); - _base=this; - _charset=null; - _charsetString=null; - _assumedCharset=false; - _field=new PreEncodedHttpField(HttpHeader.CONTENT_TYPE,_string); + _string = s; + _buffer = BufferUtil.toBuffer(s); + _base = this; + _charset = null; + _charsetString = null; + _assumedCharset = false; + _field = new PreEncodedHttpField(HttpHeader.CONTENT_TYPE, _string); } - /* ------------------------------------------------------------ */ - Type(String s,Type base) + Type(String s, Type base) { - _string=s; - _buffer=BufferUtil.toBuffer(s); - _base=base; - int i=s.indexOf(";charset="); - _charset=Charset.forName(s.substring(i+9)); - _charsetString=_charset.toString().toLowerCase(Locale.ENGLISH); - _assumedCharset=false; - _field=new PreEncodedHttpField(HttpHeader.CONTENT_TYPE,_string); + _string = s; + _buffer = BufferUtil.toBuffer(s); + _base = base; + int i = s.indexOf(";charset="); + _charset = Charset.forName(s.substring(i + 9)); + _charsetString = _charset.toString().toLowerCase(Locale.ENGLISH); + _assumedCharset = false; + _field = new PreEncodedHttpField(HttpHeader.CONTENT_TYPE, _string); } - /* ------------------------------------------------------------ */ - Type(String s,Charset cs) + Type(String s, Charset cs) { - _string=s; - _base=this; - _buffer=BufferUtil.toBuffer(s); - _charset=cs; - _charsetString=_charset==null?null:_charset.toString().toLowerCase(Locale.ENGLISH); - _assumedCharset=true; - _field=new PreEncodedHttpField(HttpHeader.CONTENT_TYPE,_string); + _string = s; + _base = this; + _buffer = BufferUtil.toBuffer(s); + _charset = cs; + _charsetString = _charset == null ? null : _charset.toString().toLowerCase(Locale.ENGLISH); + _assumedCharset = true; + _field = new PreEncodedHttpField(HttpHeader.CONTENT_TYPE, _string); } - /* ------------------------------------------------------------ */ public ByteBuffer asBuffer() { return _buffer.asReadOnlyBuffer(); } - /* ------------------------------------------------------------ */ public Charset getCharset() { return _charset; } - /* ------------------------------------------------------------ */ public String getCharsetString() { return _charsetString; } - /* ------------------------------------------------------------ */ public boolean is(String s) { return _string.equalsIgnoreCase(s); } - /* ------------------------------------------------------------ */ public String asString() { return _string; } - /* ------------------------------------------------------------ */ @Override public String toString() { return _string; } - /* ------------------------------------------------------------ */ public boolean isCharsetAssumed() { return _assumedCharset; } - /* ------------------------------------------------------------ */ public HttpField getContentTypeField() { return _field; } - /* ------------------------------------------------------------ */ public Type getBaseType() { return _base; } } - /* ------------------------------------------------------------ */ - public static final Trie CACHE= new ArrayTrie<>(512); + public static final Trie CACHE = new ArrayTrie<>(512); + static { for (MimeTypes.Type type : MimeTypes.Type.values()) { - CACHE.put(type.toString(),type); - TYPES.put(type.toString(),type.asBuffer()); + CACHE.put(type.toString(), type); + TYPES.put(type.toString(), type.asBuffer()); - int charset=type.toString().indexOf(";charset="); - if (charset>0) + int charset = type.toString().indexOf(";charset="); + if (charset > 0) { String alt = StringUtil.replace(type.toString(), ";charset=", "; charset="); - CACHE.put(alt,type); - TYPES.put(alt,type.asBuffer()); + CACHE.put(alt, type); + TYPES.put(alt, type.asBuffer()); } - + if (type.isCharsetAssumed()) - __assumedEncodings.put(type.asString(),type.getCharsetString()); + __assumedEncodings.put(type.asString(), type.getCharsetString()); } String resourceName = "mime.properties"; @@ -219,25 +203,24 @@ public class MimeTypes Properties props = new Properties(); props.load(reader); props.stringPropertyNames().stream() - .filter(x->x!=null) - .forEach(x-> - __dftMimeMap.put(StringUtil.asciiToLowerCase(x), normalizeMimeType(props.getProperty(x)))); + .filter(x -> x != null) + .forEach(x -> + __dftMimeMap.put(StringUtil.asciiToLowerCase(x), normalizeMimeType(props.getProperty(x)))); if (__dftMimeMap.isEmpty()) { LOG.warn("Empty mime types at {}", resourceName); } - else if (__dftMimeMap.size()t!=null) - .forEach(t-> - { - String charset = props.getProperty(t); - if (charset.startsWith("-")) - __assumedEncodings.put(t, charset.substring(1)); - else - __inferredEncodings.put(t, props.getProperty(t)); - }); + .filter(t -> t != null) + .forEach(t -> + { + String charset = props.getProperty(t); + if (charset.startsWith("-")) + __assumedEncodings.put(t, charset.substring(1)); + else + __inferredEncodings.put(t, props.getProperty(t)); + }); if (__inferredEncodings.isEmpty()) { LOG.warn("Empty encodings at {}", resourceName); } - else if ((__inferredEncodings.size()+__assumedEncodings.size()) _mimeMap = new HashMap(); - /* ------------------------------------------------------------ */ - private final Map _mimeMap=new HashMap(); - - /* ------------------------------------------------------------ */ - /** Constructor. + /** + * Constructor. */ public MimeTypes() { } - /* ------------------------------------------------------------ */ - public synchronized Map getMimeMap() + public synchronized Map getMimeMap() { return _mimeMap; } - /* ------------------------------------------------------------ */ /** * @param mimeMap A Map of file extension to mime-type. */ - public void setMimeMap(Map mimeMap) + public void setMimeMap(Map mimeMap) { _mimeMap.clear(); - if (mimeMap!=null) + if (mimeMap != null) { for (Entry ext : mimeMap.entrySet()) - _mimeMap.put(StringUtil.asciiToLowerCase(ext.getKey()),normalizeMimeType(ext.getValue())); + { + _mimeMap.put(StringUtil.asciiToLowerCase(ext.getKey()), normalizeMimeType(ext.getValue())); + } } } - /* ------------------------------------------------------------ */ - /** Get the MIME type by filename extension. + /** + * Get the MIME type by filename extension. * Lookup only the static default mime map. + * * @param filename A file name * @return MIME type matching the longest dot extension of the * file name. */ public static String getDefaultMimeByExtension(String filename) { - String type=null; + String type = null; - if (filename!=null) + if (filename != null) { - int i=-1; - while(type==null) + int i = -1; + while (type == null) { - i=filename.indexOf(".",i+1); + i = filename.indexOf(".", i + 1); - if (i<0 || i>=filename.length()) + if (i < 0 || i >= filename.length()) break; - String ext=StringUtil.asciiToLowerCase(filename.substring(i+1)); - if (type==null) - type=__dftMimeMap.get(ext); + String ext = StringUtil.asciiToLowerCase(filename.substring(i + 1)); + if (type == null) + type = __dftMimeMap.get(ext); } } - if (type==null) + if (type == null) { - type=__dftMimeMap.get("*"); + type = __dftMimeMap.get("*"); } return type; } - /* ------------------------------------------------------------ */ - /** Get the MIME type by filename extension. + /** + * Get the MIME type by filename extension. * Lookup the content and static default mime maps. + * * @param filename A file name * @return MIME type matching the longest dot extension of the * file name. */ public String getMimeByExtension(String filename) { - String type=null; + String type = null; - if (filename!=null) + if (filename != null) { - int i=-1; - while(type==null) + int i = -1; + while (type == null) { - i=filename.indexOf(".",i+1); + i = filename.indexOf(".", i + 1); - if (i<0 || i>=filename.length()) + if (i < 0 || i >= filename.length()) break; - String ext=StringUtil.asciiToLowerCase(filename.substring(i+1)); - if (_mimeMap!=null) - type=_mimeMap.get(ext); - if (type==null) - type=__dftMimeMap.get(ext); + String ext = StringUtil.asciiToLowerCase(filename.substring(i + 1)); + if (_mimeMap != null) + type = _mimeMap.get(ext); + if (type == null) + type = __dftMimeMap.get(ext); } } - if (type==null) + if (type == null) { - if (_mimeMap!=null) - type=_mimeMap.get("*"); - if (type==null) - type=__dftMimeMap.get("*"); + if (_mimeMap != null) + type = _mimeMap.get("*"); + if (type == null) + type = __dftMimeMap.get("*"); } return type; } - /* ------------------------------------------------------------ */ - /** Set a mime mapping + /** + * Set a mime mapping + * * @param extension the extension * @param type the mime type */ - public void addMimeMapping(String extension,String type) + public void addMimeMapping(String extension, String type) { - _mimeMap.put(StringUtil.asciiToLowerCase(extension),normalizeMimeType(type)); + _mimeMap.put(StringUtil.asciiToLowerCase(extension), normalizeMimeType(type)); } - /* ------------------------------------------------------------ */ public static Set getKnownMimeTypes() { return new HashSet<>(__dftMimeMap.values()); } - /* ------------------------------------------------------------ */ private static String normalizeMimeType(String type) { - MimeTypes.Type t =CACHE.get(type); - if (t!=null) + MimeTypes.Type t = CACHE.get(type); + if (t != null) return t.asString(); return StringUtil.asciiToLowerCase(type); } - /* ------------------------------------------------------------ */ public static String getCharsetFromContentType(String value) { - if (value==null) + if (value == null) return null; - int end=value.length(); - int state=0; - int start=0; - boolean quote=false; - int i=0; - for (;i getInferredEncodings() + public static Map getInferredEncodings() { return __inferredEncodings; } - + /** * Access a mutable map of mime type to the charset assumed for that content type. - * An assumed encoding is used by when encoding/decoding a stream, but is not + * An assumed encoding is used by when encoding/decoding a stream, but is not * explicitly set in any metadata (eg Content-Type). + * * @return Map of mime type to charset */ - public static Map getAssumedEncodings() + public static Map getAssumedEncodings() { return __assumedEncodings; } @@ -528,97 +551,136 @@ public class MimeTypes { return __assumedEncodings.get(contentType); } - + public static String getContentTypeWithoutCharset(String value) { - int end=value.length(); - int state=0; - int start=0; - boolean quote=false; - int i=0; - StringBuilder builder=null; - for (;i _headers; protected long _size = 0; protected boolean _temporary = true; - + public MultiPart(String name, String filename) { _name = name; _filename = filename; } - + @Override public String toString() { return String.format("Part{n=%s,fn=%s,ct=%s,s=%d,tmp=%b,file=%s}", _name, _filename, _contentType, _size, _temporary, _file); } - + protected void setContentType(String contentType) { _contentType = contentType; } - + protected void open() throws IOException { // We will either be writing to a file, if it has a filename on the content-disposition @@ -117,38 +117,38 @@ public class MultiPartFormInputStream _out = _bout = new ByteArrayOutputStream2(); } } - + protected void close() throws IOException { _out.close(); } - + protected void write(int b) throws IOException { if (MultiPartFormInputStream.this._config.getMaxFileSize() > 0 && _size + 1 > MultiPartFormInputStream.this._config.getMaxFileSize()) throw new IllegalStateException("Multipart Mime part " + _name + " exceeds max filesize"); - - if (MultiPartFormInputStream.this._config.getFileSizeThreshold() > 0 && _size + 1 > MultiPartFormInputStream.this._config.getFileSizeThreshold() - && _file == null) + + if (MultiPartFormInputStream.this._config.getFileSizeThreshold() > 0 && + _size + 1 > MultiPartFormInputStream.this._config.getFileSizeThreshold() && _file == null) createFile(); - + _out.write(b); _size++; } - + protected void write(byte[] bytes, int offset, int length) throws IOException { if (MultiPartFormInputStream.this._config.getMaxFileSize() > 0 && _size + length > MultiPartFormInputStream.this._config.getMaxFileSize()) throw new IllegalStateException("Multipart Mime part " + _name + " exceeds max filesize"); - - if (MultiPartFormInputStream.this._config.getFileSizeThreshold() > 0 - && _size + length > MultiPartFormInputStream.this._config.getFileSizeThreshold() && _file == null) + + if (MultiPartFormInputStream.this._config.getFileSizeThreshold() > 0 && + _size + length > MultiPartFormInputStream.this._config.getFileSizeThreshold() && _file == null) createFile(); - + _out.write(bytes, offset, length); _size += length; } - + protected void createFile() throws IOException { /* @@ -156,16 +156,16 @@ public class MultiPartFormInputStream */ final boolean USER = true; final boolean WORLD = false; - + _file = File.createTempFile("MultiPart", "", MultiPartFormInputStream.this._tmpDir); _file.setReadable(false, WORLD); // (reset) disable it for everyone first _file.setReadable(true, USER); // enable for user only - + if (_deleteOnExit) _file.deleteOnExit(); FileOutputStream fos = new FileOutputStream(_file); BufferedOutputStream bos = new BufferedOutputStream(fos); - + if (_size > 0 && _out != null) { // already written some bytes, so need to copy them into the file @@ -176,18 +176,18 @@ public class MultiPartFormInputStream _bout = null; _out = bos; } - + protected void setHeaders(MultiMap headers) { _headers = headers; } - + @Override public String getContentType() { return _contentType; } - + @Override public String getHeader(String name) { @@ -195,19 +195,19 @@ public class MultiPartFormInputStream return null; return _headers.getValue(StringUtil.asciiToLowerCase(name), 0); } - + @Override public Collection getHeaderNames() { return _headers.keySet(); } - + @Override public Collection getHeaders(String name) { return _headers.getValues(name); } - + @Override public InputStream getInputStream() throws IOException { @@ -222,42 +222,42 @@ public class MultiPartFormInputStream return new ByteArrayInputStream(_bout.getBuf(), 0, _bout.size()); } } - + @Override public String getSubmittedFileName() { return getContentDispositionFilename(); } - + public byte[] getBytes() { if (_bout != null) return _bout.toByteArray(); return null; } - + @Override public String getName() { return _name; } - + @Override public long getSize() { return _size; } - + @Override public void write(String fileName) throws IOException { if (_file == null) { _temporary = false; - + // part data is only in the ByteArrayOutputStream and never been written to disk _file = new File(_tmpDir, fileName); - + try (BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(_file))) { _bout.writeTo(bos); @@ -272,14 +272,14 @@ public class MultiPartFormInputStream { // the part data is already written to a temporary file, just rename it _temporary = false; - + Path src = _file.toPath(); Path target = src.resolveSibling(fileName); Files.move(src, target, StandardCopyOption.REPLACE_EXISTING); _file = target.toFile(); } } - + /** * Remove the file, whether or not Part.write() was called on it (ie no longer temporary) */ @@ -290,7 +290,7 @@ public class MultiPartFormInputStream if (!_file.delete()) throw new IOException("Could Not Delete File"); } - + /** * Only remove tmp files. * @@ -301,7 +301,7 @@ public class MultiPartFormInputStream if (_temporary) delete(); } - + /** * Get the file * @@ -311,7 +311,7 @@ public class MultiPartFormInputStream { return _file; } - + /** * Get the filename from the content-disposition. * @@ -322,11 +322,11 @@ public class MultiPartFormInputStream return _filename; } } - + /** - * @param in Request input stream - * @param contentType Content-Type header - * @param config MultipartConfigElement + * @param in Request input stream + * @param contentType Content-Type header + * @param config MultipartConfigElement * @param contextTmpDir javax.servlet.context.tempdir */ public MultiPartFormInputStream(InputStream in, String contentType, MultipartConfigElement config, File contextTmpDir) @@ -336,10 +336,10 @@ public class MultiPartFormInputStream _contextTmpDir = contextTmpDir; if (_contextTmpDir == null) _contextTmpDir = new File(System.getProperty("java.io.tmpdir")); - + if (_config == null) _config = new MultipartConfigElement(_contextTmpDir.getAbsolutePath()); - + if (in instanceof ServletInputStream) { if (((ServletInputStream)in).isFinished()) @@ -351,7 +351,7 @@ public class MultiPartFormInputStream } _in = new BufferedInputStream(in); } - + /** * @return whether the list of parsed parts is empty */ @@ -359,17 +359,17 @@ public class MultiPartFormInputStream { if (_parts == null) return true; - + Collection> values = _parts.values(); for (List partList : values) { if (!partList.isEmpty()) return false; } - + return true; } - + /** * Delete any tmp storage for parts, and clear out the parts list. */ @@ -393,11 +393,11 @@ public class MultiPartFormInputStream } } _parts.clear(); - + if (err != null) err.ifExceptionThrowRuntime(); } - + /** * Parse, if necessary, the multipart data and return the list of Parts. * @@ -409,7 +409,7 @@ public class MultiPartFormInputStream if (!_parsed) parse(); throwIfError(); - + Collection> values = _parts.values(); List parts = new ArrayList<>(); for (List o : values) @@ -419,7 +419,7 @@ public class MultiPartFormInputStream } return parts; } - + /** * Get the named Part. * @@ -434,7 +434,7 @@ public class MultiPartFormInputStream throwIfError(); return _parts.getValue(name, 0); } - + /** * Throws an exception if one has been latched. * @@ -455,7 +455,7 @@ public class MultiPartFormInputStream throw new IllegalStateException(_err); } } - + /** * Parse, if necessary, the multipart stream. */ @@ -472,11 +472,11 @@ public class MultiPartFormInputStream { // initialize _parts = new MultiMap<>(); - + // if its not a multipart request, don't parse it if (_contentType == null || !_contentType.startsWith("multipart/form-data")) return; - + // sort out the location to which to write the files if (_config.getLocation() == null) _tmpDir = _contextTmpDir; @@ -490,10 +490,10 @@ public class MultiPartFormInputStream else _tmpDir = new File(_contextTmpDir, _config.getLocation()); } - + if (!_tmpDir.exists()) _tmpDir.mkdirs(); - + String contentTypeBoundary = ""; int bstart = _contentType.indexOf("boundary="); if (bstart >= 0) @@ -502,17 +502,17 @@ public class MultiPartFormInputStream bend = (bend < 0 ? _contentType.length() : bend); contentTypeBoundary = QuotedStringTokenizer.unquote(value(_contentType.substring(bstart, bend)).trim()); } - + parser = new MultiPartParser(handler, contentTypeBoundary); byte[] data = new byte[_bufferSize]; int len; long total = 0; - + while (true) { - + len = _in.read(data); - + if (len > 0) { // keep running total of size of bytes read from input and throw an exception if exceeds MultipartConfigElement._maxRequestSize @@ -522,30 +522,28 @@ public class MultiPartFormInputStream _err = new IllegalStateException("Request exceeds maxRequestSize (" + _config.getMaxRequestSize() + ")"); return; } - + ByteBuffer buffer = BufferUtil.toBuffer(data); buffer.limit(len); if (parser.parse(buffer, false)) break; - + if (buffer.hasRemaining()) throw new IllegalStateException("Buffer did not fully consume"); - } else if (len == -1) { parser.parse(BufferUtil.EMPTY_BUFFER, true); break; } - } - + // check for exceptions if (_err != null) { return; } - + // check we read to the end of the message if (parser.getState() != MultiPartParser.State.END) { @@ -554,12 +552,11 @@ public class MultiPartFormInputStream else _err = new IOException("Incomplete Multipart"); } - + if (LOG.isDebugEnabled()) { LOG.debug("Parsing Complete {} err={}", parser, _err); } - } catch (Throwable e) { @@ -570,20 +567,20 @@ public class MultiPartFormInputStream parser.parse(BufferUtil.EMPTY_BUFFER, true); } } - + class Handler implements MultiPartParser.Handler { private MultiPart _part = null; private String contentDisposition = null; private String contentType = null; private MultiMap headers = new MultiMap<>(); - + @Override public boolean messageComplete() { return true; } - + @Override public void parsedField(String key, String value) { @@ -593,12 +590,12 @@ public class MultiPartFormInputStream contentDisposition = value; else if (key.equalsIgnoreCase("content-type")) contentType = value; - + // Transfer encoding is not longer considers as it is deprecated as per // https://tools.ietf.org/html/rfc7578#section-4.7 - + } - + @Override public boolean headerComplete() { @@ -606,16 +603,16 @@ public class MultiPartFormInputStream { LOG.debug("headerComplete {}", this); } - + try { // Extract content-disposition - boolean form_data = false; + boolean formData = false; if (contentDisposition == null) { throw new IOException("Missing content-disposition"); } - + QuotedStringTokenizer tok = new QuotedStringTokenizer(contentDisposition, ";", false, true); String name = null; String filename = null; @@ -624,17 +621,17 @@ public class MultiPartFormInputStream String t = tok.nextToken().trim(); String tl = StringUtil.asciiToLowerCase(t); if (tl.startsWith("form-data")) - form_data = true; + formData = true; else if (tl.startsWith("name=")) name = value(t); else if (tl.startsWith("filename=")) filename = filenameValue(t); } - + // Check disposition - if (!form_data) + if (!formData) throw new IOException("Part not form-data"); - + // It is valid for reset and submit buttons to have an empty name. // If no name is supplied, the browser skips sending the info for that field. // However, if you supply the empty string as the name, the browser sends the @@ -642,14 +639,13 @@ public class MultiPartFormInputStream // have not yet seen a name field. if (name == null) throw new IOException("No name in part"); - - + // create the new part _part = new MultiPart(name, filename); _part.setHeaders(headers); _part.setContentType(contentType); _parts.add(name, _part); - + try { _part.open(); @@ -665,16 +661,16 @@ public class MultiPartFormInputStream _err = e; return true; } - + return false; } - + @Override public boolean content(ByteBuffer buffer, boolean last) { if (_part == null) return false; - + if (BufferUtil.hasContent(buffer)) { try @@ -687,7 +683,7 @@ public class MultiPartFormInputStream return true; } } - + if (last) { try @@ -700,16 +696,16 @@ public class MultiPartFormInputStream return true; } } - + return false; } - + @Override public void startPart() { reset(); } - + @Override public void earlyEOF() { @@ -726,7 +722,7 @@ public class MultiPartFormInputStream LOG.warn("part could not be closed", e); } } - + public void reset() { _part = null; @@ -735,41 +731,39 @@ public class MultiPartFormInputStream headers = new MultiMap<>(); } } - + public void setDeleteOnExit(boolean deleteOnExit) { _deleteOnExit = deleteOnExit; } - + public void setWriteFilesWithFilenames(boolean writeFilesWithFilenames) { _writeFilesWithFilenames = writeFilesWithFilenames; } - + public boolean isWriteFilesWithFilenames() { return _writeFilesWithFilenames; } - + public boolean isDeleteOnExit() { return _deleteOnExit; } - - /* ------------------------------------------------------------ */ + private static String value(String nameEqualsValue) { int idx = nameEqualsValue.indexOf('='); String value = nameEqualsValue.substring(idx + 1).trim(); return QuotedStringTokenizer.unquoteOnly(value); } - - /* ------------------------------------------------------------ */ + private static String filenameValue(String nameEqualsValue) { int idx = nameEqualsValue.indexOf('='); String value = nameEqualsValue.substring(idx + 1).trim(); - + if (value.matches(".??[a-z,A-Z]\\:\\\\[^\\\\].*")) { // incorrectly escaped IE filenames that have the whole path @@ -780,7 +774,7 @@ public class MultiPartFormInputStream char last = value.charAt(value.length() - 1); if (last == '"' || last == '\'') value = value.substring(0, value.length() - 1); - + return value; } else @@ -790,7 +784,7 @@ public class MultiPartFormInputStream // backslashes return QuotedStringTokenizer.unquoteOnly(value, true); } - + /** * @return the size of buffer used to read data from the input stream */ @@ -798,7 +792,7 @@ public class MultiPartFormInputStream { return _bufferSize; } - + /** * @param bufferSize the size of buffer used to read data from the input stream */ diff --git a/jetty-http/src/main/java/org/eclipse/jetty/http/MultiPartParser.java b/jetty-http/src/main/java/org/eclipse/jetty/http/MultiPartParser.java index 7e4b12da9d8..286ee58be62 100644 --- a/jetty-http/src/main/java/org/eclipse/jetty/http/MultiPartParser.java +++ b/jetty-http/src/main/java/org/eclipse/jetty/http/MultiPartParser.java @@ -29,8 +29,6 @@ import org.eclipse.jetty.util.Utf8StringBuilder; import org.eclipse.jetty.util.log.Log; import org.eclipse.jetty.util.log.Logger; -/* ------------------------------------------------------------ */ - /** * A parser for MultiPart content type. * @@ -40,7 +38,7 @@ import org.eclipse.jetty.util.log.Logger; public class MultiPartParser { public static final Logger LOG = Log.getLogger(MultiPartParser.class); - + // States public enum FieldState { @@ -50,7 +48,7 @@ public class MultiPartParser VALUE, IN_VALUE } - + // States public enum State { @@ -64,89 +62,83 @@ public class MultiPartParser EPILOGUE, END } - - private final static EnumSet __delimiterStates = EnumSet.of(State.DELIMITER, State.DELIMITER_CLOSE, State.DELIMITER_PADDING); - private final static int MAX_HEADER_LINE_LENGTH = 998; - - private final boolean DEBUG = LOG.isDebugEnabled(); + + private static final EnumSet __delimiterStates = EnumSet.of(State.DELIMITER, State.DELIMITER_CLOSE, State.DELIMITER_PADDING); + private static final int MAX_HEADER_LINE_LENGTH = 998; + + private final boolean debugEnabled = LOG.isDebugEnabled(); private final Handler _handler; private final SearchPattern _delimiterSearch; - + private String _fieldName; private String _fieldValue; - + private State _state = State.PREAMBLE; private FieldState _fieldState = FieldState.FIELD; private int _partialBoundary = 2; // No CRLF if no preamble private boolean _cr; private ByteBuffer _patternBuffer; - + private final Utf8StringBuilder _string = new Utf8StringBuilder(); private int _length; - + private int _totalHeaderLineLength = -1; - - /* ------------------------------------------------------------------------------- */ + public MultiPartParser(Handler handler, String boundary) { _handler = handler; - + String delimiter = "\r\n--" + boundary; _patternBuffer = ByteBuffer.wrap(delimiter.getBytes(StandardCharsets.US_ASCII)); _delimiterSearch = SearchPattern.compile(_patternBuffer.array()); } - + public void reset() { _state = State.PREAMBLE; _fieldState = FieldState.FIELD; _partialBoundary = 2; // No CRLF if no preamble } - - /* ------------------------------------------------------------------------------- */ + public Handler getHandler() { return _handler; } - - /* ------------------------------------------------------------------------------- */ + public State getState() { return _state; } - - /* ------------------------------------------------------------------------------- */ + public boolean isState(State state) { return _state == state; } - - /* ------------------------------------------------------------------------------- */ + private static boolean hasNextByte(ByteBuffer buffer) { return BufferUtil.hasContent(buffer); } - - /* ------------------------------------------------------------------------------- */ + private HttpTokens.Token next(ByteBuffer buffer) { byte ch = buffer.get(); HttpTokens.Token t = HttpTokens.TOKENS[0xff & ch]; - - switch(t.getType()) + + switch (t.getType()) { case CNTL: - throw new IllegalCharacterException(_state,t,buffer); + throw new IllegalCharacterException(_state, t, buffer); case LF: - _cr=false; + _cr = false; break; case CR: if (_cr) throw new BadMessageException("Bad EOL"); - _cr=true; + _cr = true; return null; case ALPHA: @@ -160,23 +152,21 @@ public class MultiPartParser if (_cr) throw new BadMessageException("Bad EOL"); break; - + default: break; } return t; - } - - /* ------------------------------------------------------------------------------- */ + } + private void setString(String s) { _string.reset(); _string.append(s); _length = s.length(); } - - /* ------------------------------------------------------------------------------- */ + /* * Mime Field strings are treated as UTF-8 as per https://tools.ietf.org/html/rfc7578#section-5.1 */ @@ -190,14 +180,12 @@ public class MultiPartParser _length = -1; return s; } - - /* ------------------------------------------------------------------------------- */ - + /** * Parse until next Event. * * @param buffer the buffer to parse - * @param last whether this buffer contains last bit of content + * @param last whether this buffer contains last bit of content * @return True if an {@link RequestHandler} method was called and it returned true; */ public boolean parse(ByteBuffer buffer, boolean last) @@ -210,61 +198,59 @@ public class MultiPartParser case PREAMBLE: parsePreamble(buffer); continue; - + case DELIMITER: case DELIMITER_PADDING: case DELIMITER_CLOSE: parseDelimiter(buffer); continue; - + case BODY_PART: handle = parseMimePartHeaders(buffer); break; - + case FIRST_OCTETS: case OCTETS: handle = parseOctetContent(buffer); break; - + case EPILOGUE: BufferUtil.clear(buffer); break; - + case END: handle = true; break; - + default: throw new IllegalStateException(); - } } - + if (last && BufferUtil.isEmpty(buffer)) { if (_state == State.EPILOGUE) { _state = State.END; - + if (LOG.isDebugEnabled()) LOG.debug("messageComplete {}", this); - + return _handler.messageComplete(); } else { if (LOG.isDebugEnabled()) LOG.debug("earlyEOF {}", this); - + _handler.earlyEOF(); return true; } } - + return handle; } - - /* ------------------------------------------------------------------------------- */ + private void parsePreamble(ByteBuffer buffer) { if (LOG.isDebugEnabled()) @@ -282,15 +268,15 @@ public class MultiPartParser setState(State.DELIMITER); return; } - + _partialBoundary = partial; BufferUtil.clear(buffer); return; } - + _partialBoundary = 0; } - + int delimiter = _delimiterSearch.match(buffer.array(), buffer.arrayOffset() + buffer.position(), buffer.remaining()); if (delimiter >= 0) { @@ -298,12 +284,11 @@ public class MultiPartParser setState(State.DELIMITER); return; } - + _partialBoundary = _delimiterSearch.endsWith(buffer.array(), buffer.arrayOffset() + buffer.position(), buffer.remaining()); BufferUtil.clear(buffer); } - - /* ------------------------------------------------------------------------------- */ + private void parseDelimiter(ByteBuffer buffer) { if (LOG.isDebugEnabled()) @@ -314,18 +299,18 @@ public class MultiPartParser HttpTokens.Token t = next(buffer); if (t == null) return; - - if (t.getType()==HttpTokens.Type.LF) + + if (t.getType() == HttpTokens.Type.LF) { setState(State.BODY_PART); - + if (LOG.isDebugEnabled()) LOG.debug("startPart {}", this); - + _handler.startPart(); return; } - + switch (_state) { case DELIMITER: @@ -334,7 +319,7 @@ public class MultiPartParser else setState(State.DELIMITER_PADDING); continue; - + case DELIMITER_CLOSE: if (t.getChar() == '-') { @@ -343,14 +328,13 @@ public class MultiPartParser } setState(State.DELIMITER_PADDING); continue; - + case DELIMITER_PADDING: default: } } } - - /* ------------------------------------------------------------------------------- */ + /* * Parse the message headers and return true if the handler has signaled for a return */ @@ -366,13 +350,13 @@ public class MultiPartParser HttpTokens.Token t = next(buffer); if (t == null) break; - + if (t.getType() != HttpTokens.Type.LF) _totalHeaderLineLength++; - + if (_totalHeaderLineLength > MAX_HEADER_LINE_LENGTH) throw new IllegalStateException("Header Line Exceeded Max Length"); - + switch (_fieldState) { case FIELD: @@ -382,10 +366,10 @@ public class MultiPartParser case HTAB: { // Folded field value! - + if (_fieldName == null) throw new IllegalStateException("First field folded"); - + if (_fieldValue == null) { _string.reset(); @@ -401,15 +385,15 @@ public class MultiPartParser setState(FieldState.VALUE); break; } - + case LF: handleField(); setState(State.FIRST_OCTETS); _partialBoundary = 2; // CRLF is option for empty parts - + if (LOG.isDebugEnabled()) LOG.debug("headerComplete {}", this); - + if (_handler.headerComplete()) return true; break; @@ -419,39 +403,39 @@ public class MultiPartParser case TCHAR: // process previous header handleField(); - + // New header setState(FieldState.IN_NAME); _string.reset(); _string.append(t.getChar()); _length = 1; - + break; default: - throw new IllegalCharacterException(_state,t,buffer); + throw new IllegalCharacterException(_state, t, buffer); } break; - + case IN_NAME: - switch(t.getType()) + switch (t.getType()) { case COLON: _fieldName = takeString(); _length = -1; setState(FieldState.VALUE); break; - + case SPACE: // Ignore trailing whitespaces setState(FieldState.AFTER_NAME); break; - + case LF: { if (LOG.isDebugEnabled()) LOG.debug("Line Feed in Name {}", this); - + handleField(); setState(FieldState.FIELD); break; @@ -463,47 +447,47 @@ public class MultiPartParser _string.append(t.getChar()); _length = _string.length(); break; - + default: - throw new IllegalCharacterException(_state,t,buffer); + throw new IllegalCharacterException(_state, t, buffer); } break; - + case AFTER_NAME: - switch(t.getType()) + switch (t.getType()) { case COLON: _fieldName = takeString(); _length = -1; setState(FieldState.VALUE); break; - + case LF: _fieldName = takeString(); _string.reset(); _fieldValue = ""; _length = -1; break; - + case SPACE: break; - + default: throw new IllegalCharacterException(_state, t, buffer); } break; - + case VALUE: - switch(t.getType()) + switch (t.getType()) { case LF: _string.reset(); _fieldValue = ""; _length = -1; - + setState(FieldState.FIELD); break; - + case SPACE: case HTAB: break; @@ -520,18 +504,18 @@ public class MultiPartParser break; default: - throw new IllegalCharacterException(_state,t,buffer); + throw new IllegalCharacterException(_state, t, buffer); } break; - + case IN_VALUE: - switch(t.getType()) + switch (t.getType()) { case SPACE: case HTAB: _string.append(' '); break; - + case LF: if (_length > 0) { @@ -541,7 +525,7 @@ public class MultiPartParser } setState(FieldState.FIELD); break; - + case ALPHA: case DIGIT: case TCHAR: @@ -549,40 +533,36 @@ public class MultiPartParser case COLON: case OTEXT: _string.append(t.getByte()); - _length=_string.length(); + _length = _string.length(); break; default: - throw new IllegalCharacterException(_state,t,buffer); + throw new IllegalCharacterException(_state, t, buffer); } break; - + default: throw new IllegalStateException(_state.toString()); - } } return false; } - - /* ------------------------------------------------------------------------------- */ + private void handleField() { if (LOG.isDebugEnabled()) LOG.debug("parsedField: _fieldName={} _fieldValue={} {}", _fieldName, _fieldValue, this); - + if (_fieldName != null && _fieldValue != null) _handler.parsedField(_fieldName, _fieldValue); _fieldName = _fieldValue = null; } - - /* ------------------------------------------------------------------------------- */ - + protected boolean parseOctetContent(ByteBuffer buffer) { if (LOG.isDebugEnabled()) LOG.debug("parseOctetContent({})", BufferUtil.toDetailString(buffer)); - + // Starts With if (_partialBoundary > 0) { @@ -594,13 +574,13 @@ public class MultiPartParser buffer.position(buffer.position() + _delimiterSearch.getLength() - _partialBoundary); setState(State.DELIMITER); _partialBoundary = 0; - + if (LOG.isDebugEnabled()) LOG.debug("Content={}, Last={} {}", BufferUtil.toDetailString(BufferUtil.EMPTY_BUFFER), true, this); - + return _handler.content(BufferUtil.EMPTY_BUFFER, true); } - + _partialBoundary = partial; BufferUtil.clear(buffer); return false; @@ -616,81 +596,75 @@ public class MultiPartParser } content.limit(_partialBoundary); _partialBoundary = 0; - + if (LOG.isDebugEnabled()) LOG.debug("Content={}, Last={} {}", BufferUtil.toDetailString(content), false, this); - + if (_handler.content(content, false)) return true; } } - + // Contains int delimiter = _delimiterSearch.match(buffer.array(), buffer.arrayOffset() + buffer.position(), buffer.remaining()); if (delimiter >= 0) { ByteBuffer content = buffer.slice(); content.limit(delimiter - buffer.arrayOffset() - buffer.position()); - + buffer.position(delimiter - buffer.arrayOffset() + _delimiterSearch.getLength()); setState(State.DELIMITER); - + if (LOG.isDebugEnabled()) LOG.debug("Content={}, Last={} {}", BufferUtil.toDetailString(content), true, this); - + return _handler.content(content, true); } - + // Ends With _partialBoundary = _delimiterSearch.endsWith(buffer.array(), buffer.arrayOffset() + buffer.position(), buffer.remaining()); if (_partialBoundary > 0) { ByteBuffer content = buffer.slice(); content.limit(content.limit() - _partialBoundary); - + if (LOG.isDebugEnabled()) LOG.debug("Content={}, Last={} {}", BufferUtil.toDetailString(content), false, this); - + BufferUtil.clear(buffer); return _handler.content(content, false); } - + // There is normal content with no delimiter ByteBuffer content = buffer.slice(); - + if (LOG.isDebugEnabled()) LOG.debug("Content={}, Last={} {}", BufferUtil.toDetailString(content), false, this); - + BufferUtil.clear(buffer); return _handler.content(content, false); } - - /* ------------------------------------------------------------------------------- */ + private void setState(State state) { - if (DEBUG) + if (debugEnabled) LOG.debug("{} --> {}", _state, state); _state = state; } - - /* ------------------------------------------------------------------------------- */ + private void setState(FieldState state) { - if (DEBUG) + if (debugEnabled) LOG.debug("{}:{} --> {}", _state, _fieldState, state); _fieldState = state; } - - /* ------------------------------------------------------------------------------- */ + @Override public String toString() { return String.format("%s{s=%s}", getClass().getSimpleName(), _state); } - - /* ------------------------------------------------------------ */ - /* ------------------------------------------------------------ */ - /* ------------------------------------------------------------ */ + /* * Event Handler interface These methods return true if the caller should process the events so far received (eg return from parseNext and call * HttpChannel.handle). If multiple callbacks are called in sequence (eg headerComplete then messageComplete) from the same point in the parsing then it is @@ -701,42 +675,41 @@ public class MultiPartParser default void startPart() { } - + @SuppressWarnings("unused") default void parsedField(String name, String value) { } - + default boolean headerComplete() { return false; } - + @SuppressWarnings("unused") default boolean content(ByteBuffer item, boolean last) { return false; } - + default boolean messageComplete() { return false; } - + default void earlyEOF() { } } - /* ------------------------------------------------------------------------------- */ @SuppressWarnings("serial") private static class IllegalCharacterException extends BadMessageException { - private IllegalCharacterException(State state,HttpTokens.Token token,ByteBuffer buffer) + private IllegalCharacterException(State state, HttpTokens.Token token, ByteBuffer buffer) { - super(400,String.format("Illegal character %s",token)); + super(400, String.format("Illegal character %s", token)); if (LOG.isDebugEnabled()) - LOG.debug(String.format("Illegal character %s in state=%s for buffer %s",token,state,BufferUtil.toDetailString(buffer))); + LOG.debug(String.format("Illegal character %s in state=%s for buffer %s", token, state, BufferUtil.toDetailString(buffer))); } } } diff --git a/jetty-http/src/main/java/org/eclipse/jetty/http/PreEncodedHttpField.java b/jetty-http/src/main/java/org/eclipse/jetty/http/PreEncodedHttpField.java index 7b5c0c47d88..35ec9a7cd40 100644 --- a/jetty-http/src/main/java/org/eclipse/jetty/http/PreEncodedHttpField.java +++ b/jetty-http/src/main/java/org/eclipse/jetty/http/PreEncodedHttpField.java @@ -16,7 +16,6 @@ // ======================================================================== // - package org.eclipse.jetty.http; import java.nio.ByteBuffer; @@ -28,23 +27,22 @@ import java.util.ServiceLoader; import org.eclipse.jetty.util.log.Log; import org.eclipse.jetty.util.log.Logger; - -/* ------------------------------------------------------------ */ -/** Pre encoded HttpField. - *

    A HttpField that will be cached and used many times can be created as +/** + * Pre encoded HttpField. + *

    A HttpField that will be cached and used many times can be created as * a {@link PreEncodedHttpField}, which will use the {@link HttpFieldPreEncoder} - * instances discovered by the {@link ServiceLoader} to pre-encode the header - * for each version of HTTP in use. This will save garbage + * instances discovered by the {@link ServiceLoader} to pre-encode the header + * for each version of HTTP in use. This will save garbage * and CPU each time the field is encoded into a response. *

    */ public class PreEncodedHttpField extends HttpField { - private final static Logger LOG = Log.getLogger(PreEncodedHttpField.class); - private final static HttpFieldPreEncoder[] __encoders; - + private static final Logger LOG = Log.getLogger(PreEncodedHttpField.class); + private static final HttpFieldPreEncoder[] __encoders; + static - { + { List encoders = new ArrayList<>(); Iterator iter = ServiceLoader.load(HttpFieldPreEncoder.class).iterator(); while (iter.hasNext()) @@ -52,32 +50,32 @@ public class PreEncodedHttpField extends HttpField try { HttpFieldPreEncoder encoder = iter.next(); - if (index(encoder.getHttpVersion())>=0) + if (index(encoder.getHttpVersion()) >= 0) encoders.add(encoder); } - catch(Error|RuntimeException e) + catch (Error | RuntimeException e) { LOG.debug(e); } } - LOG.debug("HttpField encoders loaded: {}",encoders); - int size=encoders.size(); - - __encoders = new HttpFieldPreEncoder[size==0?1:size]; - for (HttpFieldPreEncoder e:encoders) + LOG.debug("HttpField encoders loaded: {}", encoders); + int size = encoders.size(); + + __encoders = new HttpFieldPreEncoder[size == 0 ? 1 : size]; + for (HttpFieldPreEncoder e : encoders) { int i = index(e.getHttpVersion()); - if (__encoders[i]==null) + if (__encoders[i] == null) __encoders[i] = e; else - LOG.warn("multiple PreEncoders for "+e.getHttpVersion()); + LOG.warn("multiple PreEncoders for " + e.getHttpVersion()); } // Always support HTTP1 - if (__encoders[0]==null) - __encoders[0] = new Http1FieldPreEncoder(); + if (__encoders[0] == null) + __encoders[0] = new Http1FieldPreEncoder(); } - + private static int index(HttpVersion version) { switch (version) @@ -93,26 +91,28 @@ public class PreEncodedHttpField extends HttpField return -1; } } - - private final byte[][] _encodedField=new byte[__encoders.length][]; - public PreEncodedHttpField(HttpHeader header,String name,String value) + private final byte[][] _encodedField = new byte[__encoders.length][]; + + public PreEncodedHttpField(HttpHeader header, String name, String value) { - super(header,name, value); - for (int i=0;i<__encoders.length;i++) - _encodedField[i]=__encoders[i].getEncodedField(header,name,value); + super(header, name, value); + for (int i = 0; i < __encoders.length; i++) + { + _encodedField[i] = __encoders[i].getEncodedField(header, name, value); + } } - - public PreEncodedHttpField(HttpHeader header,String value) + + public PreEncodedHttpField(HttpHeader header, String value) { - this(header,header.asString(),value); + this(header, header.asString(), value); } - - public PreEncodedHttpField(String name,String value) + + public PreEncodedHttpField(String name, String value) { - this(null,name,value); + this(null, name, value); } - + public void putTo(ByteBuffer bufferInFillMode, HttpVersion version) { bufferInFillMode.put(_encodedField[index(version)]); diff --git a/jetty-http/src/main/java/org/eclipse/jetty/http/PrecompressedHttpContent.java b/jetty-http/src/main/java/org/eclipse/jetty/http/PrecompressedHttpContent.java index 3cdce953736..e7fceabea63 100644 --- a/jetty-http/src/main/java/org/eclipse/jetty/http/PrecompressedHttpContent.java +++ b/jetty-http/src/main/java/org/eclipse/jetty/http/PrecompressedHttpContent.java @@ -27,7 +27,6 @@ import java.util.Map; import org.eclipse.jetty.http.MimeTypes.Type; import org.eclipse.jetty.util.resource.Resource; -/* ------------------------------------------------------------ */ public class PrecompressedHttpContent implements HttpContent { private final HttpContent _content; @@ -66,7 +65,7 @@ public class PrecompressedHttpContent implements HttpContent @Override public HttpField getETag() { - return new HttpField(HttpHeader.ETAG,getETagValue()); + return new HttpField(HttpHeader.ETAG, getETagValue()); } @Override @@ -168,10 +167,10 @@ public class PrecompressedHttpContent implements HttpContent @Override public String toString() { - return String.format("PrecompressedHttpContent@%x{e=%s,r=%s|%s,lm=%s|%s,ct=%s}",hashCode(),_format._encoding, - _content.getResource(),_precompressedContent.getResource(), - _content.getResource().lastModified(),_precompressedContent.getResource().lastModified(), - getContentType()); + return String.format("PrecompressedHttpContent@%x{e=%s,r=%s|%s,lm=%s|%s,ct=%s}", hashCode(), _format._encoding, + _content.getResource(), _precompressedContent.getResource(), + _content.getResource().lastModified(), _precompressedContent.getResource().lastModified(), + getContentType()); } @Override diff --git a/jetty-http/src/main/java/org/eclipse/jetty/http/QuotedCSV.java b/jetty-http/src/main/java/org/eclipse/jetty/http/QuotedCSV.java index 538bfc51c8f..d767e006fed 100644 --- a/jetty-http/src/main/java/org/eclipse/jetty/http/QuotedCSV.java +++ b/jetty-http/src/main/java/org/eclipse/jetty/http/QuotedCSV.java @@ -25,11 +25,11 @@ import java.util.List; import org.eclipse.jetty.util.QuotedStringTokenizer; -/* ------------------------------------------------------------ */ /** * Implements a quoted comma separated list of values * in accordance with RFC7230. * OWS is removed and quoted characters ignored for parsing. + * * @see "https://tools.ietf.org/html/rfc7230#section-3.2.6" * @see "https://tools.ietf.org/html/rfc7230#section-7" */ @@ -42,6 +42,7 @@ public class QuotedCSV extends QuotedCSVParser implements Iterable /** * Join a list into Quoted CSV string + * * @param values A list of values * @return A Quoted Comma Separated Value list */ @@ -61,12 +62,13 @@ public class QuotedCSV extends QuotedCSVParser implements Iterable return values.get(0); StringBuilder ret = new StringBuilder(); - join(ret,values); + join(ret, values); return ret.toString(); } /** * Join a list into Quoted CSV string + * * @param values A list of values * @return A Quoted Comma Separated Value list */ @@ -90,6 +92,7 @@ public class QuotedCSV extends QuotedCSVParser implements Iterable /** * Join a list into Quoted CSV StringBuilder + * * @param builder A builder to join the list into * @param values A list of values */ @@ -114,14 +117,16 @@ public class QuotedCSV extends QuotedCSVParser implements Iterable public QuotedCSV(String... values) { - this(true,values); + this(true, values); } - - public QuotedCSV(boolean keepQuotes,String... values) + + public QuotedCSV(boolean keepQuotes, String... values) { super(keepQuotes); - for (String v:values) + for (String v : values) + { addValue(v); + } } @Override @@ -144,7 +149,7 @@ public class QuotedCSV extends QuotedCSVParser implements Iterable { return _values; } - + @Override public Iterator iterator() { @@ -156,7 +161,9 @@ public class QuotedCSV extends QuotedCSVParser implements Iterable { List list = new ArrayList<>(); for (String s : this) + { list.add(s); + } return list.toString(); } } diff --git a/jetty-http/src/main/java/org/eclipse/jetty/http/QuotedCSVParser.java b/jetty-http/src/main/java/org/eclipse/jetty/http/QuotedCSVParser.java index 622c3345e77..3cdf5e5af7c 100644 --- a/jetty-http/src/main/java/org/eclipse/jetty/http/QuotedCSVParser.java +++ b/jetty-http/src/main/java/org/eclipse/jetty/http/QuotedCSVParser.java @@ -18,74 +18,79 @@ package org.eclipse.jetty.http; - /** * Implements a quoted comma separated list parser * in accordance with RFC7230. * OWS is removed and quoted characters ignored for parsing. + * * @see "https://tools.ietf.org/html/rfc7230#section-3.2.6" * @see "https://tools.ietf.org/html/rfc7230#section-7" */ public abstract class QuotedCSVParser { - private enum State { VALUE, PARAM_NAME, PARAM_VALUE} + private enum State + { + VALUE, PARAM_NAME, PARAM_VALUE + } protected final boolean _keepQuotes; public QuotedCSVParser(boolean keepQuotes) { - _keepQuotes=keepQuotes; + _keepQuotes = keepQuotes; } public static String unquote(String s) { // handle trivial cases - int l=s.length(); - if (s==null || l==0) + int l = s.length(); + if (s == null || l == 0) return s; // Look for any quotes - int i=0; - for (;ilast_length) // not leading OWS + if (buffer.length() > lastLength) // not leading OWS buffer.append(c); continue; case '"': - quoted=true; + quoted = true; if (_keepQuotes) { - if (state==State.PARAM_VALUE && param_value<0) - param_value=nws_length; + if (state == State.PARAM_VALUE && paramValue < 0) + paramValue = nwsLength; buffer.append(c); } - else if (state==State.PARAM_VALUE && param_value<0) - param_value=nws_length; - nws_length=buffer.length(); + else if (state == State.PARAM_VALUE && paramValue < 0) + paramValue = nwsLength; + nwsLength = buffer.length(); continue; case ';': - buffer.setLength(nws_length); // trim following OWS - if (state==State.VALUE) + buffer.setLength(nwsLength); // trim following OWS + if (state == State.VALUE) { parsedValue(buffer); - value_length=buffer.length(); + valueLength = buffer.length(); } else - parsedParam(buffer,value_length,param_name,param_value); - nws_length=buffer.length(); - param_name=param_value=-1; + parsedParam(buffer, valueLength, paramName, paramValue); + nwsLength = buffer.length(); + paramName = paramValue = -1; buffer.append(c); - last_length=++nws_length; - state=State.PARAM_NAME; + lastLength = ++nwsLength; + state = State.PARAM_NAME; continue; case ',': case 0: - if (nws_length>0) + if (nwsLength > 0) { - buffer.setLength(nws_length); // trim following OWS - switch(state) + buffer.setLength(nwsLength); // trim following OWS + switch (state) { case VALUE: parsedValue(buffer); - value_length=buffer.length(); + valueLength = buffer.length(); break; case PARAM_NAME: case PARAM_VALUE: - parsedParam(buffer,value_length,param_name,param_value); + parsedParam(buffer, valueLength, paramName, paramValue); break; } parsedValueAndParams(buffer); } buffer.setLength(0); - last_length=0; - nws_length=0; - value_length=param_name=param_value=-1; - state=State.VALUE; + lastLength = 0; + nwsLength = 0; + valueLength = paramName = paramValue = -1; + state = State.VALUE; continue; case '=': @@ -204,30 +209,30 @@ public abstract class QuotedCSVParser { case VALUE: // It wasn't really a value, it was a param name - value_length=param_name=0; - buffer.setLength(nws_length); // trim following OWS + valueLength = paramName = 0; + buffer.setLength(nwsLength); // trim following OWS String param = buffer.toString(); buffer.setLength(0); parsedValue(buffer); - value_length=buffer.length(); + valueLength = buffer.length(); buffer.append(param); buffer.append(c); - last_length=++nws_length; - state=State.PARAM_VALUE; + lastLength = ++nwsLength; + state = State.PARAM_VALUE; continue; case PARAM_NAME: - buffer.setLength(nws_length); // trim following OWS + buffer.setLength(nwsLength); // trim following OWS buffer.append(c); - last_length=++nws_length; - state=State.PARAM_VALUE; + lastLength = ++nwsLength; + state = State.PARAM_VALUE; continue; case PARAM_VALUE: - if (param_value<0) - param_value=nws_length; + if (paramValue < 0) + paramValue = nwsLength; buffer.append(c); - nws_length=buffer.length(); + nwsLength = buffer.length(); continue; } continue; @@ -239,25 +244,25 @@ public abstract class QuotedCSVParser case VALUE: { buffer.append(c); - nws_length=buffer.length(); + nwsLength = buffer.length(); continue; } case PARAM_NAME: { - if (param_name<0) - param_name=nws_length; + if (paramName < 0) + paramName = nwsLength; buffer.append(c); - nws_length=buffer.length(); + nwsLength = buffer.length(); continue; } case PARAM_VALUE: { - if (param_value<0) - param_value=nws_length; + if (paramValue < 0) + paramValue = nwsLength; buffer.append(c); - nws_length=buffer.length(); + nwsLength = buffer.length(); continue; } } @@ -268,6 +273,7 @@ public abstract class QuotedCSVParser /** * Called when a value and it's parameters has been parsed + * * @param buffer Containing the trimmed value and parameters */ protected void parsedValueAndParams(StringBuffer buffer) @@ -276,6 +282,7 @@ public abstract class QuotedCSVParser /** * Called when a value has been parsed (prior to any parameters) + * * @param buffer Containing the trimmed value, which may be mutated */ protected void parsedValue(StringBuffer buffer) @@ -284,6 +291,7 @@ public abstract class QuotedCSVParser /** * Called when a parameter has been parsed + * * @param buffer Containing the trimmed value and all parameters, which may be mutated * @param valueLength The length of the value * @param paramName The index of the start of the parameter just parsed @@ -292,5 +300,4 @@ public abstract class QuotedCSVParser protected void parsedParam(StringBuffer buffer, int valueLength, int paramName, int paramValue) { } - } diff --git a/jetty-http/src/main/java/org/eclipse/jetty/http/QuotedQualityCSV.java b/jetty-http/src/main/java/org/eclipse/jetty/http/QuotedQualityCSV.java index e8956a4108f..2e4a97058df 100644 --- a/jetty-http/src/main/java/org/eclipse/jetty/http/QuotedQualityCSV.java +++ b/jetty-http/src/main/java/org/eclipse/jetty/http/QuotedQualityCSV.java @@ -27,10 +27,6 @@ import org.eclipse.jetty.util.log.Log; import static java.lang.Integer.MIN_VALUE; -import static java.lang.Integer.MIN_VALUE; - -/* ------------------------------------------------------------ */ - /** * Implements a quoted comma separated list of quality values * in accordance with RFC7230 and RFC7231. @@ -63,8 +59,6 @@ public class QuotedQualityCSV extends QuotedCSV implements Iterable private boolean _sorted = false; private final ToIntFunction _secondaryOrdering; - /* ------------------------------------------------------------ */ - /** * Sorts values with equal quality according to the length of the value String. */ @@ -73,8 +67,6 @@ public class QuotedQualityCSV extends QuotedCSV implements Iterable this((ToIntFunction)null); } - /* ------------------------------------------------------------ */ - /** * Sorts values with equal quality according to given order. * @@ -85,8 +77,10 @@ public class QuotedQualityCSV extends QuotedCSV implements Iterable this((s) -> { for (int i = 0; i < preferredOrder.length; ++i) + { if (preferredOrder[i].equals(s)) return preferredOrder.length - i; + } if ("*".equals(s)) return preferredOrder.length; @@ -95,8 +89,6 @@ public class QuotedQualityCSV extends QuotedCSV implements Iterable }); } - /* ------------------------------------------------------------ */ - /** * Orders values with equal quality with the given function. * @@ -107,7 +99,6 @@ public class QuotedQualityCSV extends QuotedCSV implements Iterable this._secondaryOrdering = secondaryOrdering == null ? s -> 0 : secondaryOrdering; } - /* ------------------------------------------------------------ */ @Override protected void parsedValue(StringBuffer buffer) { @@ -117,7 +108,6 @@ public class QuotedQualityCSV extends QuotedCSV implements Iterable _quality.add(1.0D); } - /* ------------------------------------------------------------ */ @Override protected void parsedParam(StringBuffer buffer, int valueLength, int paramName, int paramValue) { @@ -127,15 +117,15 @@ public class QuotedQualityCSV extends QuotedCSV implements Iterable buffer.setLength(buffer.length() - 1); } else if (paramValue >= 0 && - buffer.charAt(paramName) == 'q' && paramValue > paramName && - buffer.length() >= paramName && buffer.charAt(paramName + 1) == '=') + buffer.charAt(paramName) == 'q' && paramValue > paramName && + buffer.length() >= paramName && buffer.charAt(paramName + 1) == '=') { Double q; try { q = (_keepQuotes && buffer.charAt(paramValue) == '"') - ? Double.valueOf(buffer.substring(paramValue + 1, buffer.length() - 1)) - : Double.valueOf(buffer.substring(paramValue)); + ? Double.valueOf(buffer.substring(paramValue + 1, buffer.length() - 1)) + : Double.valueOf(buffer.substring(paramValue)); } catch (Exception e) { @@ -195,11 +185,11 @@ public class QuotedQualityCSV extends QuotedCSV implements Iterable lastSecondaryOrder = _secondaryOrdering.applyAsInt(v); } - int last_element = _quality.size(); - while (last_element > 0 && _quality.get(--last_element).equals(0.0D)) + int lastElement = _quality.size(); + while (lastElement > 0 && _quality.get(--lastElement).equals(0.0D)) { - _quality.remove(last_element); - _values.remove(last_element); + _quality.remove(lastElement); + _values.remove(lastElement); } } } diff --git a/jetty-http/src/main/java/org/eclipse/jetty/http/ResourceHttpContent.java b/jetty-http/src/main/java/org/eclipse/jetty/http/ResourceHttpContent.java index c52b2f4f5dd..5441a0d7b7a 100644 --- a/jetty-http/src/main/java/org/eclipse/jetty/http/ResourceHttpContent.java +++ b/jetty-http/src/main/java/org/eclipse/jetty/http/ResourceHttpContent.java @@ -29,11 +29,10 @@ import org.eclipse.jetty.http.MimeTypes.Type; import org.eclipse.jetty.util.BufferUtil; import org.eclipse.jetty.util.resource.Resource; - -/* ------------------------------------------------------------ */ -/** HttpContent created from a {@link Resource}. +/** + * HttpContent created from a {@link Resource}. *

    The HttpContent is used to server static content that is not - * cached. So fields and values are only generated as need be an not + * cached. So fields and values are only generated as need be an not * kept for reuse

    */ public class ResourceHttpContent implements HttpContent @@ -44,23 +43,20 @@ public class ResourceHttpContent implements HttpContent Map _precompressedContents; String _etag; - /* ------------------------------------------------------------ */ public ResourceHttpContent(final Resource resource, final String contentType) { - this(resource,contentType,-1,null); + this(resource, contentType, -1, null); } - /* ------------------------------------------------------------ */ public ResourceHttpContent(final Resource resource, final String contentType, int maxBuffer) { - this(resource,contentType,maxBuffer,null); + this(resource, contentType, maxBuffer, null); } - - /* ------------------------------------------------------------ */ + public ResourceHttpContent(final Resource resource, final String contentType, int maxBuffer, Map precompressedContents) { - _resource=resource; - _contentType=contentType; + _resource = resource; + _contentType = contentType; _maxBuffer = maxBuffer; if (precompressedContents == null) { @@ -71,170 +67,149 @@ public class ResourceHttpContent implements HttpContent _precompressedContents = new HashMap<>(precompressedContents.size()); for (Map.Entry entry : precompressedContents.entrySet()) { - _precompressedContents.put(entry.getKey(),new PrecompressedHttpContent(this,entry.getValue(),entry.getKey())); + _precompressedContents.put(entry.getKey(), new PrecompressedHttpContent(this, entry.getValue(), entry.getKey())); } } } - /* ------------------------------------------------------------ */ @Override public String getContentTypeValue() { return _contentType; } - - /* ------------------------------------------------------------ */ + @Override public HttpField getContentType() { - return _contentType==null?null:new HttpField(HttpHeader.CONTENT_TYPE,_contentType); + return _contentType == null ? null : new HttpField(HttpHeader.CONTENT_TYPE, _contentType); } - /* ------------------------------------------------------------ */ @Override public HttpField getContentEncoding() { return null; } - /* ------------------------------------------------------------ */ @Override public String getContentEncodingValue() { return null; } - /* ------------------------------------------------------------ */ @Override public String getCharacterEncoding() { - return _contentType==null?null:MimeTypes.getCharsetFromContentType(_contentType); + return _contentType == null ? null : MimeTypes.getCharsetFromContentType(_contentType); } - /* ------------------------------------------------------------ */ @Override public Type getMimeType() { - return _contentType==null?null:MimeTypes.CACHE.get(MimeTypes.getContentTypeWithoutCharset(_contentType)); + return _contentType == null ? null : MimeTypes.CACHE.get(MimeTypes.getContentTypeWithoutCharset(_contentType)); } - - /* ------------------------------------------------------------ */ + @Override public HttpField getLastModified() { long lm = _resource.lastModified(); - return lm>=0?new HttpField(HttpHeader.LAST_MODIFIED,DateGenerator.formatDate(lm)):null; + return lm >= 0 ? new HttpField(HttpHeader.LAST_MODIFIED, DateGenerator.formatDate(lm)) : null; } - /* ------------------------------------------------------------ */ @Override public String getLastModifiedValue() { long lm = _resource.lastModified(); - return lm>=0?DateGenerator.formatDate(lm):null; + return lm >= 0 ? DateGenerator.formatDate(lm) : null; } - /* ------------------------------------------------------------ */ @Override public ByteBuffer getDirectBuffer() { - if (_resource.length()<=0 || _maxBuffer>0 && _maxBuffer<_resource.length()) + if (_resource.length() <= 0 || _maxBuffer > 0 && _maxBuffer < _resource.length()) return null; try { - return BufferUtil.toBuffer(_resource,true); + return BufferUtil.toBuffer(_resource, true); } - catch(IOException e) + catch (IOException e) { throw new RuntimeException(e); } } - - /* ------------------------------------------------------------ */ + @Override public HttpField getETag() { - return new HttpField(HttpHeader.ETAG,getETagValue()); + return new HttpField(HttpHeader.ETAG, getETagValue()); } - - /* ------------------------------------------------------------ */ + @Override public String getETagValue() { return _resource.getWeakETag(); } - /* ------------------------------------------------------------ */ @Override public ByteBuffer getIndirectBuffer() { - if (_resource.length()<=0 || _maxBuffer>0 && _maxBuffer<_resource.length()) + if (_resource.length() <= 0 || _maxBuffer > 0 && _maxBuffer < _resource.length()) return null; try { - return BufferUtil.toBuffer(_resource,false); + return BufferUtil.toBuffer(_resource, false); } - catch(IOException e) + catch (IOException e) { throw new RuntimeException(e); } } - /* ------------------------------------------------------------ */ @Override public HttpField getContentLength() { - long l=_resource.length(); - return l==-1?null:new HttpField.LongValueHttpField(HttpHeader.CONTENT_LENGTH,l); + long l = _resource.length(); + return l == -1 ? null : new HttpField.LongValueHttpField(HttpHeader.CONTENT_LENGTH, l); } - /* ------------------------------------------------------------ */ @Override public long getContentLengthValue() { return _resource.length(); } - /* ------------------------------------------------------------ */ @Override public InputStream getInputStream() throws IOException { return _resource.getInputStream(); } - - /* ------------------------------------------------------------ */ + @Override public ReadableByteChannel getReadableByteChannel() throws IOException { return _resource.getReadableByteChannel(); } - /* ------------------------------------------------------------ */ @Override public Resource getResource() { return _resource; } - /* ------------------------------------------------------------ */ @Override public void release() { _resource.close(); } - - /* ------------------------------------------------------------ */ + @Override public String toString() { - return String.format("%s@%x{r=%s,ct=%s,c=%b}",this.getClass().getSimpleName(),hashCode(),_resource,_contentType,_precompressedContents!=null); + return String.format("%s@%x{r=%s,ct=%s,c=%b}", this.getClass().getSimpleName(), hashCode(), _resource, _contentType, _precompressedContents != null); } - /* ------------------------------------------------------------ */ @Override public Map getPrecompressedContents() { return _precompressedContents; } - } diff --git a/jetty-http/src/main/java/org/eclipse/jetty/http/Syntax.java b/jetty-http/src/main/java/org/eclipse/jetty/http/Syntax.java index 1c8305ba101..cb0b2a7d97d 100644 --- a/jetty-http/src/main/java/org/eclipse/jetty/http/Syntax.java +++ b/jetty-http/src/main/java/org/eclipse/jetty/http/Syntax.java @@ -28,7 +28,7 @@ import java.util.Objects; */ public final class Syntax { - + /** * Per RFC2616: Section 2.2, a token follows these syntax rules *
    @@ -49,30 +49,30 @@ public final class Syntax
         public static void requireValidRFC2616Token(String value, String msg)
         {
             Objects.requireNonNull(msg, "msg cannot be null");
    -        
    +
             if (value == null)
             {
                 return;
             }
    -        
    +
             int valueLen = value.length();
             if (valueLen == 0)
             {
                 return;
             }
    -        
    +
             for (int i = 0; i < valueLen; i++)
             {
                 char c = value.charAt(i);
    -            
    +
                 // 0x00 - 0x1F are low order control characters
                 // 0x7F is the DEL control character
                 if ((c <= 0x1F) || (c == 0x7F))
                     throw new IllegalArgumentException(msg + ": RFC2616 tokens may not contain control characters");
    -            if (c == '(' || c == ')' || c == '<' || c == '>' || c == '@'
    -                    || c == ',' || c == ';' || c == ':' || c == '\\' || c == '"'
    -                    || c == '/' || c == '[' || c == ']' || c == '?' || c == '='
    -                    || c == '{' || c == '}' || c == ' ')
    +            if (c == '(' || c == ')' || c == '<' || c == '>' || c == '@' ||
    +                c == ',' || c == ';' || c == ':' || c == '\\' || c == '"' ||
    +                c == '/' || c == '[' || c == ']' || c == '?' || c == '=' ||
    +                c == '{' || c == '}' || c == ' ')
                 {
                     throw new IllegalArgumentException(msg + ": RFC2616 tokens may not contain separator character: [" + c + "]");
                 }
    @@ -80,7 +80,7 @@ public final class Syntax
                     throw new IllegalArgumentException(msg + ": RFC2616 tokens characters restricted to US-ASCII: 0x" + Integer.toHexString(c));
             }
         }
    -    
    +
         /**
          * Per RFC6265, Cookie.value follows these syntax rules
          * 
    @@ -100,13 +100,13 @@ public final class Syntax
             {
                 return;
             }
    -        
    +
             int valueLen = value.length();
             if (valueLen == 0)
             {
                 return;
             }
    -        
    +
             int i = 0;
             if (value.charAt(0) == '"')
             {
    @@ -115,7 +115,7 @@ public final class Syntax
                 {
                     throw new IllegalArgumentException("RFC6265 Cookie values must have balanced DQUOTES (if used)");
                 }
    -            
    +
                 // adjust search range to exclude DQUOTES
                 i++;
                 valueLen--;
    @@ -123,15 +123,15 @@ public final class Syntax
             for (; i < valueLen; i++)
             {
                 char c = value.charAt(i);
    -            
    +
                 // 0x00 - 0x1F are low order control characters
                 // 0x7F is the DEL control character
                 if ((c <= 0x1F) || (c == 0x7F))
                     throw new IllegalArgumentException("RFC6265 Cookie values may not contain control characters");
                 if ((c == ' ' /* 0x20 */) ||
    -                    (c == '"' /* 0x2C */) ||
    -                    (c == ';' /* 0x3B */) ||
    -                    (c == '\\' /* 0x5C */))
    +                (c == '"' /* 0x2C */) ||
    +                (c == ';' /* 0x3B */) ||
    +                (c == '\\' /* 0x5C */))
                 {
                     throw new IllegalArgumentException("RFC6265 Cookie values may not contain character: [" + c + "]");
                 }
    diff --git a/jetty-http/src/main/java/org/eclipse/jetty/http/pathmap/MappedResource.java b/jetty-http/src/main/java/org/eclipse/jetty/http/pathmap/MappedResource.java
    index 2c41790006d..2d50bb15175 100644
    --- a/jetty-http/src/main/java/org/eclipse/jetty/http/pathmap/MappedResource.java
    +++ b/jetty-http/src/main/java/org/eclipse/jetty/http/pathmap/MappedResource.java
    @@ -96,6 +96,6 @@ public class MappedResource implements Comparable>
         @Override
         public String toString()
         {
    -        return String.format("MappedResource[pathSpec=%s,resource=%s]",pathSpec,resource);
    +        return String.format("MappedResource[pathSpec=%s,resource=%s]", pathSpec, resource);
         }
     }
    diff --git a/jetty-http/src/main/java/org/eclipse/jetty/http/pathmap/PathMappings.java b/jetty-http/src/main/java/org/eclipse/jetty/http/pathmap/PathMappings.java
    index f93b856748e..4194b8db83f 100644
    --- a/jetty-http/src/main/java/org/eclipse/jetty/http/pathmap/PathMappings.java
    +++ b/jetty-http/src/main/java/org/eclipse/jetty/http/pathmap/PathMappings.java
    @@ -39,7 +39,7 @@ import org.eclipse.jetty.util.log.Logger;
      * Path Mappings of PathSpec to Resource.
      * 

    * Sorted into search order upon entry into the Set - * + * * @param the type of mapping endpoint */ @ManagedObject("Path Mappings") @@ -47,11 +47,11 @@ public class PathMappings implements Iterable>, Dumpable { private static final Logger LOG = Log.getLogger(PathMappings.class); private final Set> _mappings = new TreeSet<>(); - - private Trie> _exactMap=new ArrayTernaryTrie<>(false); - private Trie> _prefixMap=new ArrayTernaryTrie<>(false); - private Trie> _suffixMap=new ArrayTernaryTrie<>(false); - + + private Trie> _exactMap = new ArrayTernaryTrie<>(false); + private Trie> _prefixMap = new ArrayTernaryTrie<>(false); + private Trie> _suffixMap = new ArrayTernaryTrie<>(false); + @Override public String dump() { @@ -61,9 +61,9 @@ public class PathMappings implements Iterable>, Dumpable @Override public void dump(Appendable out, String indent) throws IOException { - Dumpable.dumpObjects(out, indent, toString(), _mappings); + Dumpable.dumpObjects(out, indent, toString(), _mappings); } - + @ManagedAttribute(value = "mappings", readonly = true) public List> getMappings() { @@ -74,31 +74,31 @@ public class PathMappings implements Iterable>, Dumpable { return _mappings.size(); } - + public void reset() { _mappings.clear(); _prefixMap.clear(); _suffixMap.clear(); } - + public void removeIf(Predicate> predicate) { _mappings.removeIf(predicate); } - + /** * Return a list of MappedResource matches for the specified path. - * + * * @param path the path to return matches on * @return the list of mapped resource the path matches on */ public List> getMatches(String path) { boolean isRootPath = "/".equals(path); - + List> ret = new ArrayList<>(); - for (MappedResource mr :_mappings) + for (MappedResource mr : _mappings) { switch (mr.getPathSpec().group) { @@ -121,72 +121,72 @@ public class PathMappings implements Iterable>, Dumpable public MappedResource getMatch(String path) { - PathSpecGroup last_group=null; - + PathSpecGroup lastGroup = null; + // Search all the mappings for (MappedResource mr : _mappings) { - PathSpecGroup group=mr.getPathSpec().getGroup(); - if (group!=last_group) + PathSpecGroup group = mr.getPathSpec().getGroup(); + if (group != lastGroup) { // New group in list, so let's look for an optimization - switch(group) + switch (group) { case EXACT: { - int i= path.length(); - final Trie> exact_map=_exactMap; - while(i>=0) + int i = path.length(); + final Trie> exact_map = _exactMap; + while (i >= 0) { - MappedResource candidate=exact_map.getBest(path,0,i); - if (candidate==null) + MappedResource candidate = exact_map.getBest(path, 0, i); + if (candidate == null) break; if (candidate.getPathSpec().matches(path)) return candidate; - i=candidate.getPathSpec().getPrefix().length()-1; + i = candidate.getPathSpec().getPrefix().length() - 1; } break; } - + case PREFIX_GLOB: { - int i= path.length(); - final Trie> prefix_map=_prefixMap; - while(i>=0) + int i = path.length(); + final Trie> prefix_map = _prefixMap; + while (i >= 0) { - MappedResource candidate=prefix_map.getBest(path,0,i); - if (candidate==null) + MappedResource candidate = prefix_map.getBest(path, 0, i); + if (candidate == null) break; if (candidate.getPathSpec().matches(path)) return candidate; - i=candidate.getPathSpec().getPrefix().length()-1; + i = candidate.getPathSpec().getPrefix().length() - 1; } break; } - + case SUFFIX_GLOB: { - int i=0; - final Trie> suffix_map=_suffixMap; - while ((i=path.indexOf('.',i+1))>0) + int i = 0; + final Trie> suffix_map = _suffixMap; + while ((i = path.indexOf('.', i + 1)) > 0) { - MappedResource candidate=suffix_map.get(path,i+1,path.length()-i-1); - if (candidate!=null && candidate.getPathSpec().matches(path)) + MappedResource candidate = suffix_map.get(path, i + 1, path.length() - i - 1); + if (candidate != null && candidate.getPathSpec().matches(path)) return candidate; } break; } - + default: } } - + if (mr.getPathSpec().matches(path)) return mr; - - last_group=group; + + lastGroup = group; } - + return null; } @@ -202,55 +202,61 @@ public class PathMappings implements Iterable>, Dumpable { throw new RuntimeException("Path Spec String must start with '^', '/', or '*.': got [" + pathSpecString + "]"); } - return pathSpecString.charAt(0) == '^' ? new RegexPathSpec(pathSpecString):new ServletPathSpec(pathSpecString); + return pathSpecString.charAt(0) == '^' ? new RegexPathSpec(pathSpecString) : new ServletPathSpec(pathSpecString); } - + public E get(PathSpec spec) { Optional optionalResource = _mappings.stream() - .filter(mappedResource -> mappedResource.getPathSpec().equals(spec)) - .map(mappedResource -> mappedResource.getResource()) - .findFirst(); - if(!optionalResource.isPresent()) + .filter(mappedResource -> mappedResource.getPathSpec().equals(spec)) + .map(mappedResource -> mappedResource.getResource()) + .findFirst(); + if (!optionalResource.isPresent()) return null; - + return optionalResource.get(); } - + public boolean put(String pathSpecString, E resource) { - return put(asPathSpec(pathSpecString),resource); + return put(asPathSpec(pathSpecString), resource); } - + public boolean put(PathSpec pathSpec, E resource) { - MappedResource entry = new MappedResource<>(pathSpec,resource); + MappedResource entry = new MappedResource<>(pathSpec, resource); switch (pathSpec.group) { case EXACT: String exact = pathSpec.getPrefix(); - while (exact!=null && !_exactMap.put(exact,entry)) - _exactMap=new ArrayTernaryTrie<>((ArrayTernaryTrie>)_exactMap,1.5); + while (exact != null && !_exactMap.put(exact, entry)) + { + _exactMap = new ArrayTernaryTrie<>((ArrayTernaryTrie>)_exactMap, 1.5); + } break; case PREFIX_GLOB: String prefix = pathSpec.getPrefix(); - while (prefix!=null && !_prefixMap.put(prefix,entry)) - _prefixMap=new ArrayTernaryTrie<>((ArrayTernaryTrie>)_prefixMap,1.5); + while (prefix != null && !_prefixMap.put(prefix, entry)) + { + _prefixMap = new ArrayTernaryTrie<>((ArrayTernaryTrie>)_prefixMap, 1.5); + } break; case SUFFIX_GLOB: String suffix = pathSpec.getSuffix(); - while (suffix!=null && !_suffixMap.put(suffix,entry)) - _suffixMap=new ArrayTernaryTrie<>((ArrayTernaryTrie>)_prefixMap,1.5); + while (suffix != null && !_suffixMap.put(suffix, entry)) + { + _suffixMap = new ArrayTernaryTrie<>((ArrayTernaryTrie>)_prefixMap, 1.5); + } break; default: } - - boolean added =_mappings.add(entry); + + boolean added = _mappings.add(entry); if (LOG.isDebugEnabled()) - LOG.debug("{} {} to {}",added?"Added":"Ignored",entry,this); + LOG.debug("{} {} to {}", added ? "Added" : "Ignored", entry, this); return added; } - + @SuppressWarnings("incomplete-switch") public boolean remove(PathSpec pathSpec) { @@ -266,27 +272,26 @@ public class PathMappings implements Iterable>, Dumpable _suffixMap.remove(pathSpec.getSuffix()); break; } - + Iterator> iter = _mappings.iterator(); - boolean removed=false; + boolean removed = false; while (iter.hasNext()) { if (iter.next().getPathSpec().equals(pathSpec)) { - removed=true; + removed = true; iter.remove(); break; } } if (LOG.isDebugEnabled()) - LOG.debug("{} {} to {}",removed?"Removed":"Ignored",pathSpec,this); + LOG.debug("{} {} to {}", removed ? "Removed" : "Ignored", pathSpec, this); return removed; } @Override public String toString() { - return String.format("%s[size=%d]",this.getClass().getSimpleName(),_mappings.size()); + return String.format("%s[size=%d]", this.getClass().getSimpleName(), _mappings.size()); } - } diff --git a/jetty-http/src/main/java/org/eclipse/jetty/http/pathmap/PathSpec.java b/jetty-http/src/main/java/org/eclipse/jetty/http/pathmap/PathSpec.java index 4ecb76f01b4..eb1c2e111e3 100644 --- a/jetty-http/src/main/java/org/eclipse/jetty/http/pathmap/PathSpec.java +++ b/jetty-http/src/main/java/org/eclipse/jetty/http/pathmap/PathSpec.java @@ -90,7 +90,7 @@ public abstract class PathSpec implements Comparable * Get the number of path elements that this path spec declares. *

    * This is used to determine longest match logic. - * + * * @return the depth of the path segments that this spec declares */ public int getPathDepth() @@ -100,25 +100,23 @@ public abstract class PathSpec implements Comparable /** * Return the portion of the path that is after the path spec. - * - * @param path - * the path to match against + * + * @param path the path to match against * @return the path info portion of the string */ public abstract String getPathInfo(String path); /** * Return the portion of the path that matches a path spec. - * - * @param path - * the path to match against + * + * @param path the path to match against * @return the match, or null if no match at all */ public abstract String getPathMatch(String path); /** * The as-provided path spec. - * + * * @return the as-provided path spec */ public String getDeclaration() @@ -128,6 +126,7 @@ public abstract class PathSpec implements Comparable /** * A simple prefix match for the pathspec or null + * * @return A simple prefix match for the pathspec or null */ public String getPrefix() @@ -137,20 +136,19 @@ public abstract class PathSpec implements Comparable /** * A simple suffix match for the pathspec or null + * * @return A simple suffix match for the pathspec or null */ public String getSuffix() { return suffix; } - + /** * Get the relative path. - * - * @param base - * the base the path is relative to - * @param path - * the additional path + * + * @param base the base the path is relative to + * @param path the additional path * @return the base plus path with pathSpec portion removed */ public abstract String getRelativePath(String base, String path); @@ -160,15 +158,14 @@ public abstract class PathSpec implements Comparable { final int prime = 31; int result = 1; - result = (prime * result) + ((pathSpec == null)?0:pathSpec.hashCode()); + result = (prime * result) + ((pathSpec == null) ? 0 : pathSpec.hashCode()); return result; } /** * Test to see if the provided path matches this path spec - * - * @param path - * the path to test + * + * @param path the path to test * @return true if the path matches this path spec, false otherwise */ public abstract boolean matches(String path); diff --git a/jetty-http/src/main/java/org/eclipse/jetty/http/pathmap/PathSpecGroup.java b/jetty-http/src/main/java/org/eclipse/jetty/http/pathmap/PathSpecGroup.java index 0f286236990..7d364ab2035 100644 --- a/jetty-http/src/main/java/org/eclipse/jetty/http/pathmap/PathSpecGroup.java +++ b/jetty-http/src/main/java/org/eclipse/jetty/http/pathmap/PathSpecGroup.java @@ -23,7 +23,7 @@ package org.eclipse.jetty.http.pathmap; *

    * This is used to facilitate proper pathspec search order. *

    - * Search Order: + * Search Order: *

      *
    1. {@link PathSpecGroup#ordinal()} [increasing]
    2. *
    3. {@link PathSpec#specLength} [decreasing]
    4. @@ -36,12 +36,12 @@ public enum PathSpecGroup /** * The root spec for accessing the Root behavior. - * + * *
            *   ""           - servlet spec       (Root Servlet)
            *   null         - servlet spec       (Root Servlet)
            * 
      - * + * * Note: there is no known uri-template spec variant of this kind of path spec */ ROOT, @@ -51,12 +51,12 @@ public enum PathSpecGroup EXACT, /** * For path specs that have a hardcoded prefix and suffix with wildcard glob in the middle. - * + * *
            *   "^/downloads/[^/]*.zip$"  - regex spec
            *   "/a/{var}/c"              - uri-template spec
            * 
      - * + * * Note: there is no known servlet spec variant of this kind of path spec */ MIDDLE_GLOB, @@ -74,25 +74,25 @@ public enum PathSpecGroup PREFIX_GLOB, /** * For path specs that have a wildcard glob with a hardcoded suffix - * + * *
            *   "*.do"        - servlet spec
            *   "*.css"       - servlet spec
            *   "^.*\.zip$"   - regex spec
            * 
      - * + * * Note: there is no known uri-template spec variant of this kind of path spec */ SUFFIX_GLOB, /** * The default spec for accessing the Default path behavior. - * + * *
            *   "/"           - servlet spec      (Default Servlet)
            *   "/"           - uri-template spec (Root Context)
            *   "^/$"         - regex spec        (Root Context)
            * 
      - * + * * Per Servlet Spec, pathInfo is always null for these specs. * If nothing above matches, then default will match. */ diff --git a/jetty-http/src/main/java/org/eclipse/jetty/http/pathmap/PathSpecSet.java b/jetty-http/src/main/java/org/eclipse/jetty/http/pathmap/PathSpecSet.java index 75e7ede0bca..252706d67dc 100644 --- a/jetty-http/src/main/java/org/eclipse/jetty/http/pathmap/PathSpecSet.java +++ b/jetty-http/src/main/java/org/eclipse/jetty/http/pathmap/PathSpecSet.java @@ -34,10 +34,9 @@ public class PathSpecSet extends AbstractSet implements Predicate implements Predicate implements Predicate iterator() { diff --git a/jetty-http/src/main/java/org/eclipse/jetty/http/pathmap/RegexPathSpec.java b/jetty-http/src/main/java/org/eclipse/jetty/http/pathmap/RegexPathSpec.java index 42624ac7ca2..5381f4726af 100644 --- a/jetty-http/src/main/java/org/eclipse/jetty/http/pathmap/RegexPathSpec.java +++ b/jetty-http/src/main/java/org/eclipse/jetty/http/pathmap/RegexPathSpec.java @@ -76,15 +76,15 @@ public class RegexPathSpec extends PathSpec // Figure out the grouping based on the signature String sig = signature.toString(); - if (Pattern.matches("^l*$",sig)) + if (Pattern.matches("^l*$", sig)) { this.group = PathSpecGroup.EXACT; } - else if (Pattern.matches("^l*g+",sig)) + else if (Pattern.matches("^l*g+", sig)) { this.group = PathSpecGroup.PREFIX_GLOB; } - else if (Pattern.matches("^g+l+$",sig)) + else if (Pattern.matches("^g+l+$", sig)) { this.group = PathSpecGroup.SUFFIX_GLOB; } @@ -140,7 +140,7 @@ public class RegexPathSpec extends PathSpec { idx--; } - return path.substring(0,idx); + return path.substring(0, idx); } } return path; @@ -167,7 +167,7 @@ public class RegexPathSpec extends PathSpec if (idx >= 0) { // match only non-query part - return getMatcher(path.substring(0,idx)).matches(); + return getMatcher(path.substring(0, idx)).matches(); } else { diff --git a/jetty-http/src/main/java/org/eclipse/jetty/http/pathmap/ServletPathSpec.java b/jetty-http/src/main/java/org/eclipse/jetty/http/pathmap/ServletPathSpec.java index 704a33ecbd2..cceb6e519f1 100644 --- a/jetty-http/src/main/java/org/eclipse/jetty/http/pathmap/ServletPathSpec.java +++ b/jetty-http/src/main/java/org/eclipse/jetty/http/pathmap/ServletPathSpec.java @@ -26,18 +26,17 @@ public class ServletPathSpec extends PathSpec /** * If a servlet or filter path mapping isn't a suffix mapping, ensure * it starts with '/' - * + * * @param pathSpec the servlet or filter mapping pattern * @return the pathSpec prefixed by '/' if appropriate */ public static String normalize(String pathSpec) { - if (StringUtil.isNotBlank(pathSpec) && !pathSpec.startsWith("/") && !pathSpec.startsWith("*")) + if (StringUtil.isNotBlank(pathSpec) && !pathSpec.startsWith("/") && !pathSpec.startsWith("*")) return "/" + pathSpec; return pathSpec; } - /** * @param pathSpec the path spec * @param path the path @@ -56,37 +55,39 @@ public class ServletPathSpec extends PathSpec */ public static boolean match(String pathSpec, String path, boolean noDefault) { - if (pathSpec.length()==0) + if (pathSpec.length() == 0) return "/".equals(path); char c = pathSpec.charAt(0); - if (c=='/') + if (c == '/') { - if (!noDefault && pathSpec.length()==1 || pathSpec.equals(path)) + if (!noDefault && pathSpec.length() == 1 || pathSpec.equals(path)) return true; - if(isPathWildcardMatch(pathSpec, path)) + if (isPathWildcardMatch(pathSpec, path)) return true; } - else if (c=='*') - return path.regionMatches(path.length()-pathSpec.length()+1, - pathSpec,1,pathSpec.length()-1); + else if (c == '*') + return path.regionMatches(path.length() - pathSpec.length() + 1, + pathSpec, 1, pathSpec.length() - 1); return false; } private static boolean isPathWildcardMatch(String pathSpec, String path) { // For a spec of "/foo/*" match "/foo" , "/foo/..." but not "/foobar" - int cpl=pathSpec.length()-2; - if (pathSpec.endsWith("/*") && path.regionMatches(0,pathSpec,0,cpl)) + int cpl = pathSpec.length() - 2; + if (pathSpec.endsWith("/*") && path.regionMatches(0, pathSpec, 0, cpl)) { - if (path.length()==cpl || '/'==path.charAt(cpl)) + if (path.length() == cpl || '/' == path.charAt(cpl)) return true; } return false; } - /** Return the portion of a path that matches a path spec. + /** + * Return the portion of a path that matches a path spec. + * * @param pathSpec the path spec * @param path the path * @return null if no match at all. @@ -95,27 +96,29 @@ public class ServletPathSpec extends PathSpec { char c = pathSpec.charAt(0); - if (c=='/') + if (c == '/') { - if (pathSpec.length()==1) + if (pathSpec.length() == 1) return path; if (pathSpec.equals(path)) return path; if (isPathWildcardMatch(pathSpec, path)) - return path.substring(0,pathSpec.length()-2); + return path.substring(0, pathSpec.length() - 2); } - else if (c=='*') + else if (c == '*') { - if (path.regionMatches(path.length()-(pathSpec.length()-1), - pathSpec,1,pathSpec.length()-1)) + if (path.regionMatches(path.length() - (pathSpec.length() - 1), + pathSpec, 1, pathSpec.length() - 1)) return path; } return null; } - /** Return the portion of a path that is after a path spec. + /** + * Return the portion of a path that is after a path spec. + * * @param pathSpec the path spec * @param path the path * @return The path info string @@ -127,9 +130,9 @@ public class ServletPathSpec extends PathSpec char c = pathSpec.charAt(0); - if (c=='/') + if (c == '/') { - if (pathSpec.length()==1) + if (pathSpec.length() == 1) return null; boolean wildcard = isPathWildcardMatch(pathSpec, path); @@ -140,16 +143,17 @@ public class ServletPathSpec extends PathSpec if (wildcard) { - if (path.length()==pathSpec.length()-2) + if (path.length() == pathSpec.length() - 2) return null; - return path.substring(pathSpec.length()-2); + return path.substring(pathSpec.length() - 2); } } return null; } - - /** Relative path. + /** + * Relative path. + * * @param base The base the path is relative to. * @param pathSpec The spec of the path segment to ignore. * @param path the additional path @@ -157,7 +161,7 @@ public class ServletPathSpec extends PathSpec */ public static String relativePath(String base, String pathSpec, - String path ) + String path) { String info = pathInfo(pathSpec, path); if (info == null) @@ -176,7 +180,7 @@ public class ServletPathSpec extends PathSpec path = base + URIUtil.SLASH + info; return path; } - + public ServletPathSpec(String servletPathSpec) { if (servletPathSpec == null) @@ -196,7 +200,7 @@ public class ServletPathSpec extends PathSpec } // The Default Path Spec - if("/".equals(servletPathSpec)) + if ("/".equals(servletPathSpec)) { super.pathSpec = "/"; super.pathDepth = -1; // force this to be at the end of the sort order @@ -204,7 +208,7 @@ public class ServletPathSpec extends PathSpec this.group = PathSpecGroup.DEFAULT; return; } - + this.specLength = servletPathSpec.length(); super.pathDepth = 0; char lastChar = servletPathSpec.charAt(specLength - 1); @@ -212,13 +216,13 @@ public class ServletPathSpec extends PathSpec if ((servletPathSpec.charAt(0) == '/') && (specLength > 1) && (lastChar == '*')) { this.group = PathSpecGroup.PREFIX_GLOB; - this.prefix = servletPathSpec.substring(0,specLength-2); + this.prefix = servletPathSpec.substring(0, specLength - 2); } // suffix based else if (servletPathSpec.charAt(0) == '*') { this.group = PathSpecGroup.SUFFIX_GLOB; - this.suffix = servletPathSpec.substring(2,specLength); + this.suffix = servletPathSpec.substring(2, specLength); } else { @@ -268,12 +272,12 @@ public class ServletPathSpec extends PathSpec // only allowed to have '*' at the end of the path spec if (idx != (len - 1)) { - throw new IllegalArgumentException("Servlet Spec 12.2 violation: glob '*' can only exist at end of prefix based matches: bad spec \""+ servletPathSpec +"\""); + throw new IllegalArgumentException("Servlet Spec 12.2 violation: glob '*' can only exist at end of prefix based matches: bad spec \"" + servletPathSpec + "\""); } - - if (idx<1 || servletPathSpec.charAt(idx-1)!='/') + + if (idx < 1 || servletPathSpec.charAt(idx - 1) != '/') { - throw new IllegalArgumentException("Servlet Spec 12.2 violation: suffix glob '*' can only exist after '/': bad spec \""+ servletPathSpec +"\""); + throw new IllegalArgumentException("Servlet Spec 12.2 violation: suffix glob '*' can only exist after '/': bad spec \"" + servletPathSpec + "\""); } } else if (servletPathSpec.startsWith("*.")) @@ -283,19 +287,19 @@ public class ServletPathSpec extends PathSpec // cannot have path separator if (idx >= 0) { - throw new IllegalArgumentException("Servlet Spec 12.2 violation: suffix based path spec cannot have path separators: bad spec \""+ servletPathSpec +"\""); + throw new IllegalArgumentException("Servlet Spec 12.2 violation: suffix based path spec cannot have path separators: bad spec \"" + servletPathSpec + "\""); } - idx = servletPathSpec.indexOf('*',2); + idx = servletPathSpec.indexOf('*', 2); // only allowed to have 1 glob '*', at the start of the path spec if (idx >= 1) { - throw new IllegalArgumentException("Servlet Spec 12.2 violation: suffix based path spec cannot have multiple glob '*': bad spec \""+ servletPathSpec +"\""); + throw new IllegalArgumentException("Servlet Spec 12.2 violation: suffix based path spec cannot have multiple glob '*': bad spec \"" + servletPathSpec + "\""); } } else { - throw new IllegalArgumentException("Servlet Spec 12.2 violation: path spec must start with \"/\" or \"*.\": bad spec \""+ servletPathSpec +"\""); + throw new IllegalArgumentException("Servlet Spec 12.2 violation: path spec must start with \"/\" or \"*.\": bad spec \"" + servletPathSpec + "\""); } } @@ -332,14 +336,14 @@ public class ServletPathSpec extends PathSpec case PREFIX_GLOB: if (isWildcardMatch(path)) { - return path.substring(0,specLength - 2); + return path.substring(0, specLength - 2); } else { return null; } case SUFFIX_GLOB: - if (path.regionMatches(path.length() - (specLength - 1),pathSpec,1,specLength - 1)) + if (path.regionMatches(path.length() - (specLength - 1), pathSpec, 1, specLength - 1)) { return path; } @@ -393,7 +397,7 @@ public class ServletPathSpec extends PathSpec { // For a spec of "/foo/*" match "/foo" , "/foo/..." but not "/foobar" int cpl = specLength - 2; - if ((group == PathSpecGroup.PREFIX_GLOB) && (path.regionMatches(0,pathSpec,0,cpl))) + if ((group == PathSpecGroup.PREFIX_GLOB) && (path.regionMatches(0, pathSpec, 0, cpl))) { if ((path.length() == cpl) || ('/' == path.charAt(cpl))) { @@ -413,7 +417,7 @@ public class ServletPathSpec extends PathSpec case PREFIX_GLOB: return isWildcardMatch(path); case SUFFIX_GLOB: - return path.regionMatches((path.length() - specLength) + 1,pathSpec,1,specLength - 1); + return path.regionMatches((path.length() - specLength) + 1, pathSpec, 1, specLength - 1); case ROOT: // Only "/" matches return ("/".equals(path)); diff --git a/jetty-http/src/main/java/org/eclipse/jetty/http/pathmap/UriTemplatePathSpec.java b/jetty-http/src/main/java/org/eclipse/jetty/http/pathmap/UriTemplatePathSpec.java index 717a27a65e8..f24c1a05fb3 100644 --- a/jetty-http/src/main/java/org/eclipse/jetty/http/pathmap/UriTemplatePathSpec.java +++ b/jetty-http/src/main/java/org/eclipse/jetty/http/pathmap/UriTemplatePathSpec.java @@ -36,19 +36,23 @@ import org.eclipse.jetty.util.log.Logger; /** * PathSpec for URI Template based declarations - * + * * @see URI Templates (Level 1) */ public class UriTemplatePathSpec extends RegexPathSpec { private static final Logger LOG = Log.getLogger(UriTemplatePathSpec.class); - + private static final Pattern VARIABLE_PATTERN = Pattern.compile("\\{(.*)\\}"); - /** Reserved Symbols in URI Template variable */ + /** + * Reserved Symbols in URI Template variable + */ private static final String VARIABLE_RESERVED = ":/?#[]@" + // gen-delims - "!$&'()*+,;="; // sub-delims - /** Allowed Symbols in a URI Template variable */ - private static final String VARIABLE_SYMBOLS="-._"; + "!$&'()*+,;="; // sub-delims + /** + * Allowed Symbols in a URI Template variable + */ + private static final String VARIABLE_SYMBOLS = "-._"; private static final Set FORBIDDEN_SEGMENTS; static @@ -59,12 +63,12 @@ public class UriTemplatePathSpec extends RegexPathSpec FORBIDDEN_SEGMENTS.add("//"); } - private String variables[]; + private String[] variables; public UriTemplatePathSpec(String rawSpec) { super(); - Objects.requireNonNull(rawSpec,"Path Param Spec cannot be null"); + Objects.requireNonNull(rawSpec, "Path Param Spec cannot be null"); if ("".equals(rawSpec) || "/".equals(rawSpec)) { @@ -107,8 +111,8 @@ public class UriTemplatePathSpec extends RegexPathSpec List varNames = new ArrayList<>(); // split up into path segments (ignoring the first slash that will always be empty) - String segments[] = rawSpec.substring(1).split("/"); - char segmentSignature[] = new char[segments.length]; + String[] segments = rawSpec.substring(1).split("/"); + char[] segmentSignature = new char[segments.length]; this.pathDepth = segments.length; for (int i = 0; i < segments.length; i++) { @@ -185,9 +189,9 @@ public class UriTemplatePathSpec extends RegexPathSpec } } } - + // Handle trailing slash (which is not picked up during split) - if(rawSpec.charAt(rawSpec.length()-1) == '/') + if (rawSpec.charAt(rawSpec.length() - 1) == '/') { regex.append('/'); } @@ -202,15 +206,15 @@ public class UriTemplatePathSpec extends RegexPathSpec // Convert signature to group String sig = String.valueOf(segmentSignature); - if (Pattern.matches("^e*$",sig)) + if (Pattern.matches("^e*$", sig)) { this.group = PathSpecGroup.EXACT; } - else if (Pattern.matches("^e*v+",sig)) + else if (Pattern.matches("^e*v+", sig)) { this.group = PathSpecGroup.PREFIX_GLOB; } - else if (Pattern.matches("^v+e+",sig)) + else if (Pattern.matches("^v+e+", sig)) { this.group = PathSpecGroup.SUFFIX_GLOB; } @@ -222,16 +226,15 @@ public class UriTemplatePathSpec extends RegexPathSpec /** * Validate variable literal name, per RFC6570, Section 2.1 Literals - * @param variable */ private void assertIsValidVariableLiteral(String variable) { int len = variable.length(); - + int i = 0; int codepoint; boolean valid = (len > 0); // must not be zero length - + while (valid && i < len) { codepoint = variable.codePointAt(i); @@ -267,7 +270,7 @@ public class UriTemplatePathSpec extends RegexPathSpec continue; } } - + valid = false; } @@ -282,27 +285,27 @@ public class UriTemplatePathSpec extends RegexPathSpec throw new IllegalArgumentException(err.toString()); } } - + private boolean isValidBasicLiteralCodepoint(int codepoint) { // basic letters or digits - if((codepoint >= 'a' && codepoint <= 'z') || - (codepoint >= 'A' && codepoint <= 'Z') || - (codepoint >= '0' && codepoint <= '9')) + if ((codepoint >= 'a' && codepoint <= 'z') || + (codepoint >= 'A' && codepoint <= 'Z') || + (codepoint >= '0' && codepoint <= '9')) { return true; } - + // basic allowed symbols - if(VARIABLE_SYMBOLS.indexOf(codepoint) >= 0) + if (VARIABLE_SYMBOLS.indexOf(codepoint) >= 0) { return true; // valid simple value } - + // basic reserved symbols - if(VARIABLE_RESERVED.indexOf(codepoint) >= 0) + if (VARIABLE_RESERVED.indexOf(codepoint) >= 0) { - LOG.warn("Detected URI Template reserved symbol [{}] in path spec \"{}\"",(char)codepoint,pathSpec); + LOG.warn("Detected URI Template reserved symbol [{}] in path spec \"{}\"", (char)codepoint, pathSpec); return false; // valid simple value } diff --git a/jetty-http/src/test/java/org/eclipse/jetty/http/CookieCutterLenientTest.java b/jetty-http/src/test/java/org/eclipse/jetty/http/CookieCutterLenientTest.java index ff5b239545f..e5bf0672a16 100644 --- a/jetty-http/src/test/java/org/eclipse/jetty/http/CookieCutterLenientTest.java +++ b/jetty-http/src/test/java/org/eclipse/jetty/http/CookieCutterLenientTest.java @@ -148,12 +148,12 @@ public class CookieCutterLenientTest Arguments.of("$Version=0; rToken=F_TOKEN''!--\"=&{()}", "rToken", "F_TOKEN''!--\"=&{()}"), // Commas that were not commas - Arguments.of("name=foo,bar","name","foo,bar"), - Arguments.of("name=foo , bar","name","foo , bar"), - Arguments.of("name=foo , bar, bob","name","foo , bar, bob") + Arguments.of("name=foo,bar", "name", "foo,bar"), + Arguments.of("name=foo , bar", "name", "foo , bar"), + Arguments.of("name=foo , bar, bob", "name", "foo , bar, bob") ); } - + @ParameterizedTest @MethodSource("data") public void testLenientBehavior(String rawHeader, String expectedName, String expectedValue) @@ -161,7 +161,7 @@ public class CookieCutterLenientTest TestCutter cutter = new TestCutter(); cutter.parseField(rawHeader); - if (expectedName==null) + if (expectedName == null) assertThat("Cookies.length", cutter.names.size(), is(0)); else { @@ -171,7 +171,6 @@ public class CookieCutterLenientTest } } - class TestCutter extends CookieCutter { List names = new ArrayList<>(); @@ -193,5 +192,7 @@ public class CookieCutterLenientTest { super.parseFields(Collections.singletonList(field)); } - }; + } + + ; } diff --git a/jetty-http/src/test/java/org/eclipse/jetty/http/CookieCutterTest.java b/jetty-http/src/test/java/org/eclipse/jetty/http/CookieCutterTest.java index de68a91f493..de27eb12d82 100644 --- a/jetty-http/src/test/java/org/eclipse/jetty/http/CookieCutterTest.java +++ b/jetty-http/src/test/java/org/eclipse/jetty/http/CookieCutterTest.java @@ -29,7 +29,7 @@ import static org.hamcrest.Matchers.is; public class CookieCutterTest { - private Cookie[] parseCookieHeaders(CookieCompliance compliance,String... headers) + private Cookie[] parseCookieHeaders(CookieCompliance compliance, String... headers) { TestCutter cutter = new TestCutter(compliance, null); for (String header : headers) @@ -38,7 +38,7 @@ public class CookieCutterTest } return cutter.cookies.toArray(new Cookie[cutter.cookies.size()]); } - + private void assertCookie(String prefix, Cookie cookie, String expectedName, String expectedValue, @@ -50,7 +50,7 @@ public class CookieCutterTest assertThat(prefix + ".version", cookie.getVersion(), is(expectedVersion)); assertThat(prefix + ".path", cookie.getPath(), is(expectedPath)); } - + /** * Example from RFC2109 and RFC2965 */ @@ -58,13 +58,13 @@ public class CookieCutterTest public void testRFC_Single() { String rawCookie = "$Version=\"1\"; Customer=\"WILE_E_COYOTE\"; $Path=\"/acme\""; - - Cookie cookies[] = parseCookieHeaders(CookieCompliance.RFC2965,rawCookie); - + + Cookie cookies[] = parseCookieHeaders(CookieCompliance.RFC2965, rawCookie); + assertThat("Cookies.length", cookies.length, is(1)); assertCookie("Cookies[0]", cookies[0], "Customer", "WILE_E_COYOTE", 1, "/acme"); } - + /** * Example from RFC2109 and RFC2965 */ @@ -72,16 +72,16 @@ public class CookieCutterTest public void testRFC_Double() { String rawCookie = "$Version=\"1\"; " + - "Customer=\"WILE_E_COYOTE\"; $Path=\"/acme\"; " + - "Part_Number=\"Rocket_Launcher_0001\"; $Path=\"/acme\""; - - Cookie cookies[] = parseCookieHeaders(CookieCompliance.RFC2965,rawCookie); - + "Customer=\"WILE_E_COYOTE\"; $Path=\"/acme\"; " + + "Part_Number=\"Rocket_Launcher_0001\"; $Path=\"/acme\""; + + Cookie cookies[] = parseCookieHeaders(CookieCompliance.RFC2965, rawCookie); + assertThat("Cookies.length", cookies.length, is(2)); assertCookie("Cookies[0]", cookies[0], "Customer", "WILE_E_COYOTE", 1, "/acme"); assertCookie("Cookies[1]", cookies[1], "Part_Number", "Rocket_Launcher_0001", 1, "/acme"); } - + /** * Example from RFC2109 and RFC2965 */ @@ -89,18 +89,18 @@ public class CookieCutterTest public void testRFC_Triple() { String rawCookie = "$Version=\"1\"; " + - "Customer=\"WILE_E_COYOTE\"; $Path=\"/acme\"; " + - "Part_Number=\"Rocket_Launcher_0001\"; $Path=\"/acme\"; " + - "Shipping=\"FedEx\"; $Path=\"/acme\""; - - Cookie cookies[] = parseCookieHeaders(CookieCompliance.RFC2965,rawCookie); - + "Customer=\"WILE_E_COYOTE\"; $Path=\"/acme\"; " + + "Part_Number=\"Rocket_Launcher_0001\"; $Path=\"/acme\"; " + + "Shipping=\"FedEx\"; $Path=\"/acme\""; + + Cookie cookies[] = parseCookieHeaders(CookieCompliance.RFC2965, rawCookie); + assertThat("Cookies.length", cookies.length, is(3)); assertCookie("Cookies[0]", cookies[0], "Customer", "WILE_E_COYOTE", 1, "/acme"); assertCookie("Cookies[1]", cookies[1], "Part_Number", "Rocket_Launcher_0001", 1, "/acme"); assertCookie("Cookies[2]", cookies[2], "Shipping", "FedEx", 1, "/acme"); } - + /** * Example from RFC2109 and RFC2965 */ @@ -108,16 +108,16 @@ public class CookieCutterTest public void testRFC_PathExample() { String rawCookie = "$Version=\"1\"; " + - "Part_Number=\"Riding_Rocket_0023\"; $Path=\"/acme/ammo\"; " + - "Part_Number=\"Rocket_Launcher_0001\"; $Path=\"/acme\""; - - Cookie cookies[] = parseCookieHeaders(CookieCompliance.RFC2965,rawCookie); - + "Part_Number=\"Riding_Rocket_0023\"; $Path=\"/acme/ammo\"; " + + "Part_Number=\"Rocket_Launcher_0001\"; $Path=\"/acme\""; + + Cookie cookies[] = parseCookieHeaders(CookieCompliance.RFC2965, rawCookie); + assertThat("Cookies.length", cookies.length, is(2)); assertCookie("Cookies[0]", cookies[0], "Part_Number", "Riding_Rocket_0023", 1, "/acme/ammo"); assertCookie("Cookies[1]", cookies[1], "Part_Number", "Rocket_Launcher_0001", 1, "/acme"); } - + /** * Example from RFC2109 */ @@ -125,16 +125,16 @@ public class CookieCutterTest public void testRFC2109_CookieSpoofingExample() { String rawCookie = "$Version=\"1\"; " + - "session_id=\"1234\"; " + - "session_id=\"1111\"; $Domain=\".cracker.edu\""; - - Cookie cookies[] = parseCookieHeaders(CookieCompliance.RFC2965,rawCookie); - + "session_id=\"1234\"; " + + "session_id=\"1111\"; $Domain=\".cracker.edu\""; + + Cookie cookies[] = parseCookieHeaders(CookieCompliance.RFC2965, rawCookie); + assertThat("Cookies.length", cookies.length, is(2)); assertCookie("Cookies[0]", cookies[0], "session_id", "1234", 1, null); assertCookie("Cookies[1]", cookies[1], "session_id", "1111", 1, null); } - + /** * Example from RFC2965 */ @@ -142,21 +142,20 @@ public class CookieCutterTest public void testRFC2965_CookieSpoofingExample() { String rawCookie = "$Version=\"1\"; session_id=\"1234\", " + - "$Version=\"1\"; session_id=\"1111\"; $Domain=\".cracker.edu\""; + "$Version=\"1\"; session_id=\"1111\"; $Domain=\".cracker.edu\""; - - Cookie cookies[] = parseCookieHeaders(CookieCompliance.RFC2965,rawCookie); + Cookie cookies[] = parseCookieHeaders(CookieCompliance.RFC2965, rawCookie); assertThat("Cookies.length", cookies.length, is(2)); assertCookie("Cookies[0]", cookies[0], "session_id", "1234", 1, null); assertCookie("Cookies[1]", cookies[1], "session_id", "1111", 1, null); - cookies = parseCookieHeaders(CookieCompliance.RFC6265,rawCookie); + cookies = parseCookieHeaders(CookieCompliance.RFC6265, rawCookie); assertThat("Cookies.length", cookies.length, is(2)); assertCookie("Cookies[0]", cookies[0], "session_id", "1234\", $Version=\"1", 0, null); assertCookie("Cookies[1]", cookies[1], "session_id", "1111", 0, null); } - + /** * Example from RFC6265 */ @@ -164,13 +163,13 @@ public class CookieCutterTest public void testRFC6265_SidExample() { String rawCookie = "SID=31d4d96e407aad42"; - - Cookie cookies[] = parseCookieHeaders(CookieCompliance.RFC6265,rawCookie); - + + Cookie cookies[] = parseCookieHeaders(CookieCompliance.RFC6265, rawCookie); + assertThat("Cookies.length", cookies.length, is(1)); assertCookie("Cookies[0]", cookies[0], "SID", "31d4d96e407aad42", 0, null); } - + /** * Example from RFC6265 */ @@ -178,14 +177,14 @@ public class CookieCutterTest public void testRFC6265_SidLangExample() { String rawCookie = "SID=31d4d96e407aad42; lang=en-US"; - - Cookie cookies[] = parseCookieHeaders(CookieCompliance.RFC6265,rawCookie); - + + Cookie cookies[] = parseCookieHeaders(CookieCompliance.RFC6265, rawCookie); + assertThat("Cookies.length", cookies.length, is(2)); assertCookie("Cookies[0]", cookies[0], "SID", "31d4d96e407aad42", 0, null); assertCookie("Cookies[1]", cookies[1], "lang", "en-US", 0, null); } - + /** * Basic name=value, following RFC6265 rules */ @@ -193,13 +192,13 @@ public class CookieCutterTest public void testKeyValue() { String rawCookie = "key=value"; - - Cookie cookies[] = parseCookieHeaders(CookieCompliance.RFC6265,rawCookie); - + + Cookie cookies[] = parseCookieHeaders(CookieCompliance.RFC6265, rawCookie); + assertThat("Cookies.length", cookies.length, is(1)); assertCookie("Cookies[0]", cookies[0], "key", "value", 0, null); } - + /** * Basic name=value, following RFC6265 rules */ @@ -207,13 +206,12 @@ public class CookieCutterTest public void testDollarName() { String rawCookie = "$key=value"; - - Cookie cookies[] = parseCookieHeaders(CookieCompliance.RFC6265,rawCookie); - + + Cookie cookies[] = parseCookieHeaders(CookieCompliance.RFC6265, rawCookie); + assertThat("Cookies.length", cookies.length, is(0)); } - static class Cookie { String name; @@ -276,12 +274,14 @@ public class CookieCutterTest @Override protected void addCookie(String cookieName, String cookieValue, String cookieDomain, String cookiePath, int cookieVersion, String cookieComment) { - cookies.add(new Cookie(cookieName,cookieValue,cookieDomain,cookiePath,cookieVersion,cookieComment)); + cookies.add(new Cookie(cookieName, cookieValue, cookieDomain, cookiePath, cookieVersion, cookieComment)); } public void parseFields(String... fields) { super.parseFields(Arrays.asList(fields)); } - }; + } + + ; } diff --git a/jetty-http/src/test/java/org/eclipse/jetty/http/DateParserTest.java b/jetty-http/src/test/java/org/eclipse/jetty/http/DateParserTest.java index f219fc0250e..72a90c31d02 100644 --- a/jetty-http/src/test/java/org/eclipse/jetty/http/DateParserTest.java +++ b/jetty-http/src/test/java/org/eclipse/jetty/http/DateParserTest.java @@ -41,5 +41,4 @@ public class DateParserTest { assertEquals((-1L), DateParser.parseDate("3%~ GMT")); } - } diff --git a/jetty-http/src/test/java/org/eclipse/jetty/http/GZIPContentDecoderTest.java b/jetty-http/src/test/java/org/eclipse/jetty/http/GZIPContentDecoderTest.java index 46b22aa36b3..93c7c4c3f37 100644 --- a/jetty-http/src/test/java/org/eclipse/jetty/http/GZIPContentDecoderTest.java +++ b/jetty-http/src/test/java/org/eclipse/jetty/http/GZIPContentDecoderTest.java @@ -60,7 +60,6 @@ public class GZIPContentDecoderTest buffers.decrementAndGet(); super.release(buffer); } - }; } @@ -98,7 +97,9 @@ public class GZIPContentDecoderTest { String data = "0123456789ABCDEF"; for (int i = 0; i < 10; ++i) + { data += data; + } ByteArrayOutputStream baos = new ByteArrayOutputStream(); GZIPOutputStream output = new GZIPOutputStream(baos); output.write(data.getBytes(StandardCharsets.UTF_8)); @@ -109,7 +110,9 @@ public class GZIPContentDecoderTest GZIPInputStream input = new GZIPInputStream(new ByteArrayInputStream(bytes), 1); int read; while ((read = input.read()) >= 0) + { baos.write(read); + } assertEquals(data, new String(baos.toByteArray(), StandardCharsets.UTF_8)); } @@ -262,7 +265,9 @@ public class GZIPContentDecoderTest { String data = "0123456789ABCDEF"; for (int i = 0; i < 10; ++i) + { data += data; + } ByteArrayOutputStream baos = new ByteArrayOutputStream(); GZIPOutputStream output = new GZIPOutputStream(baos); output.write(data.getBytes(StandardCharsets.UTF_8)); @@ -286,7 +291,9 @@ public class GZIPContentDecoderTest { String data = "0123456789ABCDEF"; for (int i = 0; i < 10; ++i) + { data += data; + } ByteArrayOutputStream baos = new ByteArrayOutputStream(); GZIPOutputStream output = new GZIPOutputStream(baos); output.write(data.getBytes(StandardCharsets.UTF_8)); @@ -312,7 +319,9 @@ public class GZIPContentDecoderTest { String data1 = "0123456789ABCDEF"; for (int i = 0; i < 10; ++i) + { data1 += data1; + } ByteArrayOutputStream baos = new ByteArrayOutputStream(); GZIPOutputStream output = new GZIPOutputStream(baos); output.write(data1.getBytes(StandardCharsets.UTF_8)); diff --git a/jetty-http/src/test/java/org/eclipse/jetty/http/HttpCookieTest.java b/jetty-http/src/test/java/org/eclipse/jetty/http/HttpCookieTest.java index c1ac8685311..358bb397033 100644 --- a/jetty-http/src/test/java/org/eclipse/jetty/http/HttpCookieTest.java +++ b/jetty-http/src/test/java/org/eclipse/jetty/http/HttpCookieTest.java @@ -40,38 +40,36 @@ public class HttpCookieTest public void testSetRFC2965Cookie() throws Exception { HttpCookie httpCookie; - - httpCookie = new HttpCookie("null", null, null, null, -1, false, false, null, -1); - assertEquals("null=",httpCookie.getRFC2965SetCookie()); + httpCookie = new HttpCookie("null", null, null, null, -1, false, false, null, -1); + assertEquals("null=", httpCookie.getRFC2965SetCookie()); httpCookie = new HttpCookie("minimal", "value", null, null, -1, false, false, null, -1); - assertEquals("minimal=value",httpCookie.getRFC2965SetCookie()); + assertEquals("minimal=value", httpCookie.getRFC2965SetCookie()); httpCookie = new HttpCookie("everything", "something", "domain", "path", 0, true, true, "noncomment", 0); - assertEquals("everything=something;Version=1;Path=path;Domain=domain;Expires=Thu, 01-Jan-1970 00:00:00 GMT;Max-Age=0;Secure;HttpOnly;Comment=noncomment",httpCookie.getRFC2965SetCookie()); - + assertEquals("everything=something;Version=1;Path=path;Domain=domain;Expires=Thu, 01-Jan-1970 00:00:00 GMT;Max-Age=0;Secure;HttpOnly;Comment=noncomment", httpCookie.getRFC2965SetCookie()); + httpCookie = new HttpCookie("everything", "value", "domain", "path", 0, true, true, "comment", 0); - assertEquals("everything=value;Version=1;Path=path;Domain=domain;Expires=Thu, 01-Jan-1970 00:00:00 GMT;Max-Age=0;Secure;HttpOnly;Comment=comment",httpCookie.getRFC2965SetCookie()); - + assertEquals("everything=value;Version=1;Path=path;Domain=domain;Expires=Thu, 01-Jan-1970 00:00:00 GMT;Max-Age=0;Secure;HttpOnly;Comment=comment", httpCookie.getRFC2965SetCookie()); httpCookie = new HttpCookie("ev erything", "va lue", "do main", "pa th", 1, true, true, "co mment", 1); - String setCookie=httpCookie.getRFC2965SetCookie(); + String setCookie = httpCookie.getRFC2965SetCookie(); assertThat(setCookie, Matchers.startsWith("\"ev erything\"=\"va lue\";Version=1;Path=\"pa th\";Domain=\"do main\";Expires=")); - assertThat(setCookie,Matchers.endsWith(" GMT;Max-Age=1;Secure;HttpOnly;Comment=\"co mment\"")); + assertThat(setCookie, Matchers.endsWith(" GMT;Max-Age=1;Secure;HttpOnly;Comment=\"co mment\"")); httpCookie = new HttpCookie("name", "value", null, null, -1, false, false, null, 0); - setCookie=httpCookie.getRFC2965SetCookie(); - assertEquals(-1,setCookie.indexOf("Version=")); + setCookie = httpCookie.getRFC2965SetCookie(); + assertEquals(-1, setCookie.indexOf("Version=")); httpCookie = new HttpCookie("name", "v a l u e", null, null, -1, false, false, null, 0); - setCookie=httpCookie.getRFC2965SetCookie(); + setCookie = httpCookie.getRFC2965SetCookie(); + + httpCookie = new HttpCookie("json", "{\"services\":[\"cwa\", \"aa\"]}", null, null, -1, false, false, null, -1); + assertEquals("json=\"{\\\"services\\\":[\\\"cwa\\\", \\\"aa\\\"]}\"", httpCookie.getRFC2965SetCookie()); - httpCookie = new HttpCookie("json","{\"services\":[\"cwa\", \"aa\"]}", null, null, -1, false, false, null, -1); - assertEquals("json=\"{\\\"services\\\":[\\\"cwa\\\", \\\"aa\\\"]}\"",httpCookie.getRFC2965SetCookie()); - httpCookie = new HttpCookie("name", "value%=", null, null, -1, false, false, null, 0); - setCookie=httpCookie.getRFC2965SetCookie(); - assertEquals("name=value%=",setCookie); + setCookie = httpCookie.getRFC2965SetCookie(); + assertEquals("name=value%=", setCookie); } @Test @@ -79,18 +77,18 @@ public class HttpCookieTest { HttpCookie httpCookie; - httpCookie = new HttpCookie("null",null,null,null,-1,false,false, null, -1); - assertEquals("null=",httpCookie.getRFC6265SetCookie()); + httpCookie = new HttpCookie("null", null, null, null, -1, false, false, null, -1); + assertEquals("null=", httpCookie.getRFC6265SetCookie()); - httpCookie = new HttpCookie("minimal","value",null,null,-1,false,false, null, -1); - assertEquals("minimal=value",httpCookie.getRFC6265SetCookie()); + httpCookie = new HttpCookie("minimal", "value", null, null, -1, false, false, null, -1); + assertEquals("minimal=value", httpCookie.getRFC6265SetCookie()); //test cookies with same name, domain and path - httpCookie = new HttpCookie("everything","something","domain","path",0,true,true, null, -1); - assertEquals("everything=something; Path=path; Domain=domain; Expires=Thu, 01-Jan-1970 00:00:00 GMT; Max-Age=0; Secure; HttpOnly",httpCookie.getRFC6265SetCookie()); + httpCookie = new HttpCookie("everything", "something", "domain", "path", 0, true, true, null, -1); + assertEquals("everything=something; Path=path; Domain=domain; Expires=Thu, 01-Jan-1970 00:00:00 GMT; Max-Age=0; Secure; HttpOnly", httpCookie.getRFC6265SetCookie()); - httpCookie = new HttpCookie("everything","value","domain","path",0,true,true, null, -1); - assertEquals("everything=value; Path=path; Domain=domain; Expires=Thu, 01-Jan-1970 00:00:00 GMT; Max-Age=0; Secure; HttpOnly",httpCookie.getRFC6265SetCookie()); + httpCookie = new HttpCookie("everything", "value", "domain", "path", 0, true, true, null, -1); + assertEquals("everything=value; Path=path; Domain=domain; Expires=Thu, 01-Jan-1970 00:00:00 GMT; Max-Age=0; Secure; HttpOnly", httpCookie.getRFC6265SetCookie()); String badNameExamples[] = { "\"name\"", diff --git a/jetty-http/src/test/java/org/eclipse/jetty/http/HttpFieldTest.java b/jetty-http/src/test/java/org/eclipse/jetty/http/HttpFieldTest.java index f4135803ffd..101b3f1fa61 100644 --- a/jetty-http/src/test/java/org/eclipse/jetty/http/HttpFieldTest.java +++ b/jetty-http/src/test/java/org/eclipse/jetty/http/HttpFieldTest.java @@ -36,7 +36,7 @@ public class HttpFieldTest @Test public void testContainsSimple() throws Exception { - HttpField field = new HttpField("name","SomeValue"); + HttpField field = new HttpField("name", "SomeValue"); assertTrue(field.contains("somevalue")); assertTrue(field.contains("sOmEvAlUe")); assertTrue(field.contains("SomeValue")); @@ -48,29 +48,29 @@ public class HttpFieldTest assertFalse(field.contains("")); assertFalse(field.contains(null)); } - + @Test public void testCaseInsensitiveHashcode_KnownField() throws Exception { - HttpField fieldFoo1 = new HttpField("Cookie","foo"); - HttpField fieldFoo2 = new HttpField("cookie","foo"); - + HttpField fieldFoo1 = new HttpField("Cookie", "foo"); + HttpField fieldFoo2 = new HttpField("cookie", "foo"); + assertThat("Field hashcodes are case insensitive", fieldFoo1.hashCode(), is(fieldFoo2.hashCode())); } - + @Test public void testCaseInsensitiveHashcode_UnknownField() throws Exception { - HttpField fieldFoo1 = new HttpField("X-Foo","bar"); - HttpField fieldFoo2 = new HttpField("x-foo","bar"); - + HttpField fieldFoo1 = new HttpField("X-Foo", "bar"); + HttpField fieldFoo2 = new HttpField("x-foo", "bar"); + assertThat("Field hashcodes are case insensitive", fieldFoo1.hashCode(), is(fieldFoo2.hashCode())); } @Test public void testContainsList() throws Exception { - HttpField field = new HttpField("name",",aaa,Bbb,CCC, ddd , e e, \"\\\"f,f\\\"\", "); + HttpField field = new HttpField("name", ",aaa,Bbb,CCC, ddd , e e, \"\\\"f,f\\\"\", "); assertTrue(field.contains("aaa")); assertTrue(field.contains("bbb")); assertTrue(field.contains("ccc")); @@ -89,98 +89,94 @@ public class HttpFieldTest assertFalse(field.contains("cc")); assertFalse(field.contains(null)); } - @Test public void testQualityContainsList() throws Exception { HttpField field; - - field = new HttpField("name","yes"); + + field = new HttpField("name", "yes"); assertTrue(field.contains("yes")); assertFalse(field.contains("no")); - field = new HttpField("name",",yes,"); + field = new HttpField("name", ",yes,"); assertTrue(field.contains("yes")); assertFalse(field.contains("no")); - - field = new HttpField("name","other,yes,other"); + + field = new HttpField("name", "other,yes,other"); assertTrue(field.contains("yes")); assertFalse(field.contains("no")); - - field = new HttpField("name","other, yes ,other"); + + field = new HttpField("name", "other, yes ,other"); assertTrue(field.contains("yes")); assertFalse(field.contains("no")); - - field = new HttpField("name","other, y s ,other"); + + field = new HttpField("name", "other, y s ,other"); assertTrue(field.contains("y s")); assertFalse(field.contains("no")); - field = new HttpField("name","other, \"yes\" ,other"); - assertTrue(field.contains("yes")); - assertFalse(field.contains("no")); - - field = new HttpField("name","other, \"\\\"yes\\\"\" ,other"); - assertTrue(field.contains("\"yes\"")); - assertFalse(field.contains("no")); - - field = new HttpField("name",";no,yes,;no"); + field = new HttpField("name", "other, \"yes\" ,other"); assertTrue(field.contains("yes")); assertFalse(field.contains("no")); - field = new HttpField("name","no;q=0,yes;q=1,no; q = 0"); + field = new HttpField("name", "other, \"\\\"yes\\\"\" ,other"); + assertTrue(field.contains("\"yes\"")); + assertFalse(field.contains("no")); + + field = new HttpField("name", ";no,yes,;no"); assertTrue(field.contains("yes")); assertFalse(field.contains("no")); - - field = new HttpField("name","no;q=0.0000,yes;q=0.0001,no; q = 0.00000"); + + field = new HttpField("name", "no;q=0,yes;q=1,no; q = 0"); assertTrue(field.contains("yes")); assertFalse(field.contains("no")); - - field = new HttpField("name","no;q=0.0000,Yes;Q=0.0001,no; Q = 0.00000"); + + field = new HttpField("name", "no;q=0.0000,yes;q=0.0001,no; q = 0.00000"); + assertTrue(field.contains("yes")); + assertFalse(field.contains("no")); + + field = new HttpField("name", "no;q=0.0000,Yes;Q=0.0001,no; Q = 0.00000"); assertTrue(field.contains("yes")); assertFalse(field.contains("no")); - } - + @Test public void testValues() { - String[] values = new HttpField("name","value").getValues(); - assertEquals(1,values.length); - assertEquals("value",values[0]); - + String[] values = new HttpField("name", "value").getValues(); + assertEquals(1, values.length); + assertEquals("value", values[0]); - values = new HttpField("name","a,b,c").getValues(); - assertEquals(3,values.length); - assertEquals("a",values[0]); - assertEquals("b",values[1]); - assertEquals("c",values[2]); + values = new HttpField("name", "a,b,c").getValues(); + assertEquals(3, values.length); + assertEquals("a", values[0]); + assertEquals("b", values[1]); + assertEquals("c", values[2]); - values = new HttpField("name","a,\"x,y,z\",c").getValues(); - assertEquals(3,values.length); - assertEquals("a",values[0]); - assertEquals("x,y,z",values[1]); - assertEquals("c",values[2]); - - values = new HttpField("name","a,\"x,\\\"p,q\\\",z\",c").getValues(); - assertEquals(3,values.length); - assertEquals("a",values[0]); - assertEquals("x,\"p,q\",z",values[1]); - assertEquals("c",values[2]); - + values = new HttpField("name", "a,\"x,y,z\",c").getValues(); + assertEquals(3, values.length); + assertEquals("a", values[0]); + assertEquals("x,y,z", values[1]); + assertEquals("c", values[2]); + + values = new HttpField("name", "a,\"x,\\\"p,q\\\",z\",c").getValues(); + assertEquals(3, values.length); + assertEquals("a", values[0]); + assertEquals("x,\"p,q\",z", values[1]); + assertEquals("c", values[2]); } - + @Test public void testCachedField() { - PreEncodedHttpField field = new PreEncodedHttpField(HttpHeader.ACCEPT,"something"); + PreEncodedHttpField field = new PreEncodedHttpField(HttpHeader.ACCEPT, "something"); ByteBuffer buf = BufferUtil.allocate(256); BufferUtil.clearToFill(buf); - field.putTo(buf,HttpVersion.HTTP_1_0); - BufferUtil.flipToFlush(buf,0); - String s=BufferUtil.toString(buf); - - assertEquals("Accept: something\r\n",s); + field.putTo(buf, HttpVersion.HTTP_1_0); + BufferUtil.flipToFlush(buf, 0); + String s = BufferUtil.toString(buf); + + assertEquals("Accept: something\r\n", s); } @Test diff --git a/jetty-http/src/test/java/org/eclipse/jetty/http/HttpFieldsTest.java b/jetty-http/src/test/java/org/eclipse/jetty/http/HttpFieldsTest.java index 11e369009e5..34714b148e7 100644 --- a/jetty-http/src/test/java/org/eclipse/jetty/http/HttpFieldsTest.java +++ b/jetty-http/src/test/java/org/eclipse/jetty/http/HttpFieldsTest.java @@ -50,16 +50,16 @@ public class HttpFieldsTest header.put("name0", "value:0"); header.put("name1", "value1"); - assertEquals(2,header.size()); - assertEquals("value:0",header.get("name0")); - assertEquals("value1",header.get("name1")); + assertEquals(2, header.size()); + assertEquals("value:0", header.get("name0")); + assertEquals("value1", header.get("name1")); assertNull(header.get("name2")); - int matches=0; + int matches = 0; Enumeration e = header.getFieldNames(); while (e.hasMoreElements()) { - Object o=e.nextElement(); + Object o = e.nextElement(); if ("name0".equals(o)) matches++; if ("name1".equals(o)) @@ -83,15 +83,15 @@ public class HttpFieldsTest header.add("name1", "value:B"); header.add("name2", ""); - ByteBuffer buffer=BufferUtil.allocate(1024); + ByteBuffer buffer = BufferUtil.allocate(1024); BufferUtil.flipToFill(buffer); - HttpGenerator.putTo(header,buffer); - BufferUtil.flipToFlush(buffer,0); - String result=BufferUtil.toString(buffer); + HttpGenerator.putTo(header, buffer); + BufferUtil.flipToFlush(buffer, 0); + String result = BufferUtil.toString(buffer); - assertThat(result,Matchers.containsString("name0: value0")); - assertThat(result,Matchers.containsString("name1: value:A")); - assertThat(result,Matchers.containsString("name1: value:B")); + assertThat(result, Matchers.containsString("name0: value0")); + assertThat(result, Matchers.containsString("name1: value:A")); + assertThat(result, Matchers.containsString("name1: value:B")); } @Test @@ -102,21 +102,22 @@ public class HttpFieldsTest header.put("name0", "value0"); header.put("name1", "value1"); - assertEquals("value0",header.get("name0")); - assertEquals("value0",header.get("Name0")); - assertEquals("value1",header.get("name1")); - assertEquals("value1",header.get("Name1")); - assertEquals(null,header.get("Name2")); + assertEquals("value0", header.get("name0")); + assertEquals("value0", header.get("Name0")); + assertEquals("value1", header.get("name1")); + assertEquals("value1", header.get("Name1")); + assertEquals(null, header.get("Name2")); - assertEquals("value0",header.getField("name0").getValue()); - assertEquals("value0",header.getField("Name0").getValue()); - assertEquals("value1",header.getField("name1").getValue()); - assertEquals("value1",header.getField("Name1").getValue()); - assertEquals(null,header.getField("Name2")); + assertEquals("value0", header.getField("name0").getValue()); + assertEquals("value0", header.getField("Name0").getValue()); + assertEquals("value1", header.getField("name1").getValue()); + assertEquals("value1", header.getField("Name1").getValue()); + assertEquals(null, header.getField("Name2")); - assertEquals("value0",header.getField(0).getValue()); - assertEquals("value1",header.getField(1).getValue()); - assertThrows(NoSuchElementException.class, ()->{ + assertEquals("value0", header.getField(0).getValue()); + assertEquals("value1", header.getField(1).getValue()); + assertThrows(NoSuchElementException.class, () -> + { header.getField(2); }); } @@ -129,14 +130,14 @@ public class HttpFieldsTest header.put("Connection", "value0"); header.put(HttpHeader.ACCEPT, "value1"); - assertEquals("value0",header.get(HttpHeader.CONNECTION)); - assertEquals("value1",header.get(HttpHeader.ACCEPT)); + assertEquals("value0", header.get(HttpHeader.CONNECTION)); + assertEquals("value1", header.get(HttpHeader.ACCEPT)); - assertEquals("value0",header.getField(HttpHeader.CONNECTION).getValue()); - assertEquals("value1",header.getField(HttpHeader.ACCEPT).getValue()); + assertEquals("value0", header.getField(HttpHeader.CONNECTION).getValue()); + assertEquals("value1", header.getField(HttpHeader.ACCEPT).getValue()); - assertEquals(null,header.getField(HttpHeader.AGE)); - assertEquals(null,header.get(HttpHeader.AGE)); + assertEquals(null, header.getField(HttpHeader.AGE)); + assertEquals(null, header.get(HttpHeader.AGE)); } @Test @@ -150,12 +151,12 @@ public class HttpFieldsTest ByteBuffer buffer = BufferUtil.allocate(1024); BufferUtil.flipToFill(buffer); - HttpGenerator.putTo(header,buffer); - BufferUtil.flipToFlush(buffer,0); + HttpGenerator.putTo(header, buffer); + BufferUtil.flipToFlush(buffer, 0); String out = BufferUtil.toString(buffer); - assertThat(out,containsString("name0: value 0")); - assertThat(out,containsString("name??1: value1")); - assertThat(out,containsString("name?2: value: 2")); + assertThat(out, containsString("name0: value 0")); + assertThat(out, containsString("name??1: value1")); + assertThat(out, containsString("name?2: value: 2")); } @Test @@ -169,13 +170,13 @@ public class HttpFieldsTest ByteBuffer buffer = BufferUtil.allocate(1024); BufferUtil.flipToFill(buffer); - HttpGenerator.putTo(header,buffer); - BufferUtil.flipToFlush(buffer,0); + HttpGenerator.putTo(header, buffer); + BufferUtil.flipToFlush(buffer, 0); String out = BufferUtil.toString(buffer).toLowerCase(Locale.ENGLISH); - assertThat(out,Matchers.containsString((HttpHeader.CONNECTION+": "+HttpHeaderValue.KEEP_ALIVE).toLowerCase(Locale.ENGLISH))); - assertThat(out,Matchers.containsString((HttpHeader.TRANSFER_ENCODING+": "+HttpHeaderValue.CHUNKED).toLowerCase(Locale.ENGLISH))); - assertThat(out,Matchers.containsString((HttpHeader.CONTENT_ENCODING+": "+HttpHeaderValue.GZIP).toLowerCase(Locale.ENGLISH))); + assertThat(out, Matchers.containsString((HttpHeader.CONNECTION + ": " + HttpHeaderValue.KEEP_ALIVE).toLowerCase(Locale.ENGLISH))); + assertThat(out, Matchers.containsString((HttpHeader.TRANSFER_ENCODING + ": " + HttpHeaderValue.CHUNKED).toLowerCase(Locale.ENGLISH))); + assertThat(out, Matchers.containsString((HttpHeader.CONTENT_ENCODING + ": " + HttpHeaderValue.GZIP).toLowerCase(Locale.ENGLISH))); } @Test @@ -187,22 +188,22 @@ public class HttpFieldsTest header.put("name1", "xxxxxx"); header.put("name2", "value2"); - assertEquals("value0",header.get("name0")); - assertEquals("xxxxxx",header.get("name1")); - assertEquals("value2",header.get("name2")); + assertEquals("value0", header.get("name0")); + assertEquals("xxxxxx", header.get("name1")); + assertEquals("value2", header.get("name2")); header.put("name1", "value1"); - assertEquals("value0",header.get("name0")); - assertEquals("value1",header.get("name1")); - assertEquals("value2",header.get("name2")); + assertEquals("value0", header.get("name0")); + assertEquals("value1", header.get("name1")); + assertEquals("value2", header.get("name2")); assertNull(header.get("name3")); - int matches=0; + int matches = 0; Enumeration e = header.getFieldNames(); while (e.hasMoreElements()) { - String o=e.nextElement(); + String o = e.nextElement(); if ("name0".equals(o)) matches++; if ("name1".equals(o)) @@ -212,7 +213,6 @@ public class HttpFieldsTest } assertEquals(3, matches); - e = header.getValues("name1"); assertEquals(true, e.hasMoreElements()); assertEquals(e.nextElement(), "value1"); @@ -228,22 +228,22 @@ public class HttpFieldsTest header.put("name1", "value1"); header.put("name2", "value2"); - assertEquals("value0",header.get("name0")); - assertEquals("value1",header.get("name1")); - assertEquals("value2",header.get("name2")); + assertEquals("value0", header.get("name0")); + assertEquals("value1", header.get("name1")); + assertEquals("value2", header.get("name2")); header.remove("name1"); - assertEquals("value0",header.get("name0")); + assertEquals("value0", header.get("name0")); assertNull(header.get("name1")); - assertEquals("value2",header.get("name2")); + assertEquals("value2", header.get("name2")); assertNull(header.get("name3")); - int matches=0; + int matches = 0; Enumeration e = header.getFieldNames(); while (e.hasMoreElements()) { - Object o=e.nextElement(); + Object o = e.nextElement(); if ("name0".equals(o)) matches++; if ("name1".equals(o)) @@ -266,22 +266,22 @@ public class HttpFieldsTest fields.add("name1", "valueA"); fields.add("name2", "value2"); - assertEquals("value0",fields.get("name0")); - assertEquals("valueA",fields.get("name1")); - assertEquals("value2",fields.get("name2")); + assertEquals("value0", fields.get("name0")); + assertEquals("valueA", fields.get("name1")); + assertEquals("value2", fields.get("name2")); fields.add("name1", "valueB"); - assertEquals("value0",fields.get("name0")); - assertEquals("valueA",fields.get("name1")); - assertEquals("value2",fields.get("name2")); + assertEquals("value0", fields.get("name0")); + assertEquals("valueA", fields.get("name1")); + assertEquals("value2", fields.get("name2")); assertNull(fields.get("name3")); - int matches=0; + int matches = 0; Enumeration e = fields.getFieldNames(); while (e.hasMoreElements()) { - Object o=e.nextElement(); + Object o = e.nextElement(); if ("name0".equals(o)) matches++; if ("name1".equals(o)) @@ -306,15 +306,15 @@ public class HttpFieldsTest PreEncodedHttpField known = new PreEncodedHttpField(HttpHeader.CONNECTION, HttpHeaderValue.CLOSE.asString()); BufferUtil.clearToFill(buffer); - known.putTo(buffer,HttpVersion.HTTP_1_1); - BufferUtil.flipToFlush(buffer,0); - assertThat(BufferUtil.toString(buffer),is("Connection: close\r\n")); + known.putTo(buffer, HttpVersion.HTTP_1_1); + BufferUtil.flipToFlush(buffer, 0); + assertThat(BufferUtil.toString(buffer), is("Connection: close\r\n")); PreEncodedHttpField unknown = new PreEncodedHttpField(null, "Header", "Value"); BufferUtil.clearToFill(buffer); - unknown.putTo(buffer,HttpVersion.HTTP_1_1); - BufferUtil.flipToFlush(buffer,0); - assertThat(BufferUtil.toString(buffer),is("Header: Value\r\n")); + unknown.putTo(buffer, HttpVersion.HTTP_1_1); + BufferUtil.flipToFlush(buffer, 0); + assertThat(BufferUtil.toString(buffer), is("Header: Value\r\n")); } @Test @@ -356,7 +356,7 @@ public class HttpFieldsTest assertEquals(e.nextElement(), "value0C,value0D"); assertEquals(false, e.hasMoreElements()); - e = Collections.enumeration(fields.getCSV("name0",false)); + e = Collections.enumeration(fields.getCSV("name0", false)); assertEquals(true, e.hasMoreElements()); assertEquals(e.nextElement(), "value0A"); assertEquals(true, e.hasMoreElements()); @@ -367,7 +367,7 @@ public class HttpFieldsTest assertEquals(e.nextElement(), "value0D"); assertEquals(false, e.hasMoreElements()); - e = Collections.enumeration(fields.getCSV("name1",false)); + e = Collections.enumeration(fields.getCSV("name1", false)); assertEquals(true, e.hasMoreElements()); assertEquals(e.nextElement(), "value1A"); assertEquals(true, e.hasMoreElements()); @@ -396,7 +396,7 @@ public class HttpFieldsTest assertEquals(e.nextElement(), "value0C,value0D"); assertEquals(false, e.hasMoreElements()); - e = Collections.enumeration(fields.getCSV("name0",false)); + e = Collections.enumeration(fields.getCSV("name0", false)); assertEquals(true, e.hasMoreElements()); assertEquals(e.nextElement(), "value0A"); assertEquals(true, e.hasMoreElements()); @@ -407,7 +407,7 @@ public class HttpFieldsTest assertEquals(e.nextElement(), "value0D"); assertEquals(false, e.hasMoreElements()); - e = Collections.enumeration(fields.getCSV("name1",false)); + e = Collections.enumeration(fields.getCSV("name1", false)); assertEquals(true, e.hasMoreElements()); assertEquals(e.nextElement(), "value1A"); assertEquals(true, e.hasMoreElements()); @@ -431,16 +431,16 @@ public class HttpFieldsTest fields.add("name", "three"); fields.add("name", "four, I V"); - List list = fields.getCSV("name",false); + List list = fields.getCSV("name", false); assertEquals(HttpFields.valueParameters(list.get(0), null), "zero"); assertEquals(HttpFields.valueParameters(list.get(1), null), "one"); assertEquals(HttpFields.valueParameters(list.get(2), null), "1 + 1"); assertEquals(HttpFields.valueParameters(list.get(3), null), "three"); assertEquals(HttpFields.valueParameters(list.get(4), null), "four"); assertEquals(HttpFields.valueParameters(list.get(5), null), "I V"); - - fields.addCSV("name","six"); - list = fields.getCSV("name",false); + + fields.addCSV("name", "six"); + list = fields.getCSV("name", false); assertEquals(HttpFields.valueParameters(list.get(0), null), "zero"); assertEquals(HttpFields.valueParameters(list.get(1), null), "one"); assertEquals(HttpFields.valueParameters(list.get(2), null), "1 + 1"); @@ -448,9 +448,9 @@ public class HttpFieldsTest assertEquals(HttpFields.valueParameters(list.get(4), null), "four"); assertEquals(HttpFields.valueParameters(list.get(5), null), "I V"); assertEquals(HttpFields.valueParameters(list.get(6), null), "six"); - - fields.addCSV("name","1 + 1","7","zero"); - list = fields.getCSV("name",false); + + fields.addCSV("name", "1 + 1", "7", "zero"); + list = fields.getCSV("name", false); assertEquals(HttpFields.valueParameters(list.get(0), null), "zero"); assertEquals(HttpFields.valueParameters(list.get(1), null), "one"); assertEquals(HttpFields.valueParameters(list.get(2), null), "1 + 1"); @@ -460,7 +460,7 @@ public class HttpFieldsTest assertEquals(HttpFields.valueParameters(list.get(6), null), "six"); assertEquals(HttpFields.valueParameters(list.get(7), null), "7"); } - + @Test public void testGetQualityCSV() throws Exception { @@ -474,7 +474,6 @@ public class HttpFieldsTest fields.add("name", "three;x=y;q=0.2;a=b,two;q=0.3"); fields.add("name", "first;"); - List list = fields.getQualityCSV("name"); assertEquals(HttpFields.valueParameters(list.get(0), null), "first"); assertEquals(HttpFields.valueParameters(list.get(1), null), "zero"); @@ -483,7 +482,7 @@ public class HttpFieldsTest assertEquals(HttpFields.valueParameters(list.get(4), null), "three"); assertEquals(HttpFields.valueParameters(list.get(5), null), "four"); } - + @Test public void testGetQualityCSVHeader() throws Exception { @@ -497,7 +496,6 @@ public class HttpFieldsTest fields.add("Accept", "three;x=y;q=0.2;a=b,two;q=0.3"); fields.add("Accept", "first;"); - List list = fields.getQualityCSV(HttpHeader.ACCEPT); assertEquals(HttpFields.valueParameters(list.get(0), null), "first"); assertEquals(HttpFields.valueParameters(list.get(1), null), "zero"); @@ -507,7 +505,6 @@ public class HttpFieldsTest assertEquals(HttpFields.valueParameters(list.get(5), null), "four"); } - @Test public void testDateFields() throws Exception { @@ -526,28 +523,28 @@ public class HttpFieldsTest long d3 = fields.getDateField("D3"); long d4 = fields.getDateField("D4"); long d5 = fields.getDateField("D5"); - assertTrue(d0!=-1); - assertTrue(d1>0); - assertTrue(d2>0); - assertEquals(d1,d2); - assertEquals(d2,d3); - assertEquals(d3+2000,d4); - assertEquals(951825600000L,d5); + assertTrue(d0 != -1); + assertTrue(d1 > 0); + assertTrue(d2 > 0); + assertEquals(d1, d2); + assertEquals(d2, d3); + assertEquals(d3 + 2000, d4); + assertEquals(951825600000L, d5); d1 = fields.getDateField("D1"); d2 = fields.getDateField("D2"); d3 = fields.getDateField("D3"); d4 = fields.getDateField("D4"); d5 = fields.getDateField("D5"); - assertTrue(d1>0); - assertTrue(d2>0); - assertEquals(d1,d2); - assertEquals(d2,d3); - assertEquals(d3+2000,d4); - assertEquals(951825600000L,d5); + assertTrue(d1 > 0); + assertTrue(d2 > 0); + assertEquals(d1, d2); + assertEquals(d2, d3); + assertEquals(d3 + 2000, d4); + assertEquals(951825600000L, d5); - fields.putDateField("D2",d1); - assertEquals("Fri, 31 Dec 1999 23:59:59 GMT",fields.get("D2")); + fields.putDateField("D2", d1); + assertEquals("Fri, 31 Dec 1999 23:59:59 GMT", fields.get("D2")); } @Test @@ -555,17 +552,17 @@ public class HttpFieldsTest { HttpFields fields = new HttpFields(); - fields.putDateField("Dzero",0); - assertEquals("Thu, 01 Jan 1970 00:00:00 GMT",fields.get("Dzero")); + fields.putDateField("Dzero", 0); + assertEquals("Thu, 01 Jan 1970 00:00:00 GMT", fields.get("Dzero")); - fields.putDateField("Dminus",-1); - assertEquals("Wed, 31 Dec 1969 23:59:59 GMT",fields.get("Dminus")); + fields.putDateField("Dminus", -1); + assertEquals("Wed, 31 Dec 1969 23:59:59 GMT", fields.get("Dminus")); - fields.putDateField("Dminus",-1000); - assertEquals("Wed, 31 Dec 1969 23:59:59 GMT",fields.get("Dminus")); + fields.putDateField("Dminus", -1000); + assertEquals("Wed, 31 Dec 1969 23:59:59 GMT", fields.get("Dminus")); - fields.putDateField("Dancient",Long.MIN_VALUE); - assertEquals("Sun, 02 Dec 55 16:47:04 GMT",fields.get("Dancient")); + fields.putDateField("Dancient", Long.MIN_VALUE); + assertEquals("Sun, 02 Dec 55 16:47:04 GMT", fields.get("Dancient")); } @Test @@ -580,54 +577,56 @@ public class HttpFieldsTest header.put("N1", " - "); header.put("N2", "xx"); - long i1=header.getLongField("I1"); + long i1 = header.getLongField("I1"); try { header.getLongField("I2"); assertTrue(false); } - catch(NumberFormatException e) + catch (NumberFormatException e) { assertTrue(true); } - long i3=header.getLongField("I3"); + long i3 = header.getLongField("I3"); try { header.getLongField("I4"); assertTrue(false); } - catch(NumberFormatException e) + catch (NumberFormatException e) { assertTrue(true); } - try{ + try + { header.getLongField("N1"); assertTrue(false); } - catch(NumberFormatException e) + catch (NumberFormatException e) { assertTrue(true); } - try{ + try + { header.getLongField("N2"); assertTrue(false); } - catch(NumberFormatException e) + catch (NumberFormatException e) { assertTrue(true); } - assertEquals(42,i1); - assertEquals(-44,i3); + assertEquals(42, i1); + assertEquals(-44, i3); header.putLongField("I5", 46); - header.putLongField("I6",-47); - assertEquals("46",header.get("I5")); - assertEquals("-47",header.get("I6")); + header.putLongField("I6", -47); + assertEquals("46", header.get("I5")); + assertEquals("-47", header.get("I6")); } @Test @@ -648,87 +647,84 @@ public class HttpFieldsTest header.add("n8", "abc , def;q=0 , hig"); header.add(HttpHeader.ACCEPT, "abc , def;q=0 , hig"); - for (int i=0;i<8;i++) + for (int i = 0; i < 8; i++) { - assertTrue(header.containsKey("n"+i)); - assertTrue(header.containsKey("N"+i)); - assertFalse(header.contains("n"+i,"xyz"),""+i); - assertEquals(i>=4,header.contains("n"+i, "def"), ""+i); + assertTrue(header.containsKey("n" + i)); + assertTrue(header.containsKey("N" + i)); + assertFalse(header.contains("n" + i, "xyz"), "" + i); + assertEquals(i >= 4, header.contains("n" + i, "def"), "" + i); } - - assertTrue(header.contains(new HttpField("N5","def"))); - assertTrue(header.contains(new HttpField("accept","abc"))); - assertTrue(header.contains(HttpHeader.ACCEPT,"abc")); - assertFalse(header.contains(new HttpField("N5","xyz"))); - assertFalse(header.contains(new HttpField("N8","def"))); - assertFalse(header.contains(HttpHeader.ACCEPT,"def")); - assertFalse(header.contains(HttpHeader.AGE,"abc")); + assertTrue(header.contains(new HttpField("N5", "def"))); + assertTrue(header.contains(new HttpField("accept", "abc"))); + assertTrue(header.contains(HttpHeader.ACCEPT, "abc")); + assertFalse(header.contains(new HttpField("N5", "xyz"))); + assertFalse(header.contains(new HttpField("N8", "def"))); + assertFalse(header.contains(HttpHeader.ACCEPT, "def")); + assertFalse(header.contains(HttpHeader.AGE, "abc")); assertFalse(header.containsKey("n11")); } - @Test public void testIteration() throws Exception { HttpFields header = new HttpFields(); Iterator i = header.iterator(); - assertThat(i.hasNext(),is(false)); + assertThat(i.hasNext(), is(false)); header.put("name1", "valueA"); header.put("name2", "valueB"); header.add("name3", "valueC"); i = header.iterator(); - assertThat(i.hasNext(),is(true)); - assertThat(i.next().getName(),is("name1")); - assertThat(i.next().getName(),is("name2")); + assertThat(i.hasNext(), is(true)); + assertThat(i.next().getName(), is("name1")); + assertThat(i.next().getName(), is("name2")); i.remove(); - assertThat(i.next().getName(),is("name3")); - assertThat(i.hasNext(),is(false)); - + assertThat(i.next().getName(), is("name3")); + assertThat(i.hasNext(), is(false)); + i = header.iterator(); - assertThat(i.hasNext(),is(true)); - assertThat(i.next().getName(),is("name1")); - assertThat(i.next().getName(),is("name3")); - assertThat(i.hasNext(),is(false)); - - + assertThat(i.hasNext(), is(true)); + assertThat(i.next().getName(), is("name1")); + assertThat(i.next().getName(), is("name3")); + assertThat(i.hasNext(), is(false)); + ListIterator l = header.listIterator(); - assertThat(l.hasNext(),is(true)); - l.add(new HttpField("name0","value")); - assertThat(l.hasNext(),is(true)); - assertThat(l.next().getName(),is("name1")); - l.set(new HttpField("NAME1","value")); - assertThat(l.hasNext(),is(true)); - assertThat(l.hasPrevious(),is(true)); - assertThat(l.previous().getName(),is("NAME1")); - assertThat(l.hasNext(),is(true)); - assertThat(l.hasPrevious(),is(true)); - assertThat(l.previous().getName(),is("name0")); - assertThat(l.hasNext(),is(true)); - assertThat(l.hasPrevious(),is(false)); - assertThat(l.next().getName(),is("name0")); - assertThat(l.hasNext(),is(true)); - assertThat(l.hasPrevious(),is(true)); - assertThat(l.next().getName(),is("NAME1")); - l.add(new HttpField("name2","value")); - assertThat(l.next().getName(),is("name3")); - assertThat(l.hasNext(),is(false)); - assertThat(l.hasPrevious(),is(true)); - l.add(new HttpField("name4","value")); - assertThat(l.hasNext(),is(false)); - assertThat(l.hasPrevious(),is(true)); - assertThat(l.previous().getName(),is("name4")); - + assertThat(l.hasNext(), is(true)); + l.add(new HttpField("name0", "value")); + assertThat(l.hasNext(), is(true)); + assertThat(l.next().getName(), is("name1")); + l.set(new HttpField("NAME1", "value")); + assertThat(l.hasNext(), is(true)); + assertThat(l.hasPrevious(), is(true)); + assertThat(l.previous().getName(), is("NAME1")); + assertThat(l.hasNext(), is(true)); + assertThat(l.hasPrevious(), is(true)); + assertThat(l.previous().getName(), is("name0")); + assertThat(l.hasNext(), is(true)); + assertThat(l.hasPrevious(), is(false)); + assertThat(l.next().getName(), is("name0")); + assertThat(l.hasNext(), is(true)); + assertThat(l.hasPrevious(), is(true)); + assertThat(l.next().getName(), is("NAME1")); + l.add(new HttpField("name2", "value")); + assertThat(l.next().getName(), is("name3")); + assertThat(l.hasNext(), is(false)); + assertThat(l.hasPrevious(), is(true)); + l.add(new HttpField("name4", "value")); + assertThat(l.hasNext(), is(false)); + assertThat(l.hasPrevious(), is(true)); + assertThat(l.previous().getName(), is("name4")); + i = header.iterator(); - assertThat(i.hasNext(),is(true)); - assertThat(i.next().getName(),is("name0")); - assertThat(i.next().getName(),is("NAME1")); - assertThat(i.next().getName(),is("name2")); - assertThat(i.next().getName(),is("name3")); - assertThat(i.next().getName(),is("name4")); - assertThat(i.hasNext(),is(false)); + assertThat(i.hasNext(), is(true)); + assertThat(i.next().getName(), is("name0")); + assertThat(i.next().getName(), is("NAME1")); + assertThat(i.next().getName(), is("name2")); + assertThat(i.next().getName(), is("name3")); + assertThat(i.next().getName(), is("name4")); + assertThat(i.hasNext(), is(false)); } } diff --git a/jetty-http/src/test/java/org/eclipse/jetty/http/HttpGeneratorClientTest.java b/jetty-http/src/test/java/org/eclipse/jetty/http/HttpGeneratorClientTest.java index 2af4efc02d6..01d965be55d 100644 --- a/jetty-http/src/test/java/org/eclipse/jetty/http/HttpGeneratorClientTest.java +++ b/jetty-http/src/test/java/org/eclipse/jetty/http/HttpGeneratorClientTest.java @@ -18,62 +18,61 @@ package org.eclipse.jetty.http; -import static org.hamcrest.MatcherAssert.assertThat; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertTrue; - import java.nio.ByteBuffer; import org.eclipse.jetty.util.BufferUtil; import org.hamcrest.Matchers; - import org.junit.jupiter.api.Test; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + public class HttpGeneratorClientTest { - public final static String[] connect={null,"keep-alive","close"}; + public static final String[] connect = {null, "keep-alive", "close"}; class Info extends MetaData.Request { - Info(String method,String uri) + Info(String method, String uri) { - super(method,new HttpURI(uri),HttpVersion.HTTP_1_1,new HttpFields(),-1); + super(method, new HttpURI(uri), HttpVersion.HTTP_1_1, new HttpFields(), -1); } - public Info(String method,String uri, int contentLength) + public Info(String method, String uri, int contentLength) { - super(method,new HttpURI(uri),HttpVersion.HTTP_1_1,new HttpFields(),contentLength); + super(method, new HttpURI(uri), HttpVersion.HTTP_1_1, new HttpFields(), contentLength); } } @Test public void testGETRequestNoContent() throws Exception { - ByteBuffer header=BufferUtil.allocate(2048); + ByteBuffer header = BufferUtil.allocate(2048); HttpGenerator gen = new HttpGenerator(); HttpGenerator.Result - result=gen.generateRequest(null,null,null,null, true); + result = gen.generateRequest(null, null, null, null, true); assertEquals(HttpGenerator.Result.NEED_INFO, result); assertEquals(HttpGenerator.State.START, gen.getState()); - Info info = new Info("GET","/index.html"); - info.getFields().add("Host","something"); - info.getFields().add("User-Agent","test"); + Info info = new Info("GET", "/index.html"); + info.getFields().add("Host", "something"); + info.getFields().add("User-Agent", "test"); assertTrue(!gen.isChunking()); - result=gen.generateRequest(info,null,null,null, true); + result = gen.generateRequest(info, null, null, null, true); assertEquals(HttpGenerator.Result.NEED_HEADER, result); assertEquals(HttpGenerator.State.START, gen.getState()); - result=gen.generateRequest(info,header,null,null, true); + result = gen.generateRequest(info, header, null, null, true); assertEquals(HttpGenerator.Result.FLUSH, result); assertEquals(HttpGenerator.State.COMPLETING, gen.getState()); assertTrue(!gen.isChunking()); String out = BufferUtil.toString(header); BufferUtil.clear(header); - result=gen.generateResponse(null,false,null,null, null, false); + result = gen.generateResponse(null, false, null, null, null, false); assertEquals(HttpGenerator.Result.DONE, result); assertEquals(HttpGenerator.State.END, gen.getState()); assertTrue(!gen.isChunking()); @@ -86,32 +85,32 @@ public class HttpGeneratorClientTest @Test public void testEmptyHeaders() throws Exception { - ByteBuffer header=BufferUtil.allocate(2048); + ByteBuffer header = BufferUtil.allocate(2048); HttpGenerator gen = new HttpGenerator(); HttpGenerator.Result - result=gen.generateRequest(null,null,null,null, true); + result = gen.generateRequest(null, null, null, null, true); assertEquals(HttpGenerator.Result.NEED_INFO, result); assertEquals(HttpGenerator.State.START, gen.getState()); - Info info = new Info("GET","/index.html"); - info.getFields().add("Host","something"); - info.getFields().add("Null",null); - info.getFields().add("Empty",""); + Info info = new Info("GET", "/index.html"); + info.getFields().add("Host", "something"); + info.getFields().add("Null", null); + info.getFields().add("Empty", ""); assertTrue(!gen.isChunking()); - result=gen.generateRequest(info,null,null,null, true); + result = gen.generateRequest(info, null, null, null, true); assertEquals(HttpGenerator.Result.NEED_HEADER, result); assertEquals(HttpGenerator.State.START, gen.getState()); - result=gen.generateRequest(info,header,null,null, true); + result = gen.generateRequest(info, header, null, null, true); assertEquals(HttpGenerator.Result.FLUSH, result); assertEquals(HttpGenerator.State.COMPLETING, gen.getState()); assertTrue(!gen.isChunking()); String out = BufferUtil.toString(header); BufferUtil.clear(header); - result=gen.generateResponse(null,false,null,null, null, false); + result = gen.generateResponse(null, false, null, null, null, false); assertEquals(HttpGenerator.Result.DONE, result); assertEquals(HttpGenerator.State.END, gen.getState()); assertTrue(!gen.isChunking()); @@ -122,36 +121,35 @@ public class HttpGeneratorClientTest assertThat(out, Matchers.containsString("Empty:")); assertThat(out, Matchers.not(Matchers.containsString("Null:"))); } - - + @Test public void testPOSTRequestNoContent() throws Exception { - ByteBuffer header=BufferUtil.allocate(2048); + ByteBuffer header = BufferUtil.allocate(2048); HttpGenerator gen = new HttpGenerator(); HttpGenerator.Result - result=gen.generateRequest(null,null,null,null, true); + result = gen.generateRequest(null, null, null, null, true); assertEquals(HttpGenerator.Result.NEED_INFO, result); assertEquals(HttpGenerator.State.START, gen.getState()); - Info info = new Info("POST","/index.html"); - info.getFields().add("Host","something"); - info.getFields().add("User-Agent","test"); + Info info = new Info("POST", "/index.html"); + info.getFields().add("Host", "something"); + info.getFields().add("User-Agent", "test"); assertTrue(!gen.isChunking()); - result=gen.generateRequest(info,null,null,null, true); + result = gen.generateRequest(info, null, null, null, true); assertEquals(HttpGenerator.Result.NEED_HEADER, result); assertEquals(HttpGenerator.State.START, gen.getState()); - result=gen.generateRequest(info,header,null,null, true); + result = gen.generateRequest(info, header, null, null, true); assertEquals(HttpGenerator.Result.FLUSH, result); assertEquals(HttpGenerator.State.COMPLETING, gen.getState()); assertTrue(!gen.isChunking()); String out = BufferUtil.toString(header); BufferUtil.clear(header); - result=gen.generateResponse(null,false,null,null, null, false); + result = gen.generateResponse(null, false, null, null, null, false); assertEquals(HttpGenerator.Result.DONE, result); assertEquals(HttpGenerator.State.END, gen.getState()); assertTrue(!gen.isChunking()); @@ -165,38 +163,37 @@ public class HttpGeneratorClientTest public void testRequestWithContent() throws Exception { String out; - ByteBuffer header=BufferUtil.allocate(4096); - ByteBuffer content0=BufferUtil.toBuffer("Hello World. The quick brown fox jumped over the lazy dog."); + ByteBuffer header = BufferUtil.allocate(4096); + ByteBuffer content0 = BufferUtil.toBuffer("Hello World. The quick brown fox jumped over the lazy dog."); HttpGenerator gen = new HttpGenerator(); HttpGenerator.Result - result=gen.generateRequest(null,null,null,content0, true); + result = gen.generateRequest(null, null, null, content0, true); assertEquals(HttpGenerator.Result.NEED_INFO, result); assertEquals(HttpGenerator.State.START, gen.getState()); - Info info = new Info("POST","/index.html"); - info.getFields().add("Host","something"); - info.getFields().add("User-Agent","test"); + Info info = new Info("POST", "/index.html"); + info.getFields().add("Host", "something"); + info.getFields().add("User-Agent", "test"); - result=gen.generateRequest(info,null,null,content0, true); + result = gen.generateRequest(info, null, null, content0, true); assertEquals(HttpGenerator.Result.NEED_HEADER, result); assertEquals(HttpGenerator.State.START, gen.getState()); - result=gen.generateRequest(info,header,null,content0, true); + result = gen.generateRequest(info, header, null, content0, true); assertEquals(HttpGenerator.Result.FLUSH, result); assertEquals(HttpGenerator.State.COMPLETING, gen.getState()); assertTrue(!gen.isChunking()); out = BufferUtil.toString(header); BufferUtil.clear(header); - out+=BufferUtil.toString(content0); + out += BufferUtil.toString(content0); BufferUtil.clear(content0); - result=gen.generateResponse(null,false,null,null, null, false); + result = gen.generateResponse(null, false, null, null, null, false); assertEquals(HttpGenerator.Result.DONE, result); assertEquals(HttpGenerator.State.END, gen.getState()); assertTrue(!gen.isChunking()); - assertThat(out, Matchers.containsString("POST /index.html HTTP/1.1")); assertThat(out, Matchers.containsString("Host: something")); assertThat(out, Matchers.containsString("Content-Length: 58")); @@ -209,60 +206,60 @@ public class HttpGeneratorClientTest public void testRequestWithChunkedContent() throws Exception { String out; - ByteBuffer header=BufferUtil.allocate(4096); - ByteBuffer chunk=BufferUtil.allocate(HttpGenerator.CHUNK_SIZE); - ByteBuffer content0=BufferUtil.toBuffer("Hello World. "); - ByteBuffer content1=BufferUtil.toBuffer("The quick brown fox jumped over the lazy dog."); + ByteBuffer header = BufferUtil.allocate(4096); + ByteBuffer chunk = BufferUtil.allocate(HttpGenerator.CHUNK_SIZE); + ByteBuffer content0 = BufferUtil.toBuffer("Hello World. "); + ByteBuffer content1 = BufferUtil.toBuffer("The quick brown fox jumped over the lazy dog."); HttpGenerator gen = new HttpGenerator(); HttpGenerator.Result - result=gen.generateRequest(null,null,null,content0, false); + result = gen.generateRequest(null, null, null, content0, false); assertEquals(HttpGenerator.Result.NEED_INFO, result); assertEquals(HttpGenerator.State.START, gen.getState()); - Info info = new Info("POST","/index.html"); - info.getFields().add("Host","something"); - info.getFields().add("User-Agent","test"); + Info info = new Info("POST", "/index.html"); + info.getFields().add("Host", "something"); + info.getFields().add("User-Agent", "test"); - result=gen.generateRequest(info,null,null,content0, false); + result = gen.generateRequest(info, null, null, content0, false); assertEquals(HttpGenerator.Result.NEED_HEADER, result); assertEquals(HttpGenerator.State.START, gen.getState()); - result=gen.generateRequest(info,header,null,content0, false); + result = gen.generateRequest(info, header, null, content0, false); assertEquals(HttpGenerator.Result.FLUSH, result); assertEquals(HttpGenerator.State.COMMITTED, gen.getState()); assertTrue(gen.isChunking()); out = BufferUtil.toString(header); BufferUtil.clear(header); - out+=BufferUtil.toString(content0); + out += BufferUtil.toString(content0); BufferUtil.clear(content0); - result=gen.generateRequest(null,header,null,content1, false); + result = gen.generateRequest(null, header, null, content1, false); assertEquals(HttpGenerator.Result.NEED_CHUNK, result); assertEquals(HttpGenerator.State.COMMITTED, gen.getState()); - result=gen.generateRequest(null,null,chunk,content1, false); + result = gen.generateRequest(null, null, chunk, content1, false); assertEquals(HttpGenerator.Result.FLUSH, result); assertEquals(HttpGenerator.State.COMMITTED, gen.getState()); assertTrue(gen.isChunking()); - out+=BufferUtil.toString(chunk); + out += BufferUtil.toString(chunk); BufferUtil.clear(chunk); - out+=BufferUtil.toString(content1); + out += BufferUtil.toString(content1); BufferUtil.clear(content1); - result=gen.generateResponse(null,false,null,chunk, null, true); + result = gen.generateResponse(null, false, null, chunk, null, true); assertEquals(HttpGenerator.Result.CONTINUE, result); assertEquals(HttpGenerator.State.COMPLETING, gen.getState()); assertTrue(gen.isChunking()); - result=gen.generateResponse(null,false,null,chunk, null, true); + result = gen.generateResponse(null, false, null, chunk, null, true); assertEquals(HttpGenerator.Result.FLUSH, result); assertEquals(HttpGenerator.State.COMPLETING, gen.getState()); - out+=BufferUtil.toString(chunk); + out += BufferUtil.toString(chunk); BufferUtil.clear(chunk); assertTrue(!gen.isChunking()); - result=gen.generateResponse(null,false,null,chunk, null, true); + result = gen.generateResponse(null, false, null, chunk, null, true); assertEquals(HttpGenerator.Result.DONE, result); assertEquals(HttpGenerator.State.END, gen.getState()); @@ -274,57 +271,56 @@ public class HttpGeneratorClientTest assertThat(out, Matchers.containsString("\r\n0\r\n\r\n")); assertEquals(58, gen.getContentPrepared()); - } @Test public void testRequestWithKnownContent() throws Exception { String out; - ByteBuffer header=BufferUtil.allocate(4096); - ByteBuffer chunk=BufferUtil.allocate(HttpGenerator.CHUNK_SIZE); - ByteBuffer content0=BufferUtil.toBuffer("Hello World. "); - ByteBuffer content1=BufferUtil.toBuffer("The quick brown fox jumped over the lazy dog."); + ByteBuffer header = BufferUtil.allocate(4096); + ByteBuffer chunk = BufferUtil.allocate(HttpGenerator.CHUNK_SIZE); + ByteBuffer content0 = BufferUtil.toBuffer("Hello World. "); + ByteBuffer content1 = BufferUtil.toBuffer("The quick brown fox jumped over the lazy dog."); HttpGenerator gen = new HttpGenerator(); HttpGenerator.Result - result=gen.generateRequest(null,null,null,content0, false); + result = gen.generateRequest(null, null, null, content0, false); assertEquals(HttpGenerator.Result.NEED_INFO, result); assertEquals(HttpGenerator.State.START, gen.getState()); - Info info = new Info("POST","/index.html",58); - info.getFields().add("Host","something"); - info.getFields().add("User-Agent","test"); + Info info = new Info("POST", "/index.html", 58); + info.getFields().add("Host", "something"); + info.getFields().add("User-Agent", "test"); - result=gen.generateRequest(info,null,null,content0, false); + result = gen.generateRequest(info, null, null, content0, false); assertEquals(HttpGenerator.Result.NEED_HEADER, result); assertEquals(HttpGenerator.State.START, gen.getState()); - result=gen.generateRequest(info,header,null,content0, false); + result = gen.generateRequest(info, header, null, content0, false); assertEquals(HttpGenerator.Result.FLUSH, result); assertEquals(HttpGenerator.State.COMMITTED, gen.getState()); assertTrue(!gen.isChunking()); out = BufferUtil.toString(header); BufferUtil.clear(header); - out+=BufferUtil.toString(content0); + out += BufferUtil.toString(content0); BufferUtil.clear(content0); - result=gen.generateRequest(null,null,null,content1, false); + result = gen.generateRequest(null, null, null, content1, false); assertEquals(HttpGenerator.Result.FLUSH, result); assertEquals(HttpGenerator.State.COMMITTED, gen.getState()); assertTrue(!gen.isChunking()); - out+=BufferUtil.toString(content1); + out += BufferUtil.toString(content1); BufferUtil.clear(content1); - result=gen.generateResponse(null,false,null,null, null, true); + result = gen.generateResponse(null, false, null, null, null, true); assertEquals(HttpGenerator.Result.CONTINUE, result); assertEquals(HttpGenerator.State.COMPLETING, gen.getState()); assertTrue(!gen.isChunking()); - result=gen.generateResponse(null,false,null,null, null, true); + result = gen.generateResponse(null, false, null, null, null, true); assertEquals(HttpGenerator.Result.DONE, result); assertEquals(HttpGenerator.State.END, gen.getState()); - out+=BufferUtil.toString(chunk); + out += BufferUtil.toString(chunk); BufferUtil.clear(chunk); assertThat(out, Matchers.containsString("POST /index.html HTTP/1.1")); @@ -333,7 +329,5 @@ public class HttpGeneratorClientTest assertThat(out, Matchers.containsString("\r\n\r\nHello World. The quick brown fox jumped over the lazy dog.")); assertEquals(58, gen.getContentPrepared()); - } - } diff --git a/jetty-http/src/test/java/org/eclipse/jetty/http/HttpGeneratorServerHTTPTest.java b/jetty-http/src/test/java/org/eclipse/jetty/http/HttpGeneratorServerHTTPTest.java index 07d6d744fe5..b28625e0e8a 100644 --- a/jetty-http/src/test/java/org/eclipse/jetty/http/HttpGeneratorServerHTTPTest.java +++ b/jetty-http/src/test/java/org/eclipse/jetty/http/HttpGeneratorServerHTTPTest.java @@ -18,12 +18,6 @@ package org.eclipse.jetty.http; -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.either; -import static org.hamcrest.Matchers.equalTo; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertTrue; - import java.nio.ByteBuffer; import java.util.ArrayList; import java.util.EnumSet; @@ -34,6 +28,12 @@ import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.Arguments; import org.junit.jupiter.params.provider.MethodSource; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.either; +import static org.hamcrest.Matchers.equalTo; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + public class HttpGeneratorServerHTTPTest { private String _content; @@ -163,7 +163,6 @@ public class HttpGeneratorServerHTTPTest chunk = BufferUtil.allocate(2048); continue; - case FLUSH: if (BufferUtil.hasContent(header)) { @@ -274,7 +273,7 @@ public class HttpGeneratorServerHTTPTest } } - public final static String CONTENT = "The quick brown fox jumped over the lazy dog.\nNow is the time for all good men to come to the aid of the party\nThe moon is blue to a fish in love.\n"; + public static final String CONTENT = "The quick brown fox jumped over the lazy dog.\nNow is the time for all good men to come to the aid of the party\nThe moon is blue to a fish in love.\n"; private static class Run { @@ -327,18 +326,17 @@ public class HttpGeneratorServerHTTPTest } } - public static Stream data() { Result[] results = { - new Result(200, null, -1, null, false), - new Result(200, null, -1, CONTENT, false), - new Result(200, null, CONTENT.length(), null, true), - new Result(200, null, CONTENT.length(), CONTENT, false), - new Result(200, "text/html", -1, null, true), - new Result(200, "text/html", -1, CONTENT, false), - new Result(200, "text/html", CONTENT.length(), null, true), - new Result(200, "text/html", CONTENT.length(), CONTENT, false) + new Result(200, null, -1, null, false), + new Result(200, null, -1, CONTENT, false), + new Result(200, null, CONTENT.length(), null, true), + new Result(200, null, CONTENT.length(), CONTENT, false), + new Result(200, "text/html", -1, null, true), + new Result(200, "text/html", -1, CONTENT, false), + new Result(200, "text/html", CONTENT.length(), null, true), + new Result(200, "text/html", CONTENT.length(), CONTENT, false) }; ArrayList data = new ArrayList<>(); diff --git a/jetty-http/src/test/java/org/eclipse/jetty/http/HttpGeneratorServerTest.java b/jetty-http/src/test/java/org/eclipse/jetty/http/HttpGeneratorServerTest.java index 5b2e665e539..cc1b0ff61e5 100644 --- a/jetty-http/src/test/java/org/eclipse/jetty/http/HttpGeneratorServerTest.java +++ b/jetty-http/src/test/java/org/eclipse/jetty/http/HttpGeneratorServerTest.java @@ -18,6 +18,12 @@ package org.eclipse.jetty.http; +import java.nio.ByteBuffer; +import java.util.function.Supplier; + +import org.eclipse.jetty.util.BufferUtil; +import org.junit.jupiter.api.Test; + import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.containsString; import static org.hamcrest.Matchers.endsWith; @@ -27,14 +33,8 @@ import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertSame; import static org.junit.jupiter.api.Assertions.assertThrows; -import java.nio.ByteBuffer; -import java.util.function.Supplier; - -import org.eclipse.jetty.util.BufferUtil; -import org.junit.jupiter.api.Test; - public class HttpGeneratorServerTest -{ +{ @Test public void test_0_9() throws Exception { @@ -57,20 +57,20 @@ public class HttpGeneratorServerTest String response = BufferUtil.toString(header); BufferUtil.clear(header); response += BufferUtil.toString(content); - BufferUtil.clear(content); + BufferUtil.clear(content); result = gen.generateResponse(null, false, null, null, content, false); assertEquals(HttpGenerator.Result.SHUTDOWN_OUT, result); assertEquals(HttpGenerator.State.END, gen.getState()); - + assertEquals(10, gen.getContentPrepared()); - + assertThat(response, not(containsString("200 OK"))); assertThat(response, not(containsString("Last-Modified: Thu, 01 Jan 1970 00:00:00 GMT"))); assertThat(response, not(containsString("Content-Length: 10"))); assertThat(response, containsString("0123456789")); } - + @Test public void testSimple() throws Exception { @@ -96,20 +96,20 @@ public class HttpGeneratorServerTest String response = BufferUtil.toString(header); BufferUtil.clear(header); response += BufferUtil.toString(content); - BufferUtil.clear(content); + BufferUtil.clear(content); result = gen.generateResponse(null, false, null, null, content, false); assertEquals(HttpGenerator.Result.DONE, result); assertEquals(HttpGenerator.State.END, gen.getState()); - + assertEquals(10, gen.getContentPrepared()); - + assertThat(response, containsString("HTTP/1.1 200 OK")); assertThat(response, containsString("Last-Modified: Thu, 01 Jan 1970 00:00:00 GMT")); assertThat(response, containsString("Content-Length: 10")); assertThat(response, containsString("\r\n0123456789")); } - + @Test public void test204() throws Exception { @@ -117,23 +117,23 @@ public class HttpGeneratorServerTest ByteBuffer content = BufferUtil.toBuffer("0123456789"); HttpGenerator gen = new HttpGenerator(); - + MetaData.Response info = new MetaData.Response(HttpVersion.HTTP_1_1, 204, "Foo", new HttpFields(), 10); info.getFields().add("Content-Type", "test/data"); info.getFields().add("Last-Modified", DateGenerator.__01Jan1970); HttpGenerator.Result result = gen.generateResponse(info, false, header, null, content, true); - - assertEquals(gen.isNoContent(), true); + + assertEquals(gen.isNoContent(), true); assertEquals(HttpGenerator.Result.FLUSH, result); assertEquals(HttpGenerator.State.COMPLETING, gen.getState()); String responseheaders = BufferUtil.toString(header); - BufferUtil.clear(header); + BufferUtil.clear(header); result = gen.generateResponse(null, false, null, null, content, false); assertEquals(HttpGenerator.Result.DONE, result); assertEquals(HttpGenerator.State.END, gen.getState()); - + assertThat(responseheaders, containsString("HTTP/1.1 204 Foo")); assertThat(responseheaders, containsString("Last-Modified: Thu, 01 Jan 1970 00:00:00 GMT")); assertThat(responseheaders, not(containsString("Content-Length: 10"))); @@ -141,8 +141,7 @@ public class HttpGeneratorServerTest //Note: the HttpConnection.process() method is responsible for actually //excluding the content from the response based on generator.isNoContent()==true } - - + @Test public void testComplexChars() throws Exception { @@ -168,14 +167,14 @@ public class HttpGeneratorServerTest String response = BufferUtil.toString(header); BufferUtil.clear(header); response += BufferUtil.toString(content); - BufferUtil.clear(content); + BufferUtil.clear(content); result = gen.generateResponse(null, false, null, null, content, false); assertEquals(HttpGenerator.Result.DONE, result); assertEquals(HttpGenerator.State.END, gen.getState()); - + assertEquals(10, gen.getContentPrepared()); - + assertThat(response, containsString("HTTP/1.1 200 ØÆ")); assertThat(response, containsString("Last-Modified: Thu, 01 Jan 1970 00:00:00 GMT")); assertThat(response, containsString("Content-Type: test/data; extra=value")); @@ -249,7 +248,8 @@ public class HttpGeneratorServerTest result = gen.generateResponse(info, false, null, null, null, true); assertEquals(HttpGenerator.Result.NEED_HEADER, result); - BadMessageException e = assertThrows(BadMessageException.class, ()->{ + BadMessageException e = assertThrows(BadMessageException.class, () -> + { gen.generateResponse(info, false, header, null, null, true); }); assertEquals(500, e._code); @@ -409,16 +409,16 @@ public class HttpGeneratorServerTest assertThat(out, containsString("Last-Modified: Thu, 01 Jan 1970 00:00:00 GMT")); assertThat(out, not(containsString("Content-Length"))); assertThat(out, containsString("Transfer-Encoding: chunked")); - + assertThat(out, endsWith( - "\r\n\r\nD\r\n"+ - "Hello World! \r\n"+ - "2E\r\n"+ - "The quick brown fox jumped over the lazy dog. \r\n"+ - "0\r\n"+ - "\r\n")); + "\r\n\r\nD\r\n" + + "Hello World! \r\n" + + "2E\r\n" + + "The quick brown fox jumped over the lazy dog. \r\n" + + "0\r\n" + + "\r\n")); } - + @Test public void testResponseWithHintedChunkedContent() throws Exception { @@ -451,7 +451,7 @@ public class HttpGeneratorServerTest result = gen.generateResponse(null, false, null, null, content1, false); assertEquals(HttpGenerator.Result.NEED_CHUNK, result); - + result = gen.generateResponse(null, false, null, chunk, content1, false); assertEquals(HttpGenerator.Result.FLUSH, result); assertEquals(HttpGenerator.State.COMMITTED, gen.getState()); @@ -478,14 +478,14 @@ public class HttpGeneratorServerTest assertThat(out, containsString("Last-Modified: Thu, 01 Jan 1970 00:00:00 GMT")); assertThat(out, not(containsString("Content-Length"))); assertThat(out, containsString("Transfer-Encoding: chunked")); - + assertThat(out, endsWith( - "\r\n\r\nD\r\n"+ - "Hello World! \r\n"+ - "2E\r\n"+ - "The quick brown fox jumped over the lazy dog. \r\n"+ - "0\r\n"+ - "\r\n")); + "\r\n\r\nD\r\n" + + "Hello World! \r\n" + + "2E\r\n" + + "The quick brown fox jumped over the lazy dog. \r\n" + + "0\r\n" + + "\r\n")); } @Test @@ -512,13 +512,13 @@ public class HttpGeneratorServerTest public HttpFields get() { HttpFields trailer = new HttpFields(); - trailer.add("T-Name0","T-ValueA"); - trailer.add("T-Name0","T-ValueB"); - trailer.add("T-Name1","T-ValueC"); + trailer.add("T-Name0", "T-ValueA"); + trailer.add("T-Name0", "T-ValueB"); + trailer.add("T-Name1", "T-ValueC"); return trailer; } }); - + result = gen.generateResponse(info, false, null, null, content0, false); assertEquals(HttpGenerator.Result.NEED_HEADER, result); assertEquals(HttpGenerator.State.START, gen.getState()); @@ -534,7 +534,7 @@ public class HttpGeneratorServerTest result = gen.generateResponse(null, false, null, null, content1, false); assertEquals(HttpGenerator.Result.NEED_CHUNK, result); - + result = gen.generateResponse(null, false, null, chunk, content1, false); assertEquals(HttpGenerator.Result.FLUSH, result); assertEquals(HttpGenerator.State.COMMITTED, gen.getState()); @@ -551,9 +551,9 @@ public class HttpGeneratorServerTest assertEquals(HttpGenerator.Result.NEED_CHUNK_TRAILER, result); assertEquals(HttpGenerator.State.COMPLETING, gen.getState()); - + result = gen.generateResponse(null, false, null, trailer, null, true); - + assertEquals(HttpGenerator.Result.FLUSH, result); assertEquals(HttpGenerator.State.COMPLETING, gen.getState()); out += BufferUtil.toString(trailer); @@ -567,17 +567,17 @@ public class HttpGeneratorServerTest assertThat(out, containsString("Last-Modified: Thu, 01 Jan 1970 00:00:00 GMT")); assertThat(out, not(containsString("Content-Length"))); assertThat(out, containsString("Transfer-Encoding: chunked")); - + assertThat(out, endsWith( - "\r\n\r\nD\r\n"+ - "Hello World! \r\n"+ - "2E\r\n"+ - "The quick brown fox jumped over the lazy dog. \r\n"+ - "0\r\n"+ - "T-Name0: T-ValueA\r\n"+ - "T-Name0: T-ValueB\r\n"+ - "T-Name1: T-ValueC\r\n"+ - "\r\n")); + "\r\n\r\nD\r\n" + + "Hello World! \r\n" + + "2E\r\n" + + "The quick brown fox jumped over the lazy dog. \r\n" + + "0\r\n" + + "T-Name0: T-ValueA\r\n" + + "T-Name0: T-ValueB\r\n" + + "T-Name1: T-ValueC\r\n" + + "\r\n")); } @Test @@ -602,13 +602,13 @@ public class HttpGeneratorServerTest public HttpFields get() { HttpFields trailer = new HttpFields(); - trailer.add("T-Name0","T-ValueA"); - trailer.add("T-Name0","T-ValueB"); - trailer.add("T-Name1","T-ValueC"); + trailer.add("T-Name0", "T-ValueA"); + trailer.add("T-Name0", "T-ValueB"); + trailer.add("T-Name1", "T-ValueC"); return trailer; } }); - + result = gen.generateResponse(info, false, null, null, null, true); assertEquals(HttpGenerator.Result.NEED_HEADER, result); assertEquals(HttpGenerator.State.START, gen.getState()); @@ -627,9 +627,9 @@ public class HttpGeneratorServerTest result = gen.generateResponse(null, false, null, chunk, null, true); assertEquals(HttpGenerator.Result.NEED_CHUNK_TRAILER, result); assertEquals(HttpGenerator.State.COMPLETING, gen.getState()); - + result = gen.generateResponse(null, false, null, trailer, null, true); - + assertEquals(HttpGenerator.Result.FLUSH, result); assertEquals(HttpGenerator.State.COMPLETING, gen.getState()); out += BufferUtil.toString(trailer); @@ -643,14 +643,14 @@ public class HttpGeneratorServerTest assertThat(out, containsString("Last-Modified: Thu, 01 Jan 1970 00:00:00 GMT")); assertThat(out, not(containsString("Content-Length"))); assertThat(out, containsString("Transfer-Encoding: chunked")); - + assertThat(out, endsWith( - "\r\n\r\n"+ - "0\r\n"+ - "T-Name0: T-ValueA\r\n"+ - "T-Name0: T-ValueB\r\n"+ - "T-Name1: T-ValueC\r\n"+ - "\r\n")); + "\r\n\r\n" + + "0\r\n" + + "T-Name0: T-ValueA\r\n" + + "T-Name0: T-ValueB\r\n" + + "T-Name1: T-ValueC\r\n" + + "\r\n")); } @Test @@ -715,7 +715,7 @@ public class HttpGeneratorServerTest MetaData.Response info = new MetaData.Response(HttpVersion.HTTP_1_1, 200, null, new HttpFields(), -1); info.getFields().add("Last-Modified", DateGenerator.__01Jan1970); - info.getFields().add("Content-Length",""+(content0.remaining()+content1.remaining())); + info.getFields().add("Content-Length", "" + (content0.remaining() + content1.remaining())); result = gen.generateResponse(info, false, null, null, content0, false); assertEquals(HttpGenerator.Result.NEED_HEADER, result); assertEquals(HttpGenerator.State.START, gen.getState()); @@ -749,9 +749,6 @@ public class HttpGeneratorServerTest assertThat(out, containsString("Content-Length: 59")); assertThat(out, containsString("\r\n\r\nHello World! The quick brown fox jumped over the lazy dog. ")); } - - - @Test public void test100ThenResponseWithContent() throws Exception @@ -780,7 +777,7 @@ public class HttpGeneratorServerTest assertEquals(HttpGenerator.Result.NEED_INFO, result); assertEquals(HttpGenerator.State.START, gen.getState()); - MetaData.Response info = new MetaData.Response(HttpVersion.HTTP_1_1, 200, null, new HttpFields(), BufferUtil.length(content0)+BufferUtil.length(content1)); + MetaData.Response info = new MetaData.Response(HttpVersion.HTTP_1_1, 200, null, new HttpFields(), BufferUtil.length(content0) + BufferUtil.length(content1)); info.getFields().add("Last-Modified", DateGenerator.__01Jan1970); result = gen.generateResponse(info, false, null, null, content0, false); assertEquals(HttpGenerator.Result.NEED_HEADER, result); diff --git a/jetty-http/src/test/java/org/eclipse/jetty/http/HttpParserTest.java b/jetty-http/src/test/java/org/eclipse/jetty/http/HttpParserTest.java index 5cee781fec7..d8eaaa3841a 100644 --- a/jetty-http/src/test/java/org/eclipse/jetty/http/HttpParserTest.java +++ b/jetty-http/src/test/java/org/eclipse/jetty/http/HttpParserTest.java @@ -147,7 +147,7 @@ public class HttpParserTest HttpParser parser = new HttpParser(handler); parseAll(parser, buffer); assertEquals("HTTP/0.9 not supported", _bad); - assertThat(_complianceViolation,Matchers.empty()); + assertThat(_complianceViolation, Matchers.empty()); } @Test @@ -177,7 +177,7 @@ public class HttpParserTest HttpParser parser = new HttpParser(handler); parseAll(parser, buffer); assertEquals("HTTP/0.9 not supported", _bad); - assertThat(_complianceViolation,Matchers.empty()); + assertThat(_complianceViolation, Matchers.empty()); } @Test @@ -225,11 +225,11 @@ public class HttpParserTest @Test public void testAllowedLinePreamble() throws Exception { - ByteBuffer buffer= BufferUtil.toBuffer("\r\n\r\nGET / HTTP/1.0\r\n"); + ByteBuffer buffer = BufferUtil.toBuffer("\r\n\r\nGET / HTTP/1.0\r\n"); - HttpParser.RequestHandler handler = new Handler(); - HttpParser parser= new HttpParser(handler); - parseAll(parser,buffer); + HttpParser.RequestHandler handler = new Handler(); + HttpParser parser = new HttpParser(handler); + parseAll(parser, buffer); assertEquals("GET", _methodOrVersion); assertEquals("/", _uriOrStatus); assertEquals("HTTP/1.0", _versionOrReason); @@ -239,11 +239,11 @@ public class HttpParserTest @Test public void testDisallowedLinePreamble() throws Exception { - ByteBuffer buffer= BufferUtil.toBuffer("\r\n \r\nGET / HTTP/1.0\r\n"); + ByteBuffer buffer = BufferUtil.toBuffer("\r\n \r\nGET / HTTP/1.0\r\n"); - HttpParser.RequestHandler handler = new Handler(); - HttpParser parser= new HttpParser(handler); - parseAll(parser,buffer); + HttpParser.RequestHandler handler = new Handler(); + HttpParser parser = new HttpParser(handler); + parseAll(parser, buffer); assertEquals("Illegal character SPACE=' '", _bad); } @@ -264,10 +264,10 @@ public class HttpParserTest public void testSimple() throws Exception { ByteBuffer buffer = BufferUtil.toBuffer( - "GET / HTTP/1.0\r\n" + - "Host: localhost\r\n" + - "Connection: close\r\n" + - "\r\n"); + "GET / HTTP/1.0\r\n" + + "Host: localhost\r\n" + + "Connection: close\r\n" + + "\r\n"); HttpParser.RequestHandler handler = new Handler(); HttpParser parser = new HttpParser(handler); @@ -289,13 +289,13 @@ public class HttpParserTest public void testFoldedField2616() throws Exception { ByteBuffer buffer = BufferUtil.toBuffer( - "GET / HTTP/1.0\r\n" + - "Host: localhost\r\n" + - "Name: value\r\n" + - " extra\r\n" + - "Name2: \r\n" + - "\tvalue2\r\n" + - "\r\n"); + "GET / HTTP/1.0\r\n" + + "Host: localhost\r\n" + + "Name: value\r\n" + + " extra\r\n" + + "Name2: \r\n" + + "\tvalue2\r\n" + + "\r\n"); HttpParser.RequestHandler handler = new Handler(); HttpParser parser = new HttpParser(handler, HttpCompliance.RFC2616_LEGACY); @@ -309,18 +309,18 @@ public class HttpParserTest assertEquals("value extra", _val[1]); assertEquals("Name2", _hdr[2]); assertEquals("value2", _val[2]); - assertThat(_complianceViolation, contains(MULTILINE_FIELD_VALUE,MULTILINE_FIELD_VALUE)); + assertThat(_complianceViolation, contains(MULTILINE_FIELD_VALUE, MULTILINE_FIELD_VALUE)); } @Test public void testFoldedField7230() throws Exception { ByteBuffer buffer = BufferUtil.toBuffer( - "GET / HTTP/1.0\r\n" + - "Host: localhost\r\n" + - "Name: value\r\n" + - " extra\r\n" + - "\r\n"); + "GET / HTTP/1.0\r\n" + + "Host: localhost\r\n" + + "Name: value\r\n" + + " extra\r\n" + + "\r\n"); HttpParser.RequestHandler handler = new Handler(); HttpParser parser = new HttpParser(handler, 4096, HttpCompliance.RFC7230_LEGACY); @@ -328,17 +328,17 @@ public class HttpParserTest assertThat(_bad, Matchers.notNullValue()); assertThat(_bad, containsString("Line Folding not supported")); - assertThat(_complianceViolation,Matchers.empty()); + assertThat(_complianceViolation, Matchers.empty()); } - + @Test public void testWhiteSpaceInName() throws Exception { ByteBuffer buffer = BufferUtil.toBuffer( - "GET / HTTP/1.0\r\n" + - "Host: localhost\r\n" + - "N ame: value\r\n" + - "\r\n"); + "GET / HTTP/1.0\r\n" + + "Host: localhost\r\n" + + "N ame: value\r\n" + + "\r\n"); HttpParser.RequestHandler handler = new Handler(); HttpParser parser = new HttpParser(handler, 4096, HttpCompliance.RFC7230_LEGACY); @@ -347,15 +347,15 @@ public class HttpParserTest assertThat(_bad, Matchers.notNullValue()); assertThat(_bad, containsString("Illegal character")); } - + @Test public void testWhiteSpaceAfterName() throws Exception { ByteBuffer buffer = BufferUtil.toBuffer( - "GET / HTTP/1.0\r\n" + - "Host: localhost\r\n" + - "Name : value\r\n" + - "\r\n"); + "GET / HTTP/1.0\r\n" + + "Host: localhost\r\n" + + "Name : value\r\n" + + "\r\n"); HttpParser.RequestHandler handler = new Handler(); HttpParser parser = new HttpParser(handler, 4096, HttpCompliance.RFC7230_LEGACY); @@ -369,27 +369,26 @@ public class HttpParserTest public void testWhiteSpaceBeforeRequest() { HttpCompliance[] compliances = new HttpCompliance[] - { - HttpCompliance.RFC7230, HttpCompliance.RFC2616 - }; + { + HttpCompliance.RFC7230, HttpCompliance.RFC2616 + }; String whitespaces[][] = new String[][] - { - { " ", "Illegal character SPACE" }, - { "\t", "Illegal character HTAB" }, - { "\n", null }, - { "\r", "Bad EOL" }, - { "\r\n", null }, - { "\r\n\r\n", null }, - { "\r\n \r\n", "Illegal character SPACE" }, - { "\r\n\t\r\n", "Illegal character HTAB" }, - { "\r\t\n", "Bad EOL" }, - { "\r\r\n", "Bad EOL" }, - { "\t\r\t\r\n", "Illegal character HTAB" }, - { " \t \r \t \n\n", "Illegal character SPACE" }, - { " \r \t \r\n\r\n\r\n", "Illegal character SPACE" } - }; - + { + {" ", "Illegal character SPACE"}, + {"\t", "Illegal character HTAB"}, + {"\n", null}, + {"\r", "Bad EOL"}, + {"\r\n", null}, + {"\r\n\r\n", null}, + {"\r\n \r\n", "Illegal character SPACE"}, + {"\r\n\t\r\n", "Illegal character HTAB"}, + {"\r\t\n", "Bad EOL"}, + {"\r\r\n", "Bad EOL"}, + {"\t\r\t\r\n", "Illegal character HTAB"}, + {" \t \r \t \n\n", "Illegal character SPACE"}, + {" \r \t \r\n\r\n\r\n", "Illegal character SPACE"} + }; for (int i = 0; i < compliances.length; i++) { @@ -398,12 +397,12 @@ public class HttpParserTest for (int j = 0; j < whitespaces.length; j++) { String request = - whitespaces[j][0] + - "GET / HTTP/1.1\r\n" + - "Host: localhost\r\n" + - "Name: value" + j + "\r\n" + - "Connection: close\r\n" + - "\r\n"; + whitespaces[j][0] + + "GET / HTTP/1.1\r\n" + + "Host: localhost\r\n" + + "Name: value" + j + "\r\n" + + "Connection: close\r\n" + + "\r\n"; ByteBuffer buffer = BufferUtil.toBuffer(request); HttpParser.RequestHandler handler = new Handler(); @@ -413,7 +412,7 @@ public class HttpParserTest String test = "whitespace.[" + compliance + "].[" + j + "]"; String expected = whitespaces[j][1]; - if (expected==null) + if (expected == null) assertThat(test, _bad, is(nullValue())); else assertThat(test, _bad, containsString(expected)); @@ -425,11 +424,11 @@ public class HttpParserTest public void testNoValue() throws Exception { ByteBuffer buffer = BufferUtil.toBuffer( - "GET / HTTP/1.0\r\n" + - "Host: localhost\r\n" + - "Name0: \r\n" + - "Name1:\r\n" + - "\r\n"); + "GET / HTTP/1.0\r\n" + + "Host: localhost\r\n" + + "Name0: \r\n" + + "Name1:\r\n" + + "\r\n"); HttpParser.RequestHandler handler = new Handler(); HttpParser parser = new HttpParser(handler); @@ -453,10 +452,10 @@ public class HttpParserTest public void testTrailingSpacesInHeaderNameNoCustom0() throws Exception { ByteBuffer buffer = BufferUtil.toBuffer( - "HTTP/1.1 204 No Content\r\n" + - "Access-Control-Allow-Headers : Origin\r\n" + - "Other: value\r\n" + - "\r\n"); + "HTTP/1.1 204 No Content\r\n" + + "Access-Control-Allow-Headers : Origin\r\n" + + "Other: value\r\n" + + "\r\n"); HttpParser.ResponseHandler handler = new Handler(); HttpParser parser = new HttpParser(handler); @@ -472,35 +471,34 @@ public class HttpParserTest public void testNoColon7230() throws Exception { ByteBuffer buffer = BufferUtil.toBuffer( - "GET / HTTP/1.0\r\n" + - "Host: localhost\r\n" + - "Name\r\n" + - "\r\n"); + "GET / HTTP/1.0\r\n" + + "Host: localhost\r\n" + + "Name\r\n" + + "\r\n"); HttpParser.RequestHandler handler = new Handler(); - HttpParser parser = new HttpParser(handler,HttpCompliance.RFC7230_LEGACY); + HttpParser parser = new HttpParser(handler, HttpCompliance.RFC7230_LEGACY); parseAll(parser, buffer); assertThat(_bad, containsString("Illegal character")); - assertThat(_complianceViolation,Matchers.empty()); + assertThat(_complianceViolation, Matchers.empty()); } - @Test public void testHeaderParseDirect() throws Exception { ByteBuffer b0 = BufferUtil.toBuffer( - "GET / HTTP/1.0\r\n" + - "Host: localhost\r\n" + - "Header1: value1\r\n" + - "Header2: value 2a \r\n" + - "Header3: 3\r\n" + - "Header4:value4\r\n" + - "Server5: notServer\r\n" + - "HostHeader: notHost\r\n" + - "Connection: close\r\n" + - "Accept-Encoding: gzip, deflated\r\n" + - "Accept: unknown\r\n" + - "\r\n"); + "GET / HTTP/1.0\r\n" + + "Host: localhost\r\n" + + "Header1: value1\r\n" + + "Header2: value 2a \r\n" + + "Header3: 3\r\n" + + "Header4:value4\r\n" + + "Server5: notServer\r\n" + + "HostHeader: notHost\r\n" + + "Connection: close\r\n" + + "Accept-Encoding: gzip, deflated\r\n" + + "Accept: unknown\r\n" + + "\r\n"); ByteBuffer buffer = BufferUtil.allocateDirect(b0.capacity()); int pos = BufferUtil.flipToFill(buffer); BufferUtil.put(b0, buffer); @@ -540,18 +538,18 @@ public class HttpParserTest public void testHeaderParseCRLF() throws Exception { ByteBuffer buffer = BufferUtil.toBuffer( - "GET / HTTP/1.0\r\n" + - "Host: localhost\r\n" + - "Header1: value1\r\n" + - "Header2: value 2a \r\n" + - "Header3: 3\r\n" + - "Header4:value4\r\n" + - "Server5: notServer\r\n" + - "HostHeader: notHost\r\n" + - "Connection: close\r\n" + - "Accept-Encoding: gzip, deflated\r\n" + - "Accept: unknown\r\n" + - "\r\n"); + "GET / HTTP/1.0\r\n" + + "Host: localhost\r\n" + + "Header1: value1\r\n" + + "Header2: value 2a \r\n" + + "Header3: 3\r\n" + + "Header4:value4\r\n" + + "Server5: notServer\r\n" + + "HostHeader: notHost\r\n" + + "Connection: close\r\n" + + "Accept-Encoding: gzip, deflated\r\n" + + "Accept: unknown\r\n" + + "\r\n"); HttpParser.RequestHandler handler = new Handler(); HttpParser parser = new HttpParser(handler); parseAll(parser, buffer); @@ -586,18 +584,18 @@ public class HttpParserTest public void testHeaderParseLF() throws Exception { ByteBuffer buffer = BufferUtil.toBuffer( - "GET / HTTP/1.0\n" + - "Host: localhost\n" + - "Header1: value1\n" + - "Header2: value 2a value 2b \n" + - "Header3: 3\n" + - "Header4:value4\n" + - "Server5: notServer\n" + - "HostHeader: notHost\n" + - "Connection: close\n" + - "Accept-Encoding: gzip, deflated\n" + - "Accept: unknown\n" + - "\n"); + "GET / HTTP/1.0\n" + + "Host: localhost\n" + + "Header1: value1\n" + + "Header2: value 2a value 2b \n" + + "Header3: 3\n" + + "Header4:value4\n" + + "Server5: notServer\n" + + "HostHeader: notHost\n" + + "Connection: close\n" + + "Accept-Encoding: gzip, deflated\n" + + "Accept: unknown\n" + + "\n"); HttpParser.RequestHandler handler = new Handler(); HttpParser parser = new HttpParser(handler); parseAll(parser, buffer); @@ -632,11 +630,11 @@ public class HttpParserTest public void testQuoted() throws Exception { ByteBuffer buffer = BufferUtil.toBuffer( - "GET / HTTP/1.0\n" + - "Name0: \"value0\"\t\n" + - "Name1: \"value\t1\"\n" + - "Name2: \"value\t2A\",\"value,2B\"\t\n" + - "\n"); + "GET / HTTP/1.0\n" + + "Name0: \"value0\"\t\n" + + "Name1: \"value\t1\"\n" + + "Name2: \"value\t2A\",\"value,2B\"\t\n" + + "\n"); HttpParser.RequestHandler handler = new Handler(); HttpParser parser = new HttpParser(handler); parseAll(parser, buffer); @@ -678,30 +676,30 @@ public class HttpParserTest assertEquals("Header1", _hdr[0]); assertEquals("\u00e6 \u00e6", _val[0]); assertEquals("Header2", _hdr[1]); - assertEquals(""+(char)255, _val[1]); + assertEquals("" + (char)255, _val[1]); assertEquals(1, _headers); assertEquals(null, _bad); } - + @Test public void testResponseBufferUpgradeFrom() throws Exception { ByteBuffer buffer = BufferUtil.toBuffer( - "HTTP/1.1 101 Upgrade\r\n" + + "HTTP/1.1 101 Upgrade\r\n" + "Connection: upgrade\r\n" + "Content-Length: 0\r\n" + "Sec-WebSocket-Accept: 4GnyoUP4Sc1JD+2pCbNYAhFYVVA\r\n" + "\r\n" + "FOOGRADE"); - + HttpParser.ResponseHandler handler = new Handler(); HttpParser parser = new HttpParser(handler); - + while (!parser.isState(State.END)) { parser.parseNext(buffer); } - + assertThat(BufferUtil.toUTF8String(buffer), Matchers.is("FOOGRADE")); } @@ -709,7 +707,7 @@ public class HttpParserTest public void testBadMethodEncoding() throws Exception { ByteBuffer buffer = BufferUtil.toBuffer( - "G\u00e6T / HTTP/1.0\r\nHeader0: value0\r\n\n\n"); + "G\u00e6T / HTTP/1.0\r\nHeader0: value0\r\n\n\n"); HttpParser.RequestHandler handler = new Handler(); HttpParser parser = new HttpParser(handler); @@ -721,7 +719,7 @@ public class HttpParserTest public void testBadVersionEncoding() throws Exception { ByteBuffer buffer = BufferUtil.toBuffer( - "GET / H\u00e6P/1.0\r\nHeader0: value0\r\n\n\n"); + "GET / H\u00e6P/1.0\r\nHeader0: value0\r\n\n\n"); HttpParser.RequestHandler handler = new Handler(); HttpParser parser = new HttpParser(handler); @@ -734,8 +732,8 @@ public class HttpParserTest { ByteBuffer buffer = BufferUtil.toBuffer( "GET / HTTP/1.0\r\n" - + "H\u00e6der0: value0\r\n" - + "\n\n"); + + "H\u00e6der0: value0\r\n" + + "\n\n"); HttpParser.RequestHandler handler = new Handler(); HttpParser parser = new HttpParser(handler); @@ -747,7 +745,7 @@ public class HttpParserTest public void testBadHeaderNames() throws Exception { String[] bad = new String[] - { + { "Foo\\Bar: value\r\n", "Foo@Bar: value\r\n", "Foo,Bar: value\r\n", @@ -763,17 +761,17 @@ public class HttpParserTest "Foo/Bar: value\r\n", "Foo]Bar: value\r\n", "Foo[Bar: value\r\n", - }; + }; - for (int i=0; i _complianceViolation = new ArrayList<>(); - + private class Handler implements HttpParser.RequestHandler, HttpParser.ResponseHandler, ComplianceViolation.Listener { private boolean _headerCacheCaseSensitive; diff --git a/jetty-http/src/test/java/org/eclipse/jetty/http/HttpSchemeTest.java b/jetty-http/src/test/java/org/eclipse/jetty/http/HttpSchemeTest.java index 513c2a3f17a..018f9fbe286 100644 --- a/jetty-http/src/test/java/org/eclipse/jetty/http/HttpSchemeTest.java +++ b/jetty-http/src/test/java/org/eclipse/jetty/http/HttpSchemeTest.java @@ -18,10 +18,10 @@ package org.eclipse.jetty.http; -import org.junit.jupiter.api.Test; - import java.nio.ByteBuffer; +import org.junit.jupiter.api.Test; + import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertTrue; @@ -77,5 +77,4 @@ public class HttpSchemeTest assertFalse(byteBuffer.isDirect()); assertTrue(byteBuffer.hasRemaining()); } - } diff --git a/jetty-http/src/test/java/org/eclipse/jetty/http/HttpStatusCodeTest.java b/jetty-http/src/test/java/org/eclipse/jetty/http/HttpStatusCodeTest.java index 4350310618a..3e45cbb50d2 100644 --- a/jetty-http/src/test/java/org/eclipse/jetty/http/HttpStatusCodeTest.java +++ b/jetty-http/src/test/java/org/eclipse/jetty/http/HttpStatusCodeTest.java @@ -18,11 +18,11 @@ package org.eclipse.jetty.http; +import org.junit.jupiter.api.Test; + import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNull; -import org.junit.jupiter.api.Test; - public class HttpStatusCodeTest { @Test @@ -31,8 +31,7 @@ public class HttpStatusCodeTest assertNull(HttpStatus.getCode(800), "Invalid code: 800"); assertNull(HttpStatus.getCode(190), "Invalid code: 190"); } - - + @Test public void testImATeapot() { @@ -42,6 +41,6 @@ public class HttpStatusCodeTest public void testHttpMethod() { - assertEquals("GET",HttpMethod.GET.toString()); + assertEquals("GET", HttpMethod.GET.toString()); } } diff --git a/jetty-http/src/test/java/org/eclipse/jetty/http/HttpURIParseTest.java b/jetty-http/src/test/java/org/eclipse/jetty/http/HttpURIParseTest.java index 19fbb40abd3..1c272fcc6ee 100644 --- a/jetty-http/src/test/java/org/eclipse/jetty/http/HttpURIParseTest.java +++ b/jetty-http/src/test/java/org/eclipse/jetty/http/HttpURIParseTest.java @@ -16,15 +16,8 @@ // ======================================================================== // - package org.eclipse.jetty.http; -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.is; -import static org.hamcrest.Matchers.notNullValue; -import static org.hamcrest.Matchers.nullValue; -import static org.junit.jupiter.api.Assumptions.assumeTrue; - import java.net.URI; import java.net.URISyntaxException; import java.util.stream.Stream; @@ -33,166 +26,172 @@ import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.Arguments; import org.junit.jupiter.params.provider.MethodSource; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.is; +import static org.hamcrest.Matchers.notNullValue; +import static org.hamcrest.Matchers.nullValue; +import static org.junit.jupiter.api.Assumptions.assumeTrue; + public class HttpURIParseTest { public static Stream data() { return Stream.of( - // Nothing but path - Arguments.of("path",null,null,"-1","path",null,null,null), - Arguments.of("path/path",null,null,"-1","path/path",null,null,null), - Arguments.of("%65ncoded/path",null,null,"-1","%65ncoded/path",null,null,null), - - // Basic path reference - Arguments.of("/path/to/context",null,null,"-1","/path/to/context",null,null,null), - - // Basic with encoded query - Arguments.of("http://example.com/path/to/context;param?query=%22value%22#fragment","http","example.com","-1","/path/to/context;param","param","query=%22value%22","fragment"), - Arguments.of("http://[::1]/path/to/context;param?query=%22value%22#fragment","http","[::1]","-1","/path/to/context;param","param","query=%22value%22","fragment"), - - // Basic with parameters and query - Arguments.of("http://example.com:8080/path/to/context;param?query=%22value%22#fragment","http","example.com","8080","/path/to/context;param","param","query=%22value%22","fragment"), - Arguments.of("http://[::1]:8080/path/to/context;param?query=%22value%22#fragment","http","[::1]","8080","/path/to/context;param","param","query=%22value%22","fragment"), - - // Path References - Arguments.of("/path/info",null,null,null,"/path/info",null,null,null), - Arguments.of("/path/info#fragment",null,null,null,"/path/info",null,null,"fragment"), - Arguments.of("/path/info?query",null,null,null,"/path/info",null,"query",null), - Arguments.of("/path/info?query#fragment",null,null,null,"/path/info",null,"query","fragment"), - Arguments.of("/path/info;param",null,null,null,"/path/info;param","param",null,null), - Arguments.of("/path/info;param#fragment",null,null,null,"/path/info;param","param",null,"fragment"), - Arguments.of("/path/info;param?query",null,null,null,"/path/info;param","param","query",null), - Arguments.of("/path/info;param?query#fragment",null,null,null,"/path/info;param","param","query","fragment"), - Arguments.of("/path/info;a=b/foo;c=d",null,null,null,"/path/info;a=b/foo;c=d","c=d",null,null), // TODO #405 + // Nothing but path + Arguments.of("path", null, null, "-1", "path", null, null, null), + Arguments.of("path/path", null, null, "-1", "path/path", null, null, null), + Arguments.of("%65ncoded/path", null, null, "-1", "%65ncoded/path", null, null, null), - // Protocol Less (aka scheme-less) URIs - Arguments.of("//host/path/info",null,"host",null,"/path/info",null,null,null), - Arguments.of("//user@host/path/info",null,"host",null,"/path/info",null,null,null), - Arguments.of("//user@host:8080/path/info",null,"host","8080","/path/info",null,null,null), - Arguments.of("//host:8080/path/info",null,"host","8080","/path/info",null,null,null), - - // Host Less - Arguments.of("http:/path/info","http",null,null,"/path/info",null,null,null), - Arguments.of("http:/path/info#fragment","http",null,null,"/path/info",null,null,"fragment"), - Arguments.of("http:/path/info?query","http",null,null,"/path/info",null,"query",null), - Arguments.of("http:/path/info?query#fragment","http",null,null,"/path/info",null,"query","fragment"), - Arguments.of("http:/path/info;param","http",null,null,"/path/info;param","param",null,null), - Arguments.of("http:/path/info;param#fragment","http",null,null,"/path/info;param","param",null,"fragment"), - Arguments.of("http:/path/info;param?query","http",null,null,"/path/info;param","param","query",null), - Arguments.of("http:/path/info;param?query#fragment","http",null,null,"/path/info;param","param","query","fragment"), - - // Everything and the kitchen sink - Arguments.of("http://user@host:8080/path/info;param?query#fragment","http","host","8080","/path/info;param","param","query","fragment"), - Arguments.of("xxxxx://user@host:8080/path/info;param?query#fragment","xxxxx","host","8080","/path/info;param","param","query","fragment"), - - // No host, parameter with no content - Arguments.of("http:///;?#","http",null,null,"/;","","",""), - - // Path with query that has no value - Arguments.of("/path/info?a=?query",null,null,null,"/path/info",null,"a=?query",null), - - // Path with query alt syntax - Arguments.of("/path/info?a=;query",null,null,null,"/path/info",null,"a=;query",null), + // Basic path reference + Arguments.of("/path/to/context", null, null, "-1", "/path/to/context", null, null, null), - // URI with host character - Arguments.of("/@path/info",null,null,null,"/@path/info",null,null,null), - Arguments.of("/user@path/info",null,null,null,"/user@path/info",null,null,null), - Arguments.of("//user@host/info",null,"host",null,"/info",null,null,null), - Arguments.of("//@host/info",null,"host",null,"/info",null,null,null), - Arguments.of("@host/info",null,null,null,"@host/info",null,null,null), - - // Scheme-less, with host and port (overlapping with path) - Arguments.of("//host:8080//",null,"host","8080","//",null,null,null), - - // File reference - Arguments.of("file:///path/info","file",null,null,"/path/info",null,null,null), - Arguments.of("file:/path/info","file",null,null,"/path/info",null,null,null), + // Basic with encoded query + Arguments.of("http://example.com/path/to/context;param?query=%22value%22#fragment", "http", "example.com", "-1", "/path/to/context;param", "param", "query=%22value%22", "fragment"), + Arguments.of("http://[::1]/path/to/context;param?query=%22value%22#fragment", "http", "[::1]", "-1", "/path/to/context;param", "param", "query=%22value%22", "fragment"), - // Bad URI (no scheme, no host, no path) - Arguments.of("//",null,null,null,null,null,null,null), + // Basic with parameters and query + Arguments.of("http://example.com:8080/path/to/context;param?query=%22value%22#fragment", "http", "example.com", "8080", "/path/to/context;param", "param", "query=%22value%22", "fragment"), + Arguments.of("http://[::1]:8080/path/to/context;param?query=%22value%22#fragment", "http", "[::1]", "8080", "/path/to/context;param", "param", "query=%22value%22", "fragment"), - // Simple localhost references - Arguments.of("http://localhost/","http","localhost",null,"/",null,null,null), - Arguments.of("http://localhost:8080/", "http", "localhost","8080","/", null, null,null), - Arguments.of("http://localhost/?x=y", "http", "localhost",null,"/", null,"x=y",null), - - // Simple path with parameter - Arguments.of("/;param",null, null,null,"/;param", "param",null,null), - Arguments.of(";param",null, null,null,";param", "param",null,null), - - // Simple path with query - Arguments.of("/?x=y",null, null,null,"/", null,"x=y",null), - Arguments.of("/?abc=test",null, null,null,"/", null,"abc=test",null), - - // Simple path with fragment - Arguments.of("/#fragment",null, null,null,"/", null,null,"fragment"), - - // Simple IPv4 host with port (default path) - Arguments.of("http://192.0.0.1:8080/","http","192.0.0.1","8080","/",null,null,null), - - // Simple IPv6 host with port (default path) - - Arguments.of("http://[2001:db8::1]:8080/","http","[2001:db8::1]","8080","/",null,null,null), - // IPv6 authenticated host with port (default path) - - Arguments.of("http://user@[2001:db8::1]:8080/","http","[2001:db8::1]","8080","/",null,null,null), - - // Simple IPv6 host no port (default path) - Arguments.of("http://[2001:db8::1]/","http","[2001:db8::1]",null,"/",null,null,null), - - // Scheme-less IPv6, host with port (default path) - Arguments.of("//[2001:db8::1]:8080/",null,"[2001:db8::1]","8080","/",null,null,null), - - // Interpreted as relative path of "*" (no host/port/scheme/query/fragment) - Arguments.of("*",null,null,null,"*",null, null,null), + // Path References + Arguments.of("/path/info", null, null, null, "/path/info", null, null, null), + Arguments.of("/path/info#fragment", null, null, null, "/path/info", null, null, "fragment"), + Arguments.of("/path/info?query", null, null, null, "/path/info", null, "query", null), + Arguments.of("/path/info?query#fragment", null, null, null, "/path/info", null, "query", "fragment"), + Arguments.of("/path/info;param", null, null, null, "/path/info;param", "param", null, null), + Arguments.of("/path/info;param#fragment", null, null, null, "/path/info;param", "param", null, "fragment"), + Arguments.of("/path/info;param?query", null, null, null, "/path/info;param", "param", "query", null), + Arguments.of("/path/info;param?query#fragment", null, null, null, "/path/info;param", "param", "query", "fragment"), + Arguments.of("/path/info;a=b/foo;c=d", null, null, null, "/path/info;a=b/foo;c=d", "c=d", null, null), // TODO #405 - // Path detection Tests (seen from JSP/JSTL and use) - Arguments.of("http://host:8080/path/info?q1=v1&q2=v2","http","host","8080","/path/info",null,"q1=v1&q2=v2",null), - Arguments.of("/path/info?q1=v1&q2=v2",null,null,null,"/path/info",null,"q1=v1&q2=v2",null), - Arguments.of("/info?q1=v1&q2=v2",null,null,null,"/info",null,"q1=v1&q2=v2",null), - Arguments.of("info?q1=v1&q2=v2",null,null,null,"info",null,"q1=v1&q2=v2",null), - Arguments.of("info;q1=v1?q2=v2",null,null,null,"info;q1=v1","q1=v1","q2=v2",null), - - // Path-less, query only (seen from JSP/JSTL and use) - Arguments.of("?q1=v1&q2=v2",null,null,null,"",null,"q1=v1&q2=v2",null) + // Protocol Less (aka scheme-less) URIs + Arguments.of("//host/path/info", null, "host", null, "/path/info", null, null, null), + Arguments.of("//user@host/path/info", null, "host", null, "/path/info", null, null, null), + Arguments.of("//user@host:8080/path/info", null, "host", "8080", "/path/info", null, null, null), + Arguments.of("//host:8080/path/info", null, "host", "8080", "/path/info", null, null, null), + + // Host Less + Arguments.of("http:/path/info", "http", null, null, "/path/info", null, null, null), + Arguments.of("http:/path/info#fragment", "http", null, null, "/path/info", null, null, "fragment"), + Arguments.of("http:/path/info?query", "http", null, null, "/path/info", null, "query", null), + Arguments.of("http:/path/info?query#fragment", "http", null, null, "/path/info", null, "query", "fragment"), + Arguments.of("http:/path/info;param", "http", null, null, "/path/info;param", "param", null, null), + Arguments.of("http:/path/info;param#fragment", "http", null, null, "/path/info;param", "param", null, "fragment"), + Arguments.of("http:/path/info;param?query", "http", null, null, "/path/info;param", "param", "query", null), + Arguments.of("http:/path/info;param?query#fragment", "http", null, null, "/path/info;param", "param", "query", "fragment"), + + // Everything and the kitchen sink + Arguments.of("http://user@host:8080/path/info;param?query#fragment", "http", "host", "8080", "/path/info;param", "param", "query", "fragment"), + Arguments.of("xxxxx://user@host:8080/path/info;param?query#fragment", "xxxxx", "host", "8080", "/path/info;param", "param", "query", "fragment"), + + // No host, parameter with no content + Arguments.of("http:///;?#", "http", null, null, "/;", "", "", ""), + + // Path with query that has no value + Arguments.of("/path/info?a=?query", null, null, null, "/path/info", null, "a=?query", null), + + // Path with query alt syntax + Arguments.of("/path/info?a=;query", null, null, null, "/path/info", null, "a=;query", null), + + // URI with host character + Arguments.of("/@path/info", null, null, null, "/@path/info", null, null, null), + Arguments.of("/user@path/info", null, null, null, "/user@path/info", null, null, null), + Arguments.of("//user@host/info", null, "host", null, "/info", null, null, null), + Arguments.of("//@host/info", null, "host", null, "/info", null, null, null), + Arguments.of("@host/info", null, null, null, "@host/info", null, null, null), + + // Scheme-less, with host and port (overlapping with path) + Arguments.of("//host:8080//", null, "host", "8080", "//", null, null, null), + + // File reference + Arguments.of("file:///path/info", "file", null, null, "/path/info", null, null, null), + Arguments.of("file:/path/info", "file", null, null, "/path/info", null, null, null), + + // Bad URI (no scheme, no host, no path) + Arguments.of("//", null, null, null, null, null, null, null), + + // Simple localhost references + Arguments.of("http://localhost/", "http", "localhost", null, "/", null, null, null), + Arguments.of("http://localhost:8080/", "http", "localhost", "8080", "/", null, null, null), + Arguments.of("http://localhost/?x=y", "http", "localhost", null, "/", null, "x=y", null), + + // Simple path with parameter + Arguments.of("/;param", null, null, null, "/;param", "param", null, null), + Arguments.of(";param", null, null, null, ";param", "param", null, null), + + // Simple path with query + Arguments.of("/?x=y", null, null, null, "/", null, "x=y", null), + Arguments.of("/?abc=test", null, null, null, "/", null, "abc=test", null), + + // Simple path with fragment + Arguments.of("/#fragment", null, null, null, "/", null, null, "fragment"), + + // Simple IPv4 host with port (default path) + Arguments.of("http://192.0.0.1:8080/", "http", "192.0.0.1", "8080", "/", null, null, null), + + // Simple IPv6 host with port (default path) + + Arguments.of("http://[2001:db8::1]:8080/", "http", "[2001:db8::1]", "8080", "/", null, null, null), + // IPv6 authenticated host with port (default path) + + Arguments.of("http://user@[2001:db8::1]:8080/", "http", "[2001:db8::1]", "8080", "/", null, null, null), + + // Simple IPv6 host no port (default path) + Arguments.of("http://[2001:db8::1]/", "http", "[2001:db8::1]", null, "/", null, null, null), + + // Scheme-less IPv6, host with port (default path) + Arguments.of("//[2001:db8::1]:8080/", null, "[2001:db8::1]", "8080", "/", null, null, null), + + // Interpreted as relative path of "*" (no host/port/scheme/query/fragment) + Arguments.of("*", null, null, null, "*", null, null, null), + + // Path detection Tests (seen from JSP/JSTL and use) + Arguments.of("http://host:8080/path/info?q1=v1&q2=v2", "http", "host", "8080", "/path/info", null, "q1=v1&q2=v2", null), + Arguments.of("/path/info?q1=v1&q2=v2", null, null, null, "/path/info", null, "q1=v1&q2=v2", null), + Arguments.of("/info?q1=v1&q2=v2", null, null, null, "/info", null, "q1=v1&q2=v2", null), + Arguments.of("info?q1=v1&q2=v2", null, null, null, "info", null, "q1=v1&q2=v2", null), + Arguments.of("info;q1=v1?q2=v2", null, null, null, "info;q1=v1", "q1=v1", "q2=v2", null), + + // Path-less, query only (seen from JSP/JSTL and use) + Arguments.of("?q1=v1&q2=v2", null, null, null, "", null, "q1=v1&q2=v2", null) ); } - + @ParameterizedTest @MethodSource("data") public void testParseString(String input, String scheme, String host, Integer port, String path, String param, String query, String fragment) throws Exception { HttpURI httpUri = new HttpURI(input); - + try { new URI(input); // URI is valid (per java.net.URI parsing) - + // Test case sanity check - assertThat("[" + input + "] expected path (test case) cannot be null",path,notNullValue()); + assertThat("[" + input + "] expected path (test case) cannot be null", path, notNullValue()); // Assert expectations - assertThat("[" + input + "] .scheme",httpUri.getScheme(),is(scheme)); - assertThat("[" + input + "] .host",httpUri.getHost(),is(host)); - assertThat("[" + input + "] .port",httpUri.getPort(),is(port == null ? -1 : port)); - assertThat("[" + input + "] .path",httpUri.getPath(),is(path)); - assertThat("[" + input + "] .param",httpUri.getParam(),is(param)); - assertThat("[" + input + "] .query",httpUri.getQuery(),is(query)); - assertThat("[" + input + "] .fragment",httpUri.getFragment(),is(fragment)); - assertThat("[" + input + "] .toString",httpUri.toString(),is(input)); + assertThat("[" + input + "] .scheme", httpUri.getScheme(), is(scheme)); + assertThat("[" + input + "] .host", httpUri.getHost(), is(host)); + assertThat("[" + input + "] .port", httpUri.getPort(), is(port == null ? -1 : port)); + assertThat("[" + input + "] .path", httpUri.getPath(), is(path)); + assertThat("[" + input + "] .param", httpUri.getParam(), is(param)); + assertThat("[" + input + "] .query", httpUri.getQuery(), is(query)); + assertThat("[" + input + "] .fragment", httpUri.getFragment(), is(fragment)); + assertThat("[" + input + "] .toString", httpUri.toString(), is(input)); } catch (URISyntaxException e) { // Assert HttpURI values for invalid URI (such as "//") - assertThat("[" + input + "] .scheme",httpUri.getScheme(),is(nullValue())); - assertThat("[" + input + "] .host",httpUri.getHost(),is(nullValue())); - assertThat("[" + input + "] .port",httpUri.getPort(),is(-1)); - assertThat("[" + input + "] .path",httpUri.getPath(),is(nullValue())); - assertThat("[" + input + "] .param",httpUri.getParam(),is(nullValue())); - assertThat("[" + input + "] .query",httpUri.getQuery(),is(nullValue())); - assertThat("[" + input + "] .fragment",httpUri.getFragment(),is(nullValue())); + assertThat("[" + input + "] .scheme", httpUri.getScheme(), is(nullValue())); + assertThat("[" + input + "] .host", httpUri.getHost(), is(nullValue())); + assertThat("[" + input + "] .port", httpUri.getPort(), is(-1)); + assertThat("[" + input + "] .path", httpUri.getPath(), is(nullValue())); + assertThat("[" + input + "] .param", httpUri.getParam(), is(nullValue())); + assertThat("[" + input + "] .query", httpUri.getQuery(), is(nullValue())); + assertThat("[" + input + "] .fragment", httpUri.getFragment(), is(nullValue())); } } @@ -213,15 +212,15 @@ public class HttpURIParseTest HttpURI httpUri = new HttpURI(javaUri); - assertThat("[" + input + "] .scheme",httpUri.getScheme(),is(scheme)); - assertThat("[" + input + "] .host",httpUri.getHost(),is(host)); - assertThat("[" + input + "] .port",httpUri.getPort(),is(port == null ? -1 : port)); - assertThat("[" + input + "] .path",httpUri.getPath(),is(path)); - assertThat("[" + input + "] .param",httpUri.getParam(),is(param)); - assertThat("[" + input + "] .query",httpUri.getQuery(),is(query)); - assertThat("[" + input + "] .fragment",httpUri.getFragment(),is(fragment)); - - assertThat("[" + input + "] .toString",httpUri.toString(),is(input)); + assertThat("[" + input + "] .scheme", httpUri.getScheme(), is(scheme)); + assertThat("[" + input + "] .host", httpUri.getHost(), is(host)); + assertThat("[" + input + "] .port", httpUri.getPort(), is(port == null ? -1 : port)); + assertThat("[" + input + "] .path", httpUri.getPath(), is(path)); + assertThat("[" + input + "] .param", httpUri.getParam(), is(param)); + assertThat("[" + input + "] .query", httpUri.getQuery(), is(query)); + assertThat("[" + input + "] .fragment", httpUri.getFragment(), is(fragment)); + + assertThat("[" + input + "] .toString", httpUri.toString(), is(input)); } @ParameterizedTest @@ -240,14 +239,14 @@ public class HttpURIParseTest assumeTrue(javaUri != null, "Skipping, not a valid input URI"); HttpURI httpUri = new HttpURI(javaUri); - - assertThat("[" + input + "] .scheme",httpUri.getScheme(),is(javaUri.getScheme())); - assertThat("[" + input + "] .host",httpUri.getHost(),is(javaUri.getHost())); - assertThat("[" + input + "] .port",httpUri.getPort(),is(javaUri.getPort())); - assertThat("[" + input + "] .path",httpUri.getPath(),is(javaUri.getRawPath())); + + assertThat("[" + input + "] .scheme", httpUri.getScheme(), is(javaUri.getScheme())); + assertThat("[" + input + "] .host", httpUri.getHost(), is(javaUri.getHost())); + assertThat("[" + input + "] .port", httpUri.getPort(), is(javaUri.getPort())); + assertThat("[" + input + "] .path", httpUri.getPath(), is(javaUri.getRawPath())); // Not Relevant for java.net.URI -- assertThat("["+input+"] .param", httpUri.getParam(), is(param)); - assertThat("[" + input + "] .query",httpUri.getQuery(),is(javaUri.getRawQuery())); - assertThat("[" + input + "] .fragment",httpUri.getFragment(),is(javaUri.getFragment())); - assertThat("[" + input + "] .toString",httpUri.toString(),is(javaUri.toASCIIString())); + assertThat("[" + input + "] .query", httpUri.getQuery(), is(javaUri.getRawQuery())); + assertThat("[" + input + "] .fragment", httpUri.getFragment(), is(javaUri.getFragment())); + assertThat("[" + input + "] .toString", httpUri.toString(), is(javaUri.toASCIIString())); } } diff --git a/jetty-http/src/test/java/org/eclipse/jetty/http/HttpURITest.java b/jetty-http/src/test/java/org/eclipse/jetty/http/HttpURITest.java index 35ea8f13e15..ab1b78e5a78 100644 --- a/jetty-http/src/test/java/org/eclipse/jetty/http/HttpURITest.java +++ b/jetty-http/src/test/java/org/eclipse/jetty/http/HttpURITest.java @@ -16,39 +16,38 @@ // ======================================================================== // - package org.eclipse.jetty.http; -import static org.hamcrest.Matchers.is; -import static org.hamcrest.Matchers.nullValue; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.hamcrest.MatcherAssert.assertThat; -import static org.junit.jupiter.api.Assertions.assertTrue; -import static org.junit.jupiter.api.Assertions.fail; - import java.net.URLEncoder; import java.nio.charset.StandardCharsets; import org.eclipse.jetty.util.MultiMap; import org.junit.jupiter.api.Test; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.is; +import static org.hamcrest.Matchers.nullValue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.fail; + public class HttpURITest { @Test public void testExample() throws Exception { HttpURI uri = new HttpURI("http://user:password@host:8888/ignored/../p%61th;ignored/info;param?query=value#fragment"); - - assertThat(uri.getScheme(),is("http")); - assertThat(uri.getUser(),is("user:password")); - assertThat(uri.getHost(),is("host")); - assertThat(uri.getPort(),is(8888)); - assertThat(uri.getPath(),is("/ignored/../p%61th;ignored/info;param")); - assertThat(uri.getDecodedPath(),is("/path/info")); - assertThat(uri.getParam(),is("param")); - assertThat(uri.getQuery(),is("query=value")); - assertThat(uri.getFragment(),is("fragment")); - assertThat(uri.getAuthority(),is("host:8888")); + + assertThat(uri.getScheme(), is("http")); + assertThat(uri.getUser(), is("user:password")); + assertThat(uri.getHost(), is("host")); + assertThat(uri.getPort(), is(8888)); + assertThat(uri.getPath(), is("/ignored/../p%61th;ignored/info;param")); + assertThat(uri.getDecodedPath(), is("/path/info")); + assertThat(uri.getParam(), is("param")); + assertThat(uri.getQuery(), is("query=value")); + assertThat(uri.getFragment(), is("fragment")); + assertThat(uri.getAuthority(), is("host:8888")); } @Test @@ -79,20 +78,20 @@ public class HttpURITest HttpURI uri = new HttpURI(); uri.parse("*"); - assertThat(uri.getHost(),nullValue()); - assertThat(uri.getPath(),is("*")); - + assertThat(uri.getHost(), nullValue()); + assertThat(uri.getPath(), is("*")); + uri.parse("/foo/bar"); - assertThat(uri.getHost(),nullValue()); - assertThat(uri.getPath(),is("/foo/bar")); - + assertThat(uri.getHost(), nullValue()); + assertThat(uri.getPath(), is("/foo/bar")); + uri.parse("//foo/bar"); - assertThat(uri.getHost(),is("foo")); - assertThat(uri.getPath(),is("/bar")); - + assertThat(uri.getHost(), is("foo")); + assertThat(uri.getPath(), is("/bar")); + uri.parse("http://foo/bar"); - assertThat(uri.getHost(),is("foo")); - assertThat(uri.getPath(),is("/bar")); + assertThat(uri.getHost(), is("foo")); + assertThat(uri.getPath(), is("/bar")); } @Test @@ -100,33 +99,33 @@ public class HttpURITest { HttpURI uri = new HttpURI(); - uri.parseRequestTarget("GET","*"); - assertThat(uri.getHost(),nullValue()); - assertThat(uri.getPath(),is("*")); - - uri.parseRequestTarget("GET","/foo/bar"); - assertThat(uri.getHost(),nullValue()); - assertThat(uri.getPath(),is("/foo/bar")); - - uri.parseRequestTarget("GET","//foo/bar"); - assertThat(uri.getHost(),nullValue()); - assertThat(uri.getPath(),is("//foo/bar")); - - uri.parseRequestTarget("GET","http://foo/bar"); - assertThat(uri.getHost(),is("foo")); - assertThat(uri.getPath(),is("/bar")); + uri.parseRequestTarget("GET", "*"); + assertThat(uri.getHost(), nullValue()); + assertThat(uri.getPath(), is("*")); + + uri.parseRequestTarget("GET", "/foo/bar"); + assertThat(uri.getHost(), nullValue()); + assertThat(uri.getPath(), is("/foo/bar")); + + uri.parseRequestTarget("GET", "//foo/bar"); + assertThat(uri.getHost(), nullValue()); + assertThat(uri.getPath(), is("//foo/bar")); + + uri.parseRequestTarget("GET", "http://foo/bar"); + assertThat(uri.getHost(), is("foo")); + assertThat(uri.getPath(), is("/bar")); } @Test public void testExtB() throws Exception { - for (String value: new String[]{"a","abcdABCD","\u00C0","\u697C","\uD869\uDED5","\uD840\uDC08"} ) + for (String value : new String[]{"a", "abcdABCD", "\u00C0", "\u697C", "\uD869\uDED5", "\uD840\uDC08"}) { - HttpURI uri = new HttpURI("/path?value="+URLEncoder.encode(value,"UTF-8")); + HttpURI uri = new HttpURI("/path?value=" + URLEncoder.encode(value, "UTF-8")); MultiMap parameters = new MultiMap<>(); - uri.decodeQueryTo(parameters,StandardCharsets.UTF_8); - assertEquals(value,parameters.getString("value")); + uri.decodeQueryTo(parameters, StandardCharsets.UTF_8); + assertEquals(value, parameters.getString("value")); } } @@ -134,103 +133,102 @@ public class HttpURITest public void testAt() throws Exception { HttpURI uri = new HttpURI("/@foo/bar"); - assertEquals("/@foo/bar",uri.getPath()); + assertEquals("/@foo/bar", uri.getPath()); } @Test public void testParams() throws Exception { HttpURI uri = new HttpURI("/foo/bar"); - assertEquals("/foo/bar",uri.getPath()); - assertEquals("/foo/bar",uri.getDecodedPath()); - assertEquals(null,uri.getParam()); - + assertEquals("/foo/bar", uri.getPath()); + assertEquals("/foo/bar", uri.getDecodedPath()); + assertEquals(null, uri.getParam()); + uri = new HttpURI("/foo/bar;jsessionid=12345"); - assertEquals("/foo/bar;jsessionid=12345",uri.getPath()); - assertEquals("/foo/bar",uri.getDecodedPath()); - assertEquals("jsessionid=12345",uri.getParam()); - + assertEquals("/foo/bar;jsessionid=12345", uri.getPath()); + assertEquals("/foo/bar", uri.getDecodedPath()); + assertEquals("jsessionid=12345", uri.getParam()); + uri = new HttpURI("/foo;abc=123/bar;jsessionid=12345"); - assertEquals("/foo;abc=123/bar;jsessionid=12345",uri.getPath()); - assertEquals("/foo/bar",uri.getDecodedPath()); - assertEquals("jsessionid=12345",uri.getParam()); - + assertEquals("/foo;abc=123/bar;jsessionid=12345", uri.getPath()); + assertEquals("/foo/bar", uri.getDecodedPath()); + assertEquals("jsessionid=12345", uri.getParam()); + uri = new HttpURI("/foo;abc=123/bar;jsessionid=12345?name=value"); - assertEquals("/foo;abc=123/bar;jsessionid=12345",uri.getPath()); - assertEquals("/foo/bar",uri.getDecodedPath()); - assertEquals("jsessionid=12345",uri.getParam()); - + assertEquals("/foo;abc=123/bar;jsessionid=12345", uri.getPath()); + assertEquals("/foo/bar", uri.getDecodedPath()); + assertEquals("jsessionid=12345", uri.getParam()); + uri = new HttpURI("/foo;abc=123/bar;jsessionid=12345#target"); - assertEquals("/foo;abc=123/bar;jsessionid=12345",uri.getPath()); - assertEquals("/foo/bar",uri.getDecodedPath()); - assertEquals("jsessionid=12345",uri.getParam()); + assertEquals("/foo;abc=123/bar;jsessionid=12345", uri.getPath()); + assertEquals("/foo/bar", uri.getDecodedPath()); + assertEquals("jsessionid=12345", uri.getParam()); } - + @Test public void testMutableURI() { HttpURI uri = new HttpURI("/foo/bar"); - assertEquals("/foo/bar",uri.toString()); - assertEquals("/foo/bar",uri.getPath()); - assertEquals("/foo/bar",uri.getDecodedPath()); + assertEquals("/foo/bar", uri.toString()); + assertEquals("/foo/bar", uri.getPath()); + assertEquals("/foo/bar", uri.getDecodedPath()); uri.setScheme("http"); - assertEquals("http:/foo/bar",uri.toString()); - assertEquals("/foo/bar",uri.getPath()); - assertEquals("/foo/bar",uri.getDecodedPath()); + assertEquals("http:/foo/bar", uri.toString()); + assertEquals("/foo/bar", uri.getPath()); + assertEquals("/foo/bar", uri.getDecodedPath()); - uri.setAuthority("host",0); - assertEquals("http://host/foo/bar",uri.toString()); - assertEquals("/foo/bar",uri.getPath()); - assertEquals("/foo/bar",uri.getDecodedPath()); + uri.setAuthority("host", 0); + assertEquals("http://host/foo/bar", uri.toString()); + assertEquals("/foo/bar", uri.getPath()); + assertEquals("/foo/bar", uri.getDecodedPath()); + + uri.setAuthority("host", 8888); + assertEquals("http://host:8888/foo/bar", uri.toString()); + assertEquals("/foo/bar", uri.getPath()); + assertEquals("/foo/bar", uri.getDecodedPath()); - uri.setAuthority("host",8888); - assertEquals("http://host:8888/foo/bar",uri.toString()); - assertEquals("/foo/bar",uri.getPath()); - assertEquals("/foo/bar",uri.getDecodedPath()); - uri.setPathQuery("/f%30%30;p0/bar;p1;p2"); - assertEquals("http://host:8888/f%30%30;p0/bar;p1;p2",uri.toString()); - assertEquals("/f%30%30;p0/bar;p1;p2",uri.getPath()); - assertEquals("/f00/bar",uri.getDecodedPath()); - assertEquals("p2",uri.getParam()); - assertEquals(null,uri.getQuery()); - + assertEquals("http://host:8888/f%30%30;p0/bar;p1;p2", uri.toString()); + assertEquals("/f%30%30;p0/bar;p1;p2", uri.getPath()); + assertEquals("/f00/bar", uri.getDecodedPath()); + assertEquals("p2", uri.getParam()); + assertEquals(null, uri.getQuery()); + uri.setPathQuery("/f%30%30;p0/bar;p1;p2?name=value"); - assertEquals("http://host:8888/f%30%30;p0/bar;p1;p2?name=value",uri.toString()); - assertEquals("/f%30%30;p0/bar;p1;p2",uri.getPath()); - assertEquals("/f00/bar",uri.getDecodedPath()); - assertEquals("p2",uri.getParam()); - assertEquals("name=value",uri.getQuery()); - + assertEquals("http://host:8888/f%30%30;p0/bar;p1;p2?name=value", uri.toString()); + assertEquals("/f%30%30;p0/bar;p1;p2", uri.getPath()); + assertEquals("/f00/bar", uri.getDecodedPath()); + assertEquals("p2", uri.getParam()); + assertEquals("name=value", uri.getQuery()); + uri.setQuery("other=123456"); - assertEquals("http://host:8888/f%30%30;p0/bar;p1;p2?other=123456",uri.toString()); - assertEquals("/f%30%30;p0/bar;p1;p2",uri.getPath()); - assertEquals("/f00/bar",uri.getDecodedPath()); - assertEquals("p2",uri.getParam()); - assertEquals("other=123456",uri.getQuery()); + assertEquals("http://host:8888/f%30%30;p0/bar;p1;p2?other=123456", uri.toString()); + assertEquals("/f%30%30;p0/bar;p1;p2", uri.getPath()); + assertEquals("/f00/bar", uri.getDecodedPath()); + assertEquals("p2", uri.getParam()); + assertEquals("other=123456", uri.getQuery()); } @Test public void testSchemeAndOrAuthority() throws Exception { HttpURI uri = new HttpURI("/path/info"); - assertEquals("/path/info",uri.toString()); - - uri.setAuthority("host",0); - assertEquals("//host/path/info",uri.toString()); - - uri.setAuthority("host",8888); - assertEquals("//host:8888/path/info",uri.toString()); - + assertEquals("/path/info", uri.toString()); + + uri.setAuthority("host", 0); + assertEquals("//host/path/info", uri.toString()); + + uri.setAuthority("host", 8888); + assertEquals("//host:8888/path/info", uri.toString()); + uri.setScheme("http"); - assertEquals("http://host:8888/path/info",uri.toString()); - - uri.setAuthority(null,0); - assertEquals("http:/path/info",uri.toString()); - + assertEquals("http://host:8888/path/info", uri.toString()); + + uri.setAuthority(null, 0); + assertEquals("http:/path/info", uri.toString()); } - + @Test public void testBasicAuthCredentials() throws Exception { @@ -244,34 +242,33 @@ public class HttpURITest public void testCanonicalDecoded() throws Exception { HttpURI uri = new HttpURI("/path/.info"); - assertEquals("/path/.info",uri.getDecodedPath()); - + assertEquals("/path/.info", uri.getDecodedPath()); + uri = new HttpURI("/path/./info"); - assertEquals("/path/info",uri.getDecodedPath()); - + assertEquals("/path/info", uri.getDecodedPath()); + uri = new HttpURI("/path/../info"); - assertEquals("/info",uri.getDecodedPath()); - + assertEquals("/info", uri.getDecodedPath()); + uri = new HttpURI("/./path/info."); - assertEquals("/path/info.",uri.getDecodedPath()); - + assertEquals("/path/info.", uri.getDecodedPath()); + uri = new HttpURI("./path/info/."); - assertEquals("path/info/",uri.getDecodedPath()); - + assertEquals("path/info/", uri.getDecodedPath()); + uri = new HttpURI("http://host/path/.info"); - assertEquals("/path/.info",uri.getDecodedPath()); - + assertEquals("/path/.info", uri.getDecodedPath()); + uri = new HttpURI("http://host/path/./info"); - assertEquals("/path/info",uri.getDecodedPath()); - + assertEquals("/path/info", uri.getDecodedPath()); + uri = new HttpURI("http://host/path/../info"); - assertEquals("/info",uri.getDecodedPath()); - + assertEquals("/info", uri.getDecodedPath()); + uri = new HttpURI("http://host/./path/info."); - assertEquals("/path/info.",uri.getDecodedPath()); - + assertEquals("/path/info.", uri.getDecodedPath()); + uri = new HttpURI("http:./path/info/."); - assertEquals("path/info/",uri.getDecodedPath()); + assertEquals("path/info/", uri.getDecodedPath()); } - } diff --git a/jetty-http/src/test/java/org/eclipse/jetty/http/MimeTypesTest.java b/jetty-http/src/test/java/org/eclipse/jetty/http/MimeTypesTest.java index 3ada26f378a..89720e31a6a 100644 --- a/jetty-http/src/test/java/org/eclipse/jetty/http/MimeTypesTest.java +++ b/jetty-http/src/test/java/org/eclipse/jetty/http/MimeTypesTest.java @@ -31,36 +31,36 @@ public class MimeTypesTest @Test public void testGetMimeByExtension_Gzip() { - assertMimeTypeByExtension("application/gzip","test.gz"); + assertMimeTypeByExtension("application/gzip", "test.gz"); } @Test public void testGetMimeByExtension_Png() { - assertMimeTypeByExtension("image/png","test.png"); - assertMimeTypeByExtension("image/png","TEST.PNG"); - assertMimeTypeByExtension("image/png","Test.Png"); + assertMimeTypeByExtension("image/png", "test.png"); + assertMimeTypeByExtension("image/png", "TEST.PNG"); + assertMimeTypeByExtension("image/png", "Test.Png"); } @Test public void testGetMimeByExtension_Png_MultiDot() { - assertMimeTypeByExtension("image/png","org.eclipse.jetty.Logo.png"); + assertMimeTypeByExtension("image/png", "org.eclipse.jetty.Logo.png"); } @Test public void testGetMimeByExtension_Png_DeepPath() { - assertMimeTypeByExtension("image/png","/org/eclipse/jetty/Logo.png"); + assertMimeTypeByExtension("image/png", "/org/eclipse/jetty/Logo.png"); } @Test public void testGetMimeByExtension_Text() { - assertMimeTypeByExtension("text/plain","test.txt"); - assertMimeTypeByExtension("text/plain","TEST.TXT"); + assertMimeTypeByExtension("text/plain", "test.txt"); + assertMimeTypeByExtension("text/plain", "TEST.TXT"); } - + @Test public void testGetMimeByExtension_NoExtension() { @@ -74,14 +74,14 @@ public class MimeTypesTest MimeTypes mimetypes = new MimeTypes(); String contentType = mimetypes.getMimeByExtension(filename); String prefix = "MimeTypes.getMimeByExtension(" + filename + ")"; - assertNotNull(contentType,prefix); - assertEquals(expectedMimeType,contentType,prefix); + assertNotNull(contentType, prefix); + assertEquals(expectedMimeType, contentType, prefix); } - + private void assertCharsetFromContentType(String contentType, String expectedCharset) { assertThat("getCharsetFromContentType(\"" + contentType + "\")", - MimeTypes.getCharsetFromContentType(contentType), is(expectedCharset)); + MimeTypes.getCharsetFromContentType(contentType), is(expectedCharset)); } @Test @@ -110,19 +110,19 @@ public class MimeTypesTest @Test public void testContentTypeWithoutCharset() { - assertEquals("foo/bar;some=else",MimeTypes.getContentTypeWithoutCharset("foo/bar;charset=abc;some=else")); - assertEquals("foo/bar",MimeTypes.getContentTypeWithoutCharset("foo/bar;charset=abc")); - assertEquals("foo/bar",MimeTypes.getContentTypeWithoutCharset("foo/bar ; charset = abc")); - assertEquals("foo/bar;some=else",MimeTypes.getContentTypeWithoutCharset("foo/bar ; charset = abc ; some=else")); - assertEquals("foo/bar;other=param;some=else",MimeTypes.getContentTypeWithoutCharset("foo/bar;other=param;charset=abc;some=else")); - assertEquals("foo/bar;other=param",MimeTypes.getContentTypeWithoutCharset("foo/bar;other=param;charset=abc")); - assertEquals("foo/bar ; other = param",MimeTypes.getContentTypeWithoutCharset("foo/bar ; other = param ; charset = abc")); - assertEquals("foo/bar ; other = param;some=else",MimeTypes.getContentTypeWithoutCharset("foo/bar ; other = param ; charset = abc ; some=else")); - assertEquals("foo/bar ; other = param",MimeTypes.getContentTypeWithoutCharset("foo/bar ; other = param ; charset = abc")); - assertEquals("foo/bar ; other = param;some=else",MimeTypes.getContentTypeWithoutCharset("foo/bar ; other = param ; charset = \"abc\" ; some=else")); - assertEquals("foo/bar",MimeTypes.getContentTypeWithoutCharset("foo/bar")); - assertEquals("foo/bar",MimeTypes.getContentTypeWithoutCharset("foo/bar;charset=uTf8")); - assertEquals("foo/bar;other=\"charset=abc\"",MimeTypes.getContentTypeWithoutCharset("foo/bar;other=\"charset=abc\";charset=uTf8")); - assertEquals("text/html",MimeTypes.getContentTypeWithoutCharset("text/html;charset=utf-8")); + assertEquals("foo/bar;some=else", MimeTypes.getContentTypeWithoutCharset("foo/bar;charset=abc;some=else")); + assertEquals("foo/bar", MimeTypes.getContentTypeWithoutCharset("foo/bar;charset=abc")); + assertEquals("foo/bar", MimeTypes.getContentTypeWithoutCharset("foo/bar ; charset = abc")); + assertEquals("foo/bar;some=else", MimeTypes.getContentTypeWithoutCharset("foo/bar ; charset = abc ; some=else")); + assertEquals("foo/bar;other=param;some=else", MimeTypes.getContentTypeWithoutCharset("foo/bar;other=param;charset=abc;some=else")); + assertEquals("foo/bar;other=param", MimeTypes.getContentTypeWithoutCharset("foo/bar;other=param;charset=abc")); + assertEquals("foo/bar ; other = param", MimeTypes.getContentTypeWithoutCharset("foo/bar ; other = param ; charset = abc")); + assertEquals("foo/bar ; other = param;some=else", MimeTypes.getContentTypeWithoutCharset("foo/bar ; other = param ; charset = abc ; some=else")); + assertEquals("foo/bar ; other = param", MimeTypes.getContentTypeWithoutCharset("foo/bar ; other = param ; charset = abc")); + assertEquals("foo/bar ; other = param;some=else", MimeTypes.getContentTypeWithoutCharset("foo/bar ; other = param ; charset = \"abc\" ; some=else")); + assertEquals("foo/bar", MimeTypes.getContentTypeWithoutCharset("foo/bar")); + assertEquals("foo/bar", MimeTypes.getContentTypeWithoutCharset("foo/bar;charset=uTf8")); + assertEquals("foo/bar;other=\"charset=abc\"", MimeTypes.getContentTypeWithoutCharset("foo/bar;other=\"charset=abc\";charset=uTf8")); + assertEquals("text/html", MimeTypes.getContentTypeWithoutCharset("text/html;charset=utf-8")); } } diff --git a/jetty-http/src/test/java/org/eclipse/jetty/http/MultiPartCaptureTest.java b/jetty-http/src/test/java/org/eclipse/jetty/http/MultiPartCaptureTest.java index 2021e93b69e..f76fcc47227 100644 --- a/jetty-http/src/test/java/org/eclipse/jetty/http/MultiPartCaptureTest.java +++ b/jetty-http/src/test/java/org/eclipse/jetty/http/MultiPartCaptureTest.java @@ -167,8 +167,8 @@ public class MultiPartCaptureTest { MultiPartFormInputStream parser = new MultiPartFormInputStream(in, multipartExpectations.contentType, config, outputDir.toFile()); - multipartExpectations.checkParts(parser.getParts(),s-> - { + multipartExpectations.checkParts(parser.getParts(), s -> + { try { return parser.getPart(s); @@ -176,11 +176,11 @@ public class MultiPartCaptureTest catch (Exception e) { throw new RuntimeException(e); - } + } }); } } - + private MultipartConfigElement newMultipartConfigElement(Path path) { return new MultipartConfigElement(path.toString(), MAX_FILE_SIZE, MAX_REQUEST_SIZE, FILE_SIZE_THRESHOLD); @@ -221,7 +221,7 @@ public class MultiPartCaptureTest switch (split[0]) { case "Request-Header": - if(split[1].equalsIgnoreCase("Content-Type")) + if (split[1].equalsIgnoreCase("Content-Type")) { parsedContentType = split[2]; } @@ -277,12 +277,11 @@ public class MultiPartCaptureTest String defaultCharset = UTF_8.toString(); Part charSetPart = getPart.apply("_charset_"); - if(charSetPart != null) + if (charSetPart != null) { defaultCharset = IO.toString(charSetPart.getInputStream()); } - // Evaluate expected Contents for (NameValue expected : partContainsContents) { @@ -323,16 +322,16 @@ public class MultiPartCaptureTest private String getCharsetFromContentType(String contentType, String defaultCharset) { - if(StringUtil.isBlank(contentType)) + if (StringUtil.isBlank(contentType)) { return defaultCharset; } QuotedStringTokenizer tok = new QuotedStringTokenizer(contentType, ";", false, false); - while(tok.hasMoreTokens()) + while (tok.hasMoreTokens()) { String str = tok.nextToken().trim(); - if(str.startsWith("charset=")) + if (str.startsWith("charset=")) { return str.substring("charset=".length()); } diff --git a/jetty-http/src/test/java/org/eclipse/jetty/http/MultiPartFormInputStreamTest.java b/jetty-http/src/test/java/org/eclipse/jetty/http/MultiPartFormInputStreamTest.java index 7fcfdc5a62b..9343f82e58a 100644 --- a/jetty-http/src/test/java/org/eclipse/jetty/http/MultiPartFormInputStreamTest.java +++ b/jetty-http/src/test/java/org/eclipse/jetty/http/MultiPartFormInputStreamTest.java @@ -62,124 +62,121 @@ public class MultiPartFormInputStreamTest // TODO: move to testing dir concept protected String _dirname = System.getProperty("java.io.tmpdir") + File.separator + "myfiles-" + TimeUnit.NANOSECONDS.toMillis(System.nanoTime()); protected File _tmpDir = new File(_dirname); - + public MultiPartFormInputStreamTest() { _tmpDir.deleteOnExit(); } - + @Test public void testBadMultiPartRequest() - throws Exception + throws Exception { String boundary = "X0Y0"; String str = "--" + boundary + "\r\n" + - "Content-Disposition: form-data; name=\"fileup\"; filename=\"test.upload\"\r\n" + - "Content-Type: application/octet-stream\r\n\r\n" + - "How now brown cow." + - "\r\n--" + boundary + "-\r\n" - + "Content-Disposition: form-data; name=\"fileup\"; filename=\"test.upload\"\r\n" - + "\r\n"; + "Content-Disposition: form-data; name=\"fileup\"; filename=\"test.upload\"\r\n" + + "Content-Type: application/octet-stream\r\n\r\n" + + "How now brown cow." + + "\r\n--" + boundary + "-\r\n" + + "Content-Disposition: form-data; name=\"fileup\"; filename=\"test.upload\"\r\n" + + "\r\n"; MultipartConfigElement config = new MultipartConfigElement(_dirname, 1024, 3072, 50); MultiPartFormInputStream mpis = new MultiPartFormInputStream(new ByteArrayInputStream(str.getBytes()), - "multipart/form-data, boundary=" + boundary, - config, - _tmpDir); + "multipart/form-data, boundary=" + boundary, + config, + _tmpDir); mpis.setDeleteOnExit(true); IOException x = assertThrows(IOException.class, - ()-> mpis.getParts(), - "Incomplete Multipart"); + () -> mpis.getParts(), + "Incomplete Multipart"); assertThat(x.getMessage(), startsWith("Incomplete")); } - @Test public void testFinalBoundaryOnly() - throws Exception + throws Exception { String delimiter = "\r\n"; final String boundary = "MockMultiPartTestBoundary"; - // Malformed multipart request body containing only an arbitrary string of text, followed by the final boundary marker, delimited by empty lines. String str = + delimiter + + "Hello world" + + delimiter + // Two delimiter markers, which make an empty line. delimiter + - "Hello world" + - delimiter + // Two delimiter markers, which make an empty line. - delimiter + - "--" + boundary + "--" + delimiter; + "--" + boundary + "--" + delimiter; MultipartConfigElement config = new MultipartConfigElement(_dirname, 1024, 3072, 50); MultiPartFormInputStream mpis = new MultiPartFormInputStream(new ByteArrayInputStream(str.getBytes()), - "multipart/form-data, boundary=" + boundary, - config, - _tmpDir); + "multipart/form-data, boundary=" + boundary, + config, + _tmpDir); mpis.setDeleteOnExit(true); assertTrue(mpis.getParts().isEmpty()); } - - + @Test public void testEmpty() - throws Exception + throws Exception { String delimiter = "\r\n"; final String boundary = "MockMultiPartTestBoundary"; String str = - delimiter + - "--" + boundary + "--" + delimiter; + delimiter + + "--" + boundary + "--" + delimiter; MultipartConfigElement config = new MultipartConfigElement(_dirname, 1024, 3072, 50); MultiPartFormInputStream mpis = new MultiPartFormInputStream(new ByteArrayInputStream(str.getBytes()), - "multipart/form-data, boundary=" + boundary, - config, - _tmpDir); + "multipart/form-data, boundary=" + boundary, + config, + _tmpDir); mpis.setDeleteOnExit(true); assertTrue(mpis.getParts().isEmpty()); } @Test public void testNoBoundaryRequest() - throws Exception + throws Exception { String str = "--\r\n" + - "Content-Disposition: form-data; name=\"fileName\"\r\n" + - "Content-Type: text/plain; charset=US-ASCII\r\n" + - "Content-Transfer-Encoding: 8bit\r\n" + - "\r\n" + - "abc\r\n" + - "--\r\n" + - "Content-Disposition: form-data; name=\"desc\"\r\n" + - "Content-Type: text/plain; charset=US-ASCII\r\n" + - "Content-Transfer-Encoding: 8bit\r\n" + - "\r\n" + - "123\r\n" + - "--\r\n" + - "Content-Disposition: form-data; name=\"title\"\r\n" + - "Content-Type: text/plain; charset=US-ASCII\r\n" + - "Content-Transfer-Encoding: 8bit\r\n" + - "\r\n" + - "ttt\r\n" + - "--\r\n" + - "Content-Disposition: form-data; name=\"datafile5239138112980980385.txt\"; filename=\"datafile5239138112980980385.txt\"\r\n" + - "Content-Type: application/octet-stream; charset=ISO-8859-1\r\n" + - "Content-Transfer-Encoding: binary\r\n" + - "\r\n" + - "000\r\n" + - "----\r\n"; - + "Content-Disposition: form-data; name=\"fileName\"\r\n" + + "Content-Type: text/plain; charset=US-ASCII\r\n" + + "Content-Transfer-Encoding: 8bit\r\n" + + "\r\n" + + "abc\r\n" + + "--\r\n" + + "Content-Disposition: form-data; name=\"desc\"\r\n" + + "Content-Type: text/plain; charset=US-ASCII\r\n" + + "Content-Transfer-Encoding: 8bit\r\n" + + "\r\n" + + "123\r\n" + + "--\r\n" + + "Content-Disposition: form-data; name=\"title\"\r\n" + + "Content-Type: text/plain; charset=US-ASCII\r\n" + + "Content-Transfer-Encoding: 8bit\r\n" + + "\r\n" + + "ttt\r\n" + + "--\r\n" + + "Content-Disposition: form-data; name=\"datafile5239138112980980385.txt\"; filename=\"datafile5239138112980980385.txt\"\r\n" + + "Content-Type: application/octet-stream; charset=ISO-8859-1\r\n" + + "Content-Transfer-Encoding: binary\r\n" + + "\r\n" + + "000\r\n" + + "----\r\n"; + MultipartConfigElement config = new MultipartConfigElement(_dirname, 1024, 3072, 50); MultiPartFormInputStream mpis = new MultiPartFormInputStream(new ByteArrayInputStream(str.getBytes()), - "multipart/form-data", - config, - _tmpDir); + "multipart/form-data", + config, + _tmpDir); mpis.setDeleteOnExit(true); Collection parts = mpis.getParts(); assertThat(parts.size(), is(4)); - + ByteArrayOutputStream baos = new ByteArrayOutputStream(); Part fileName = mpis.getPart("fileName"); assertThat(fileName, notNullValue()); @@ -193,7 +190,7 @@ public class MultiPartFormInputStreamTest assertThat(desc.getSize(), is(3L)); IO.copy(desc.getInputStream(), baos); assertThat(baos.toString("US-ASCII"), is("123")); - + baos = new ByteArrayOutputStream(); Part title = mpis.getPart("title"); assertThat(title, notNullValue()); @@ -204,38 +201,37 @@ public class MultiPartFormInputStreamTest @Test public void testNonMultiPartRequest() - throws Exception + throws Exception { MultipartConfigElement config = new MultipartConfigElement(_dirname, 1024, 3072, 50); MultiPartFormInputStream mpis = new MultiPartFormInputStream(new ByteArrayInputStream(_multi.getBytes()), - "Content-type: text/plain", - config, - _tmpDir); + "Content-type: text/plain", + config, + _tmpDir); mpis.setDeleteOnExit(true); assertTrue(mpis.getParts().isEmpty()); } @Test public void testNoBody() - throws Exception + throws Exception { String body = ""; MultipartConfigElement config = new MultipartConfigElement(_dirname, 1024, 3072, 50); MultiPartFormInputStream mpis = new MultiPartFormInputStream(new ByteArrayInputStream(body.getBytes()), - _contentType, - config, - _tmpDir); + _contentType, + config, + _tmpDir); mpis.setDeleteOnExit(true); - IOException x = assertThrows(IOException.class, ()-> mpis.getParts()); + IOException x = assertThrows(IOException.class, () -> mpis.getParts()); assertThat(x.getMessage(), containsString("Missing initial multi part boundary")); } - - + @Test public void testBodyAlreadyConsumed() - throws Exception + throws Exception { ServletInputStream is = new ServletInputStream() { @@ -262,81 +258,78 @@ public class MultiPartFormInputStreamTest { return 0; } - }; - + MultipartConfigElement config = new MultipartConfigElement(_dirname, 1024, 3072, 50); MultiPartFormInputStream mpis = new MultiPartFormInputStream(is, - _contentType, - config, - _tmpDir); + _contentType, + config, + _tmpDir); mpis.setDeleteOnExit(true); Collection parts = mpis.getParts(); assertEquals(0, parts.size()); } - @Test public void testWhitespaceBodyWithCRLF() - throws Exception + throws Exception { String whitespace = " \n\n\n\r\n\r\n\r\n\r\n"; MultipartConfigElement config = new MultipartConfigElement(_dirname, 1024, 3072, 50); MultiPartFormInputStream mpis = new MultiPartFormInputStream(new ByteArrayInputStream(whitespace.getBytes()), - _contentType, - config, - _tmpDir); + _contentType, + config, + _tmpDir); mpis.setDeleteOnExit(true); - IOException x = assertThrows(IOException.class, ()-> mpis.getParts()); + IOException x = assertThrows(IOException.class, () -> mpis.getParts()); assertThat(x.getMessage(), containsString("Missing initial multi part boundary")); } @Test public void testWhitespaceBody() - throws Exception + throws Exception { String whitespace = " "; MultipartConfigElement config = new MultipartConfigElement(_dirname, 1024, 3072, 50); MultiPartFormInputStream mpis = new MultiPartFormInputStream(new ByteArrayInputStream(whitespace.getBytes()), - _contentType, - config, - _tmpDir); + _contentType, + config, + _tmpDir); mpis.setDeleteOnExit(true); - IOException x = assertThrows(IOException.class, ()-> mpis.getParts()); + IOException x = assertThrows(IOException.class, () -> mpis.getParts()); assertThat(x.getMessage(), containsString("Missing initial")); } @Test public void testLeadingWhitespaceBodyWithCRLF() - throws Exception + throws Exception { String body = " \n\n\n\r\n\r\n\r\n\r\n" + - "--AaB03x\r\n" + - "content-disposition: form-data; name=\"field1\"\r\n" + - "\r\n" + - "Joe Blow\r\n" + - "--AaB03x\r\n" + - "content-disposition: form-data; name=\"stuff\"; filename=\"" + "foo.txt" + "\"\r\n" + - "Content-Type: text/plain\r\n" + - "\r\n" + "aaaa" + - "bbbbb" + "\r\n" + - "--AaB03x--\r\n"; - + "--AaB03x\r\n" + + "content-disposition: form-data; name=\"field1\"\r\n" + + "\r\n" + + "Joe Blow\r\n" + + "--AaB03x\r\n" + + "content-disposition: form-data; name=\"stuff\"; filename=\"" + "foo.txt" + "\"\r\n" + + "Content-Type: text/plain\r\n" + + "\r\n" + "aaaa" + + "bbbbb" + "\r\n" + + "--AaB03x--\r\n"; MultipartConfigElement config = new MultipartConfigElement(_dirname, 1024, 3072, 50); MultiPartFormInputStream mpis = new MultiPartFormInputStream(new ByteArrayInputStream(body.getBytes()), - _contentType, - config, - _tmpDir); + _contentType, + config, + _tmpDir); mpis.setDeleteOnExit(true); Collection parts = mpis.getParts(); assertThat(parts, notNullValue()); assertThat(parts.size(), is(2)); - try(ByteArrayOutputStream baos = new ByteArrayOutputStream()) + try (ByteArrayOutputStream baos = new ByteArrayOutputStream()) { Part field1 = mpis.getPart("field1"); assertThat(field1, notNullValue()); @@ -344,7 +337,7 @@ public class MultiPartFormInputStreamTest assertThat(baos.toString("US-ASCII"), is("Joe Blow")); } - try(ByteArrayOutputStream baos = new ByteArrayOutputStream()) + try (ByteArrayOutputStream baos = new ByteArrayOutputStream()) { Part stuff = mpis.getPart("stuff"); assertThat(stuff, notNullValue()); @@ -352,28 +345,27 @@ public class MultiPartFormInputStreamTest assertThat(baos.toString("US-ASCII"), containsString("aaaa")); } } - @Test public void testLeadingWhitespaceBodyWithoutCRLF() throws Exception { - String body = " "+ - "--AaB03x\r\n"+ - "content-disposition: form-data; name=\"field1\"\r\n"+ - "\r\n"+ - "Joe Blow\r\n"+ - "--AaB03x\r\n"+ - "content-disposition: form-data; name=\"stuff\"; filename=\"" + "foo.txt" + "\"\r\n"+ - "Content-Type: text/plain\r\n"+ - "\r\n"+"aaaa"+ - "bbbbb"+"\r\n" + - "--AaB03x--\r\n"; + String body = " " + + "--AaB03x\r\n" + + "content-disposition: form-data; name=\"field1\"\r\n" + + "\r\n" + + "Joe Blow\r\n" + + "--AaB03x\r\n" + + "content-disposition: form-data; name=\"stuff\"; filename=\"" + "foo.txt" + "\"\r\n" + + "Content-Type: text/plain\r\n" + + "\r\n" + "aaaa" + + "bbbbb" + "\r\n" + + "--AaB03x--\r\n"; MultipartConfigElement config = new MultipartConfigElement(_dirname, 1024, 3072, 50); MultiPartFormInputStream mpis = new MultiPartFormInputStream(new ByteArrayInputStream(body.getBytes()), - _contentType, - config, - _tmpDir); + _contentType, + config, + _tmpDir); mpis.setDeleteOnExit(true); Collection parts = mpis.getParts(); @@ -389,90 +381,89 @@ public class MultiPartFormInputStreamTest @Test public void testNoLimits() - throws Exception + throws Exception { MultipartConfigElement config = new MultipartConfigElement(_dirname); MultiPartFormInputStream mpis = new MultiPartFormInputStream(new ByteArrayInputStream(_multi.getBytes()), - _contentType, - config, - _tmpDir); + _contentType, + config, + _tmpDir); mpis.setDeleteOnExit(true); Collection parts = mpis.getParts(); assertFalse(parts.isEmpty()); } @Test - public void testRequestTooBig () - throws Exception + public void testRequestTooBig() + throws Exception { MultipartConfigElement config = new MultipartConfigElement(_dirname, 60, 100, 50); MultiPartFormInputStream mpis = new MultiPartFormInputStream(new ByteArrayInputStream(_multi.getBytes()), - _contentType, - config, - _tmpDir); + _contentType, + config, + _tmpDir); mpis.setDeleteOnExit(true); - IllegalStateException x = assertThrows(IllegalStateException.class, ()-> mpis.getParts()); + IllegalStateException x = assertThrows(IllegalStateException.class, () -> mpis.getParts()); assertThat(x.getMessage(), containsString("Request exceeds maxRequestSize")); } - - + @Test - public void testRequestTooBigThrowsErrorOnGetParts () - throws Exception + public void testRequestTooBigThrowsErrorOnGetParts() + throws Exception { MultipartConfigElement config = new MultipartConfigElement(_dirname, 60, 100, 50); MultiPartFormInputStream mpis = new MultiPartFormInputStream(new ByteArrayInputStream(_multi.getBytes()), - _contentType, - config, - _tmpDir); + _contentType, + config, + _tmpDir); mpis.setDeleteOnExit(true); //cause parsing - IllegalStateException x = assertThrows(IllegalStateException.class, ()-> mpis.getParts()); + IllegalStateException x = assertThrows(IllegalStateException.class, () -> mpis.getParts()); assertThat(x.getMessage(), containsString("Request exceeds maxRequestSize")); //try again - x = assertThrows(IllegalStateException.class, ()-> mpis.getParts()); + x = assertThrows(IllegalStateException.class, () -> mpis.getParts()); assertThat(x.getMessage(), containsString("Request exceeds maxRequestSize")); } @Test public void testFileTooBig() - throws Exception + throws Exception { MultipartConfigElement config = new MultipartConfigElement(_dirname, 40, 1024, 30); MultiPartFormInputStream mpis = new MultiPartFormInputStream(new ByteArrayInputStream(_multi.getBytes()), - _contentType, - config, - _tmpDir); + _contentType, + config, + _tmpDir); mpis.setDeleteOnExit(true); IllegalStateException x = assertThrows(IllegalStateException.class, - ()-> mpis.getParts(), - "stuff.txt should have been larger than maxFileSize"); + () -> mpis.getParts(), + "stuff.txt should have been larger than maxFileSize"); assertThat(x.getMessage(), startsWith("Multipart Mime part")); } - + @Test public void testFileTooBigThrowsErrorOnGetParts() - throws Exception + throws Exception { MultipartConfigElement config = new MultipartConfigElement(_dirname, 40, 1024, 30); MultiPartFormInputStream mpis = new MultiPartFormInputStream(new ByteArrayInputStream(_multi.getBytes()), - _contentType, - config, - _tmpDir); + _contentType, + config, + _tmpDir); mpis.setDeleteOnExit(true); // Caused parsing IllegalStateException x = assertThrows(IllegalStateException.class, - ()-> mpis.getParts(), - "stuff.txt should have been larger than maxFileSize"); + () -> mpis.getParts(), + "stuff.txt should have been larger than maxFileSize"); assertThat(x.getMessage(), startsWith("Multipart Mime part")); //test again after the parsing x = assertThrows(IllegalStateException.class, - ()-> mpis.getParts(), - "stuff.txt should have been larger than maxFileSize"); + () -> mpis.getParts(), + "stuff.txt should have been larger than maxFileSize"); assertThat(x.getMessage(), startsWith("Multipart Mime part")); } @@ -481,12 +472,12 @@ public class MultiPartFormInputStreamTest { MultipartConfigElement config = new MultipartConfigElement(_dirname, 1024, 3072, 50); MultiPartFormInputStream mpis = new MultiPartFormInputStream(new ByteArrayInputStream(createMultipartRequestString("tptfd").getBytes()), - _contentType, - config, - _tmpDir); + _contentType, + config, + _tmpDir); mpis.setDeleteOnExit(true); mpis.getParts(); - + MultiPart part = (MultiPart)mpis.getPart("stuff"); File stuff = part.getFile(); assertThat(stuff, notNullValue()); // longer than 100 bytes, should already be a tmp file @@ -498,15 +489,15 @@ public class MultiPartFormInputStreamTest assertThat(tptfd.exists(), is(true)); //explicitly written file did not get removed after cleanup tptfd.deleteOnExit(); //clean up test } - + @Test public void testPartTmpFileDeletion() throws Exception { MultipartConfigElement config = new MultipartConfigElement(_dirname, 1024, 3072, 50); MultiPartFormInputStream mpis = new MultiPartFormInputStream(new ByteArrayInputStream(createMultipartRequestString("tptfd").getBytes()), - _contentType, - config, - _tmpDir); + _contentType, + config, + _tmpDir); mpis.setDeleteOnExit(true); mpis.getParts(); @@ -517,26 +508,26 @@ public class MultiPartFormInputStreamTest part.cleanUp(); assertThat(stuff.exists(), is(false)); //tmp file was removed after cleanup } - + @Test public void testLFOnlyRequest() - throws Exception + throws Exception { String str = "--AaB03x\n" + - "content-disposition: form-data; name=\"field1\"\n" + - "\n" + - "Joe Blow" + - "\r\n--AaB03x\n" + - "content-disposition: form-data; name=\"field2\"\n" + - "\n" + - "Other" + - "\r\n--AaB03x--\n"; + "content-disposition: form-data; name=\"field1\"\n" + + "\n" + + "Joe Blow" + + "\r\n--AaB03x\n" + + "content-disposition: form-data; name=\"field2\"\n" + + "\n" + + "Other" + + "\r\n--AaB03x--\n"; MultipartConfigElement config = new MultipartConfigElement(_dirname, 1024, 3072, 50); MultiPartFormInputStream mpis = new MultiPartFormInputStream(new ByteArrayInputStream(str.getBytes()), - _contentType, - config, - _tmpDir); + _contentType, + config, + _tmpDir); mpis.setDeleteOnExit(true); Collection parts = mpis.getParts(); assertThat(parts.size(), is(2)); @@ -551,65 +542,63 @@ public class MultiPartFormInputStreamTest baos = new ByteArrayOutputStream(); IO.copy(p2.getInputStream(), baos); assertThat(baos.toString("UTF-8"), is("Other")); - - } - + @Test public void testCROnlyRequest() - throws Exception + throws Exception { String str = "--AaB03x\r" + - "content-disposition: form-data; name=\"field1\"\r" + - "\r" + - "Joe Blow\r" + - "--AaB03x\r" + - "content-disposition: form-data; name=\"field2\"\r" + - "\r" + - "Other\r" + - "--AaB03x--\r"; + "content-disposition: form-data; name=\"field1\"\r" + + "\r" + + "Joe Blow\r" + + "--AaB03x\r" + + "content-disposition: form-data; name=\"field2\"\r" + + "\r" + + "Other\r" + + "--AaB03x--\r"; MultipartConfigElement config = new MultipartConfigElement(_dirname, 1024, 3072, 50); MultiPartFormInputStream mpis = new MultiPartFormInputStream(new ByteArrayInputStream(str.getBytes()), - _contentType, - config, - _tmpDir); + _contentType, + config, + _tmpDir); mpis.setDeleteOnExit(true); IllegalStateException x = assertThrows(IllegalStateException.class, - ()-> mpis.getParts(), - "Improper EOL"); + () -> mpis.getParts(), + "Improper EOL"); assertThat(x.getMessage(), containsString("Bad EOL")); } @Test public void testCRandLFMixRequest() - throws Exception + throws Exception { String str = "--AaB03x\r" + - "content-disposition: form-data; name=\"field1\"\r" + - "\r" + - "\nJoe Blow\n" + - "\r" + - "--AaB03x\r" + - "content-disposition: form-data; name=\"field2\"\r" + - "\r" + - "Other\r" + - "--AaB03x--\r"; - + "content-disposition: form-data; name=\"field1\"\r" + + "\r" + + "\nJoe Blow\n" + + "\r" + + "--AaB03x\r" + + "content-disposition: form-data; name=\"field2\"\r" + + "\r" + + "Other\r" + + "--AaB03x--\r"; + MultipartConfigElement config = new MultipartConfigElement(_dirname, 1024, 3072, 50); MultiPartFormInputStream mpis = new MultiPartFormInputStream(new ByteArrayInputStream(str.getBytes()), - _contentType, - config, - _tmpDir); + _contentType, + config, + _tmpDir); mpis.setDeleteOnExit(true); IllegalStateException x = assertThrows(IllegalStateException.class, - ()-> mpis.getParts(), - "Improper EOL"); + () -> mpis.getParts(), + "Improper EOL"); assertThat(x.getMessage(), containsString("Bad EOL")); } - + @Test public void testBufferOverflowNoCRLF() throws Exception { @@ -619,79 +608,78 @@ public class MultiPartFormInputStreamTest { baos.write('a'); } - + MultipartConfigElement config = new MultipartConfigElement(_dirname, 1024, 3072, 50); MultiPartFormInputStream mpis = new MultiPartFormInputStream(new ByteArrayInputStream(baos.toByteArray()), - _contentType, - config, - _tmpDir); + _contentType, + config, + _tmpDir); mpis.setDeleteOnExit(true); IllegalStateException x = assertThrows(IllegalStateException.class, - ()-> mpis.getParts(), - "Header Line Exceeded Max Length"); + () -> mpis.getParts(), + "Header Line Exceeded Max Length"); assertThat(x.getMessage(), containsString("Header Line Exceeded Max Length")); } - + @Test public void testCharsetEncoding() throws Exception { String contentType = "multipart/form-data; boundary=TheBoundary; charset=ISO-8859-1"; String str = "--TheBoundary\r\n" + - "content-disposition: form-data; name=\"field1\"\r\n" + - "\r\n" + - "\nJoe Blow\n" + - "\r\n" + - "--TheBoundary--\r\n"; - + "content-disposition: form-data; name=\"field1\"\r\n" + + "\r\n" + + "\nJoe Blow\n" + + "\r\n" + + "--TheBoundary--\r\n"; + MultipartConfigElement config = new MultipartConfigElement(_dirname, 1024, 3072, 50); MultiPartFormInputStream mpis = new MultiPartFormInputStream(new ByteArrayInputStream(str.getBytes()), - contentType, - config, - _tmpDir); + contentType, + config, + _tmpDir); mpis.setDeleteOnExit(true); Collection parts = mpis.getParts(); assertThat(parts.size(), is(1)); } - - + @Test public void testBadlyEncodedFilename() throws Exception { - + String contents = "--AaB03x\r\n" + - "content-disposition: form-data; name=\"stuff\"; filename=\"" + "Taken on Aug 22 \\ 2012.jpg" + "\"\r\n" + - "Content-Type: text/plain\r\n" + - "\r\n" + "stuff" + - "aaa" + "\r\n" + - "--AaB03x--\r\n"; - + "content-disposition: form-data; name=\"stuff\"; filename=\"" + "Taken on Aug 22 \\ 2012.jpg" + "\"\r\n" + + "Content-Type: text/plain\r\n" + + "\r\n" + "stuff" + + "aaa" + "\r\n" + + "--AaB03x--\r\n"; + MultipartConfigElement config = new MultipartConfigElement(_dirname, 1024, 3072, 50); MultiPartFormInputStream mpis = new MultiPartFormInputStream(new ByteArrayInputStream(contents.getBytes()), - _contentType, - config, - _tmpDir); + _contentType, + config, + _tmpDir); mpis.setDeleteOnExit(true); Collection parts = mpis.getParts(); assertThat(parts.size(), is(1)); assertThat(parts.iterator().next().getSubmittedFileName(), is("Taken on Aug 22 \\ 2012.jpg")); } - + @Test public void testBadlyEncodedMSFilename() throws Exception { - + String contents = "--AaB03x\r\n" + - "content-disposition: form-data; name=\"stuff\"; filename=\"" + "c:\\this\\really\\is\\some\\path\\to\\a\\file.txt" + "\"\r\n" + - "Content-Type: text/plain\r\n" + - "\r\n" + "stuff" + - "aaa" + "\r\n" + - "--AaB03x--\r\n"; - + "content-disposition: form-data; name=\"stuff\"; filename=\"" + "c:\\this\\really\\is\\some\\path\\to\\a\\file.txt" + "\"\r\n" + + "Content-Type: text/plain\r\n" + + "\r\n" + "stuff" + + "aaa" + "\r\n" + + "--AaB03x--\r\n"; + MultipartConfigElement config = new MultipartConfigElement(_dirname, 1024, 3072, 50); MultiPartFormInputStream mpis = new MultiPartFormInputStream(new ByteArrayInputStream(contents.getBytes()), - _contentType, - config, - _tmpDir); + _contentType, + config, + _tmpDir); mpis.setDeleteOnExit(true); Collection parts = mpis.getParts(); assertThat(parts.size(), is(1)); @@ -702,17 +690,17 @@ public class MultiPartFormInputStreamTest public void testCorrectlyEncodedMSFilename() throws Exception { String contents = "--AaB03x\r\n" + - "content-disposition: form-data; name=\"stuff\"; filename=\"" + "c:\\\\this\\\\really\\\\is\\\\some\\\\path\\\\to\\\\a\\\\file.txt" + "\"\r\n" + - "Content-Type: text/plain\r\n" + - "\r\n" + "stuff" + - "aaa" + "\r\n" + - "--AaB03x--\r\n"; - + "content-disposition: form-data; name=\"stuff\"; filename=\"" + "c:\\\\this\\\\really\\\\is\\\\some\\\\path\\\\to\\\\a\\\\file.txt" + "\"\r\n" + + "Content-Type: text/plain\r\n" + + "\r\n" + "stuff" + + "aaa" + "\r\n" + + "--AaB03x--\r\n"; + MultipartConfigElement config = new MultipartConfigElement(_dirname, 1024, 3072, 50); MultiPartFormInputStream mpis = new MultiPartFormInputStream(new ByteArrayInputStream(contents.getBytes()), - _contentType, - config, - _tmpDir); + _contentType, + config, + _tmpDir); mpis.setDeleteOnExit(true); Collection parts = mpis.getParts(); assertThat(parts.size(), is(1)); @@ -725,27 +713,26 @@ public class MultiPartFormInputStreamTest testMulti("stuff with spaces.txt"); } - @Test public void testWriteFilesIfContentDispositionFilename() - throws Exception + throws Exception { String s = "--AaB03x\r\n" + - "content-disposition: form-data; name=\"field1\"; filename=\"frooble.txt\"\r\n" + - "\r\n" + - "Joe Blow\r\n" + - "--AaB03x\r\n" + - "content-disposition: form-data; name=\"stuff\"\r\n" + - "Content-Type: text/plain\r\n" + - "\r\n" + "sss" + - "aaa" + "\r\n" + - "--AaB03x--\r\n"; + "content-disposition: form-data; name=\"field1\"; filename=\"frooble.txt\"\r\n" + + "\r\n" + + "Joe Blow\r\n" + + "--AaB03x\r\n" + + "content-disposition: form-data; name=\"stuff\"\r\n" + + "Content-Type: text/plain\r\n" + + "\r\n" + "sss" + + "aaa" + "\r\n" + + "--AaB03x--\r\n"; //all default values for multipartconfig, ie file size threshold 0 MultipartConfigElement config = new MultipartConfigElement(_dirname); MultiPartFormInputStream mpis = new MultiPartFormInputStream(new ByteArrayInputStream(s.getBytes()), - _contentType, - config, - _tmpDir); + _contentType, + config, + _tmpDir); mpis.setDeleteOnExit(true); mpis.setWriteFilesWithFilenames(true); Collection parts = mpis.getParts(); @@ -753,20 +740,19 @@ public class MultiPartFormInputStreamTest Part field1 = mpis.getPart("field1"); //has a filename, should be written to a file File f = ((MultiPartFormInputStream.MultiPart)field1).getFile(); assertThat(f, notNullValue()); // longer than 100 bytes, should already be a tmp file - + Part stuff = mpis.getPart("stuff"); f = ((MultiPartFormInputStream.MultiPart)stuff).getFile(); //should only be in memory, no filename assertThat(f, nullValue()); } - - + private void testMulti(String filename) throws IOException { MultipartConfigElement config = new MultipartConfigElement(_dirname, 1024, 3072, 50); MultiPartFormInputStream mpis = new MultiPartFormInputStream(new ByteArrayInputStream(createMultipartRequestString(filename).getBytes()), - _contentType, - config, - _tmpDir); + _contentType, + config, + _tmpDir); mpis.setDeleteOnExit(true); Collection parts = mpis.getParts(); assertThat(parts.size(), is(2)); @@ -803,7 +789,7 @@ public class MultiPartFormInputStreamTest assertThat(stuff.getHeader("content-disposition"), is("form-data; name=\"stuff\"; filename=\"" + filename + "\"")); assertThat(stuff.getHeaderNames().size(), is(2)); assertThat(stuff.getSize(), is(51L)); - + File tmpfile = stuff.getFile(); assertThat(tmpfile, notNullValue()); // longer than 50 bytes, should already be a tmp file assertThat(stuff.getBytes(), nullValue()); //not in an internal buffer @@ -826,30 +812,32 @@ public class MultiPartFormInputStreamTest @Test public void testMultiSameNames() - throws Exception + throws Exception { String sameNames = "--AaB03x\r\n" + - "content-disposition: form-data; name=\"stuff\"; filename=\"stuff1.txt\"\r\n" + - "Content-Type: text/plain\r\n" + - "\r\n" + - "00000\r\n" + - "--AaB03x\r\n" + - "content-disposition: form-data; name=\"stuff\"; filename=\"stuff2.txt\"\r\n" + - "Content-Type: text/plain\r\n" + - "\r\n" + - "110000000000000000000000000000000000000000000000000\r\n" + - "--AaB03x--\r\n"; + "content-disposition: form-data; name=\"stuff\"; filename=\"stuff1.txt\"\r\n" + + "Content-Type: text/plain\r\n" + + "\r\n" + + "00000\r\n" + + "--AaB03x\r\n" + + "content-disposition: form-data; name=\"stuff\"; filename=\"stuff2.txt\"\r\n" + + "Content-Type: text/plain\r\n" + + "\r\n" + + "110000000000000000000000000000000000000000000000000\r\n" + + "--AaB03x--\r\n"; MultipartConfigElement config = new MultipartConfigElement(_dirname, 1024, 3072, 50); MultiPartFormInputStream mpis = new MultiPartFormInputStream(new ByteArrayInputStream(sameNames.getBytes()), - _contentType, - config, - _tmpDir); + _contentType, + config, + _tmpDir); mpis.setDeleteOnExit(true); Collection parts = mpis.getParts(); assertEquals(2, parts.size()); for (Part p : parts) + { assertEquals("stuff", p.getName()); + } //if they all have the name name, then only retrieve the first one Part p = mpis.getPart("stuff"); @@ -861,29 +849,29 @@ public class MultiPartFormInputStreamTest public void testBase64EncodedContent() throws Exception { String contentWithEncodedPart = + "--AaB03x\r\n" + + "Content-disposition: form-data; name=\"other\"\r\n" + + "Content-Type: text/plain\r\n" + + "\r\n" + + "other" + "\r\n" + "--AaB03x\r\n" + - "Content-disposition: form-data; name=\"other\"\r\n" + - "Content-Type: text/plain\r\n" + - "\r\n" + - "other" + "\r\n" + - "--AaB03x\r\n" + - "Content-disposition: form-data; name=\"stuff\"; filename=\"stuff.txt\"\r\n" + - "Content-Transfer-Encoding: base64\r\n" + - "Content-Type: application/octet-stream\r\n" + - "\r\n" + - Base64.getEncoder().encodeToString("hello jetty".getBytes(ISO_8859_1)) + "\r\n" + - "--AaB03x\r\n" + - "Content-disposition: form-data; name=\"final\"\r\n" + - "Content-Type: text/plain\r\n" + - "\r\n" + - "the end" + "\r\n" + - "--AaB03x--\r\n"; + "Content-disposition: form-data; name=\"stuff\"; filename=\"stuff.txt\"\r\n" + + "Content-Transfer-Encoding: base64\r\n" + + "Content-Type: application/octet-stream\r\n" + + "\r\n" + + Base64.getEncoder().encodeToString("hello jetty".getBytes(ISO_8859_1)) + "\r\n" + + "--AaB03x\r\n" + + "Content-disposition: form-data; name=\"final\"\r\n" + + "Content-Type: text/plain\r\n" + + "\r\n" + + "the end" + "\r\n" + + "--AaB03x--\r\n"; MultipartConfigElement config = new MultipartConfigElement(_dirname, 1024, 3072, 50); MultiPartFormInputStream mpis = new MultiPartFormInputStream(new ByteArrayInputStream(contentWithEncodedPart.getBytes()), - _contentType, - config, - _tmpDir); + _contentType, + config, + _tmpDir); mpis.setDeleteOnExit(true); Collection parts = mpis.getParts(); assertEquals(3, parts.size()); @@ -899,35 +887,35 @@ public class MultiPartFormInputStreamTest baos = new ByteArrayOutputStream(); IO.copy(p2.getInputStream(), baos); assertEquals(Base64.getEncoder().encodeToString("hello jetty".getBytes(ISO_8859_1)), baos.toString("US-ASCII")); - + Part p3 = mpis.getPart("final"); assertNotNull(p3); baos = new ByteArrayOutputStream(); IO.copy(p3.getInputStream(), baos); assertEquals("the end", baos.toString("US-ASCII")); } - + @Test public void testQuotedPrintableEncoding() throws Exception { String contentWithEncodedPart = + "--AaB03x\r\n" + + "Content-disposition: form-data; name=\"other\"\r\n" + + "Content-Type: text/plain\r\n" + + "\r\n" + + "other" + "\r\n" + "--AaB03x\r\n" + - "Content-disposition: form-data; name=\"other\"\r\n" + - "Content-Type: text/plain\r\n" + - "\r\n" + - "other" + "\r\n" + - "--AaB03x\r\n" + - "Content-disposition: form-data; name=\"stuff\"; filename=\"stuff.txt\"\r\n" + - "Content-Transfer-Encoding: quoted-printable\r\n" + - "Content-Type: text/plain\r\n" + - "\r\n" + - "truth=3Dbeauty" + "\r\n" + - "--AaB03x--\r\n"; + "Content-disposition: form-data; name=\"stuff\"; filename=\"stuff.txt\"\r\n" + + "Content-Transfer-Encoding: quoted-printable\r\n" + + "Content-Type: text/plain\r\n" + + "\r\n" + + "truth=3Dbeauty" + "\r\n" + + "--AaB03x--\r\n"; MultipartConfigElement config = new MultipartConfigElement(_dirname, 1024, 3072, 50); MultiPartFormInputStream mpis = new MultiPartFormInputStream(new ByteArrayInputStream(contentWithEncodedPart.getBytes()), - _contentType, - config, - _tmpDir); + _contentType, + config, + _tmpDir); mpis.setDeleteOnExit(true); Collection parts = mpis.getParts(); assertEquals(2, parts.size()); @@ -945,43 +933,40 @@ public class MultiPartFormInputStreamTest assertEquals("truth=3Dbeauty", baos.toString("US-ASCII")); } - @Test public void testGeneratedForm() - throws Exception + throws Exception { String contentType = "multipart/form-data, boundary=WebKitFormBoundary7MA4YWf7OaKlSxkTrZu0gW"; String body = "Content-Type: multipart/form-data; boundary=WebKitFormBoundary7MA4YWf7OaKlSxkTrZu0gW\r\n" + - "\r\n" + - "--WebKitFormBoundary7MA4YWf7OaKlSxkTrZu0gW\r\n" + - "Content-Disposition: form-data; name=\"part1\"\r\n" + - "\n" + - "wNfミxVam﾿t\r\n" + - "--WebKitFormBoundary7MA4YWf7OaKlSxkTrZu0gW\n" + - "Content-Disposition: form-data; name=\"part2\"\r\n" + - "\r\n" + - "&ᄈᄎ￙ᅱᅢO\r\n" + - "--WebKitFormBoundary7MA4YWf7OaKlSxkTrZu0gW--"; - + "\r\n" + + "--WebKitFormBoundary7MA4YWf7OaKlSxkTrZu0gW\r\n" + + "Content-Disposition: form-data; name=\"part1\"\r\n" + + "\n" + + "wNfミxVam﾿t\r\n" + + "--WebKitFormBoundary7MA4YWf7OaKlSxkTrZu0gW\n" + + "Content-Disposition: form-data; name=\"part2\"\r\n" + + "\r\n" + + "&ᄈᄎ￙ᅱᅢO\r\n" + + "--WebKitFormBoundary7MA4YWf7OaKlSxkTrZu0gW--"; MultipartConfigElement config = new MultipartConfigElement(_dirname, 1024, 3072, 50); MultiPartFormInputStream mpis = new MultiPartFormInputStream(new ByteArrayInputStream(body.getBytes()), - contentType, - config, - _tmpDir); + contentType, + config, + _tmpDir); mpis.setDeleteOnExit(true); Collection parts = mpis.getParts(); assertThat(parts, notNullValue()); assertThat(parts.size(), is(2)); - + Part part1 = mpis.getPart("part1"); assertThat(part1, notNullValue()); Part part2 = mpis.getPart("part2"); assertThat(part2, notNullValue()); } - private static String createMultipartRequestString(String filename) { int length = filename.length(); @@ -995,16 +980,16 @@ public class MultiPartFormInputStreamTest filler.append("0"); i++; } - + return "--AaB03x\r\n" + - "content-disposition: form-data; name=\"field1\"; filename=\"frooble.txt\"\r\n" + - "\r\n" + - "Joe Blow\r\n" + - "--AaB03x\r\n" + - "content-disposition: form-data; name=\"stuff\"; filename=\"" + filename + "\"\r\n" + - "Content-Type: text/plain\r\n" + - "\r\n" + name + - filler.toString() + "\r\n" + - "--AaB03x--\r\n"; + "content-disposition: form-data; name=\"field1\"; filename=\"frooble.txt\"\r\n" + + "\r\n" + + "Joe Blow\r\n" + + "--AaB03x\r\n" + + "content-disposition: form-data; name=\"stuff\"; filename=\"" + filename + "\"\r\n" + + "Content-Type: text/plain\r\n" + + "\r\n" + name + + filler.toString() + "\r\n" + + "--AaB03x--\r\n"; } } diff --git a/jetty-http/src/test/java/org/eclipse/jetty/http/MultiPartParserTest.java b/jetty-http/src/test/java/org/eclipse/jetty/http/MultiPartParserTest.java index 1e3010d9bfb..a9502116c1d 100644 --- a/jetty-http/src/test/java/org/eclipse/jetty/http/MultiPartParserTest.java +++ b/jetty-http/src/test/java/org/eclipse/jetty/http/MultiPartParserTest.java @@ -18,12 +18,6 @@ package org.eclipse.jetty.http; -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.containsString; -import static org.hamcrest.Matchers.is; -import static org.junit.jupiter.api.Assertions.assertThrows; -import static org.junit.jupiter.api.Assertions.assertTrue; - import java.nio.ByteBuffer; import java.util.ArrayList; import java.util.List; @@ -34,6 +28,12 @@ import org.eclipse.jetty.util.BufferUtil; import org.hamcrest.Matchers; import org.junit.jupiter.api.Test; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.containsString; +import static org.hamcrest.Matchers.is; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + public class MultiPartParserTest { @@ -44,7 +44,7 @@ public class MultiPartParserTest { }, "BOUNDARY"); ByteBuffer data = BufferUtil.toBuffer(""); - + parser.parse(data, false); assertThat(parser.getState(), is(State.PREAMBLE)); } @@ -56,12 +56,12 @@ public class MultiPartParserTest { }, "BOUNDARY"); ByteBuffer data = BufferUtil.toBuffer("--BOUNDARY \r\n"); - + parser.parse(data, false); assertTrue(parser.isState(State.BODY_PART)); assertThat(data.remaining(), is(0)); } - + @Test public void testPreamble() { @@ -69,27 +69,27 @@ public class MultiPartParserTest { }, "BOUNDARY"); ByteBuffer data; - + data = BufferUtil.toBuffer("This is not part of a part\r\n"); parser.parse(data, false); assertThat(parser.getState(), is(State.PREAMBLE)); assertThat(data.remaining(), is(0)); - + data = BufferUtil.toBuffer("More data that almost includes \n--BOUNDARY but no CR before."); parser.parse(data, false); assertThat(parser.getState(), is(State.PREAMBLE)); assertThat(data.remaining(), is(0)); - + data = BufferUtil.toBuffer("Could be a boundary \r\n--BOUNDAR"); parser.parse(data, false); assertThat(parser.getState(), is(State.PREAMBLE)); assertThat(data.remaining(), is(0)); - + data = BufferUtil.toBuffer("but not it isn't \r\n--BOUN"); parser.parse(data, false); assertThat(parser.getState(), is(State.PREAMBLE)); assertThat(data.remaining(), is(0)); - + data = BufferUtil.toBuffer("DARX nor is this"); parser.parse(data, false); assertThat(parser.getState(), is(State.PREAMBLE)); @@ -103,12 +103,12 @@ public class MultiPartParserTest { }, "BOUNDARY"); ByteBuffer data = BufferUtil.toBuffer("This is not part of a part\r\n--BOUNDARY \r\n"); - + parser.parse(data, false); assertThat(parser.getState(), is(State.BODY_PART)); assertThat(data.remaining(), is(0)); } - + @Test public void testPreambleSplitBoundary() { @@ -153,12 +153,12 @@ public class MultiPartParserTest { }, "BOUNDARY"); ByteBuffer data = BufferUtil.toBuffer("--BOUNDARY\r\n\r\n"); - + parser.parse(data, false); assertThat(parser.getState(), is(State.FIRST_OCTETS)); assertThat(data.remaining(), is(0)); } - + @Test public void testFirstPartFields() { @@ -172,55 +172,54 @@ public class MultiPartParserTest } }; MultiPartParser parser = new MultiPartParser(handler, "BOUNDARY"); - + ByteBuffer data = BufferUtil.toBuffer("--BOUNDARY\r\n" - + "name0: value0\r\n" - + "name1 :value1 \r\n" - + "name2:value\r\n" - + " 2\r\n" - + "\r\n" - + "Content"); + + "name0: value0\r\n" + + "name1 :value1 \r\n" + + "name2:value\r\n" + + " 2\r\n" + + "\r\n" + + "Content"); parser.parse(data, false); assertThat(parser.getState(), is(State.FIRST_OCTETS)); assertThat(data.remaining(), is(7)); assertThat(handler.fields, Matchers.contains("name0: value0", "name1: value1", "name2: value 2", "<>")); } - + @Test public void testFirstPartNoContent() { TestHandler handler = new TestHandler(); MultiPartParser parser = new MultiPartParser(handler, "BOUNDARY"); - + ByteBuffer data = BufferUtil.toBuffer("--BOUNDARY\r\n" - + "name: value\r\n" - + "\r\n" - + "\r\n" - + "--BOUNDARY"); + + "name: value\r\n" + + "\r\n" + + "\r\n" + + "--BOUNDARY"); parser.parse(data, false); assertThat(parser.getState(), is(State.DELIMITER)); assertThat(data.remaining(), is(0)); assertThat(handler.fields, Matchers.contains("name: value", "<>")); assertThat(handler.content, Matchers.contains("<>")); } - + @Test public void testFirstPartNoContentNoCRLF() { TestHandler handler = new TestHandler(); MultiPartParser parser = new MultiPartParser(handler, "BOUNDARY"); - + ByteBuffer data = BufferUtil.toBuffer("--BOUNDARY\r\n" - + "name: value\r\n" - + "\r\n" - + "--BOUNDARY"); + + "name: value\r\n" + + "\r\n" + + "--BOUNDARY"); parser.parse(data, false); assertThat(parser.getState(), is(State.DELIMITER)); assertThat(data.remaining(), is(0)); assertThat(handler.fields, Matchers.contains("name: value", "<>")); assertThat(handler.content, Matchers.contains("<>")); - } @Test @@ -228,16 +227,15 @@ public class MultiPartParserTest { TestHandler handler = new TestHandler(); MultiPartParser parser = new MultiPartParser(handler, "BOUNDARY"); - + ByteBuffer data = BufferUtil.toBuffer("--BOUNDARY\r\n" - + "name: value\r\n" - + "\r\n" - + "-"); + + "name: value\r\n" + + "\r\n" + + "-"); parser.parse(data, false); data = BufferUtil.toBuffer("Content!"); parser.parse(data, false); - - + assertThat(parser.getState(), is(State.OCTETS)); assertThat(data.remaining(), is(0)); assertThat(handler.fields, Matchers.contains("name: value", "<>")); @@ -249,11 +247,11 @@ public class MultiPartParserTest { TestHandler handler = new TestHandler(); MultiPartParser parser = new MultiPartParser(handler, "BOUNDARY"); - + ByteBuffer data = BufferUtil.toBuffer("--BOUNDARY\r\n" - + "name: value\n" - + "\r\n" - + "Hello\r\n"); + + "name: value\n" + + "\r\n" + + "Hello\r\n"); parser.parse(data, false); assertThat(parser.getState(), is(State.OCTETS)); assertThat(data.remaining(), is(0)); @@ -261,18 +259,18 @@ public class MultiPartParserTest assertThat(handler.content, Matchers.contains("Hello")); data = BufferUtil.toBuffer( - "Now is the time for all good ment to come to the aid of the party.\r\n" - + "How now brown cow.\r\n" - + "The quick brown fox jumped over the lazy dog.\r\n" - + "this is not a --BOUNDARY\r\n"); + "Now is the time for all good ment to come to the aid of the party.\r\n" + + "How now brown cow.\r\n" + + "The quick brown fox jumped over the lazy dog.\r\n" + + "this is not a --BOUNDARY\r\n"); parser.parse(data, false); assertThat(parser.getState(), is(State.OCTETS)); assertThat(data.remaining(), is(0)); assertThat(handler.fields, Matchers.contains("name: value", "<>")); assertThat(handler.content, Matchers.contains("Hello", "\r\n", "Now is the time for all good ment to come to the aid of the party.\r\n" - + "How now brown cow.\r\n" - + "The quick brown fox jumped over the lazy dog.\r\n" - + "this is not a --BOUNDARY")); + + "How now brown cow.\r\n" + + "The quick brown fox jumped over the lazy dog.\r\n" + + "this is not a --BOUNDARY")); } @Test @@ -280,43 +278,42 @@ public class MultiPartParserTest { TestHandler handler = new TestHandler(); MultiPartParser parser = new MultiPartParser(handler, "BOUNDARY"); - + ByteBuffer data = BufferUtil.toBuffer("--BOUNDARY\r\n" - + "name: value\n" - + "\r\n" - + "Hello\r\n" - + "--BOUNDARY"); + + "name: value\n" + + "\r\n" + + "Hello\r\n" + + "--BOUNDARY"); parser.parse(data, false); assertThat(parser.getState(), is(State.DELIMITER)); assertThat(data.remaining(), is(0)); assertThat(handler.fields, Matchers.contains("name: value", "<>")); assertThat(handler.content, Matchers.contains("Hello", "<>")); } - @Test public void testFirstPartLongContent() { TestHandler handler = new TestHandler(); MultiPartParser parser = new MultiPartParser(handler, "BOUNDARY"); - + ByteBuffer data = BufferUtil.toBuffer("--BOUNDARY\r\n" - + "name: value\n" - + "\r\n" - + "Now is the time for all good ment to come to the aid of the party.\r\n" - + "How now brown cow.\r\n" - + "The quick brown fox jumped over the lazy dog.\r\n" - + "\r\n" - + "--BOUNDARY"); + + "name: value\n" + + "\r\n" + + "Now is the time for all good ment to come to the aid of the party.\r\n" + + "How now brown cow.\r\n" + + "The quick brown fox jumped over the lazy dog.\r\n" + + "\r\n" + + "--BOUNDARY"); parser.parse(data, false); assertThat(parser.getState(), is(State.DELIMITER)); assertThat(data.remaining(), is(0)); assertThat(handler.fields, Matchers.contains("name: value", "<>")); assertThat(handler.content, Matchers.contains("Now is the time for all good ment to come to the aid of the party.\r\n" - + "How now brown cow.\r\n" - + "The quick brown fox jumped over the lazy dog.\r\n", "<>")); + + "How now brown cow.\r\n" + + "The quick brown fox jumped over the lazy dog.\r\n", "<>")); } - + @Test public void testFirstPartLongContentNoCarriageReturn() { @@ -325,23 +322,22 @@ public class MultiPartParserTest //boundary still requires carriage return ByteBuffer data = BufferUtil.toBuffer("--BOUNDARY\n" - + "name: value\n" - + "\n" - + "Now is the time for all good men to come to the aid of the party.\n" - + "How now brown cow.\n" - + "The quick brown fox jumped over the lazy dog.\n" - + "\r\n" - + "--BOUNDARY"); + + "name: value\n" + + "\n" + + "Now is the time for all good men to come to the aid of the party.\n" + + "How now brown cow.\n" + + "The quick brown fox jumped over the lazy dog.\n" + + "\r\n" + + "--BOUNDARY"); parser.parse(data, false); assertThat(parser.getState(), is(State.DELIMITER)); assertThat(data.remaining(), is(0)); assertThat(handler.fields, Matchers.contains("name: value", "<>")); assertThat(handler.content, Matchers.contains("Now is the time for all good men to come to the aid of the party.\n" - + "How now brown cow.\n" - + "The quick brown fox jumped over the lazy dog.\n", "<>")); + + "How now brown cow.\n" + + "The quick brown fox jumped over the lazy dog.\n", "<>")); } - @Test public void testBinaryPart() { @@ -349,7 +345,7 @@ public class MultiPartParserTest final ByteBuffer bytes = BufferUtil.allocate(random.length); ThreadLocalRandom.current().nextBytes(random); // Arrays.fill(random,(byte)'X'); - + TestHandler handler = new TestHandler() { @Override @@ -360,89 +356,86 @@ public class MultiPartParserTest } }; MultiPartParser parser = new MultiPartParser(handler, "BOUNDARY"); - + String preamble = "Blah blah blah\r\n--BOUNDARY\r\n\r\n"; String epilogue = "\r\n--BOUNDARY\r\nBlah blah blah!\r\n"; - + ByteBuffer data = BufferUtil.allocate(preamble.length() + random.length + epilogue.length()); BufferUtil.append(data, BufferUtil.toBuffer(preamble)); BufferUtil.append(data, ByteBuffer.wrap(random)); BufferUtil.append(data, BufferUtil.toBuffer(epilogue)); - + parser.parse(data, true); assertThat(parser.getState(), is(State.DELIMITER)); assertThat(data.remaining(), is(19)); assertThat(bytes.array(), is(random)); } - + @Test public void testEpilogue() { TestHandler handler = new TestHandler(); MultiPartParser parser = new MultiPartParser(handler, "BOUNDARY"); - + ByteBuffer data = BufferUtil.toBuffer("" - + "--BOUNDARY\r\n" - + "name: value\n" - + "\r\n" - + "Hello\r\n" - + "--BOUNDARY--" - + "epilogue here:" - + "\r\n" - + "--BOUNDARY--" - + "\r\n" - + "--BOUNDARY"); - - + + "--BOUNDARY\r\n" + + "name: value\n" + + "\r\n" + + "Hello\r\n" + + "--BOUNDARY--" + + "epilogue here:" + + "\r\n" + + "--BOUNDARY--" + + "\r\n" + + "--BOUNDARY"); + parser.parse(data, false); assertThat(parser.getState(), is(State.DELIMITER)); assertThat(handler.fields, Matchers.contains("name: value", "<>")); assertThat(handler.content, Matchers.contains("Hello", "<>")); - + parser.parse(data, true); assertThat(parser.getState(), is(State.END)); } - - + @Test public void testMultipleContent() { TestHandler handler = new TestHandler(); MultiPartParser parser = new MultiPartParser(handler, "BOUNDARY"); - + ByteBuffer data = BufferUtil.toBuffer("" - + "--BOUNDARY\r\n" - + "name: value\n" - + "\r\n" - + "Hello" - + "\r\n" - + "--BOUNDARY\r\n" - + "powerLevel: 9001\n" - + "\r\n" - + "secondary" - + "\r\n" - + "content" - + "\r\n--BOUNDARY--" - + "epilogue here"); - + + "--BOUNDARY\r\n" + + "name: value\n" + + "\r\n" + + "Hello" + + "\r\n" + + "--BOUNDARY\r\n" + + "powerLevel: 9001\n" + + "\r\n" + + "secondary" + + "\r\n" + + "content" + + "\r\n--BOUNDARY--" + + "epilogue here"); + /* Test First Content Section */ parser.parse(data, false); assertThat(parser.getState(), is(State.DELIMITER)); assertThat(handler.fields, Matchers.contains("name: value", "<>")); assertThat(handler.content, Matchers.contains("Hello", "<>")); - + /* Test Second Content Section */ parser.parse(data, false); assertThat(parser.getState(), is(State.DELIMITER)); assertThat(handler.fields, Matchers.contains("name: value", "<>", "powerLevel: 9001", "<>")); assertThat(handler.content, Matchers.contains("Hello", "<>", "secondary\r\ncontent", "<>")); - + /* Test Progression to END State */ parser.parse(data, true); assertThat(parser.getState(), is(State.END)); assertThat(data.remaining(), is(0)); } - @Test public void testCrAsLineTermination() @@ -463,17 +456,17 @@ public class MultiPartParserTest } }; MultiPartParser parser = new MultiPartParser(handler, "AaB03x"); - - ByteBuffer data = BufferUtil.toBuffer( - "--AaB03x\r\n"+ - "content-disposition: form-data; name=\"field1\"\r\n"+ - "\r"+ - "Joe Blow\r\n"+ + + ByteBuffer data = BufferUtil.toBuffer( + "--AaB03x\r\n" + + "content-disposition: form-data; name=\"field1\"\r\n" + + "\r" + + "Joe Blow\r\n" + "--AaB03x--\r\n"); BadMessageException x = assertThrows(BadMessageException.class, - ()-> parser.parse(data,true), - "Invalid EOL"); + () -> parser.parse(data, true), + "Invalid EOL"); assertThat(x.getMessage(), containsString("Bad EOL")); } @@ -481,38 +474,38 @@ public class MultiPartParserTest public void testBadHeaderNames() throws Exception { String[] bad = new String[] - { - "Foo\\Bar: value\r\n", - "Foo@Bar: value\r\n", - "Foo,Bar: value\r\n", - "Foo}Bar: value\r\n", - "Foo{Bar: value\r\n", - "Foo=Bar: value\r\n", - "Foo>Bar: value\r\n", - "FooBar: value\r\n", + "Foo>" - , "Content-Disposition: form-data; name=\"file1\"; filename=\"a.txt\"" - , "Content-Type: text/plain", "<>" - , "Content-Disposition: form-data; name=\"file2\"; filename=\"a.html\"" - , "Content-Type: text/html", "<>" - , "Field1: value1", "Field2: value2", "Field3: value3" - , "Field4: value4", "Field5: value5", "Field6: value6" - , "Field7: value7", "Field8: value8", "Field9: value 9", "<>" - , "Field1: value1", "<>")); - + , "Content-Disposition: form-data; name=\"file1\"; filename=\"a.txt\"" + , "Content-Type: text/plain", "<>" + , "Content-Disposition: form-data; name=\"file2\"; filename=\"a.html\"" + , "Content-Type: text/html", "<>" + , "Field1: value1", "Field2: value2", "Field3: value3" + , "Field4: value4", "Field5: value5", "Field6: value6" + , "Field7: value7", "Field8: value8", "Field9: value 9", "<>" + , "Field1: value1", "<>")); assertThat(handler.contentString(), is("text default" + "<>" - + "Content of a.txt.\n" + "<>" - + "Content of a.html.\n" + "<>" - + "<>" - + "But the amount of denudation which the strata have\n" + - "in many places suffered, independently of the rate\n" + - "of accumulation of the degraded matter, probably\n" + - "offers the best evidence of the lapse of time. I remember\n" + - "having been much struck with the evidence of\n" + - "denudation, when viewing volcanic islands, which\n" + - "have been worn by the waves and pared all round\n" + - "into perpendicular cliffs of one or two thousand feet\n" + - "in height; for the gentle slope of the lava-streams,\n" + - "due to their formerly liquid state, showed at a glance\n" + - "how far the hard, rocky beds had once extended into\n" + - "the open ocean.\n" + "<>")); + + "Content of a.txt.\n" + "<>" + + "Content of a.html.\n" + "<>" + + "<>" + + "But the amount of denudation which the strata have\n" + + "in many places suffered, independently of the rate\n" + + "of accumulation of the degraded matter, probably\n" + + "offers the best evidence of the lapse of time. I remember\n" + + "having been much struck with the evidence of\n" + + "denudation, when viewing volcanic islands, which\n" + + "have been worn by the waves and pared all round\n" + + "into perpendicular cliffs of one or two thousand feet\n" + + "in height; for the gentle slope of the lava-streams,\n" + + "due to their formerly liquid state, showed at a glance\n" + + "how far the hard, rocky beds had once extended into\n" + + "the open ocean.\n" + "<>")); handler.clear(); parser.reset(); } } - @Test public void testGeneratedForm() @@ -671,35 +661,33 @@ public class MultiPartParserTest super.content(buffer, last); return false; } - + @Override public boolean headerComplete() { return false; } }; - + MultiPartParser parser = new MultiPartParser(handler, "WebKitFormBoundary7MA4YWf7OaKlSxkTrZu0gW"); ByteBuffer data = BufferUtil.toBuffer("" - + "Content-Type: multipart/form-data; boundary=WebKitFormBoundary7MA4YWf7OaKlSxkTrZu0gW\r\n" + - "\r\n" + - "--WebKitFormBoundary7MA4YWf7OaKlSxkTrZu0gW\r\n" + - "Content-Disposition: form-data; name=\"part1\"\r\n" + - "\n" + - "wNfミxVam﾿t\r\n" + - "--WebKitFormBoundary7MA4YWf7OaKlSxkTrZu0gW\n" + - "Content-Disposition: form-data; name=\"part2\"\r\n" + - "\r\n" + - "&ᄈᄎ￙ᅱᅢO\r\n" + - "--WebKitFormBoundary7MA4YWf7OaKlSxkTrZu0gW--"); + + "Content-Type: multipart/form-data; boundary=WebKitFormBoundary7MA4YWf7OaKlSxkTrZu0gW\r\n" + + "\r\n" + + "--WebKitFormBoundary7MA4YWf7OaKlSxkTrZu0gW\r\n" + + "Content-Disposition: form-data; name=\"part1\"\r\n" + + "\n" + + "wNfミxVam﾿t\r\n" + + "--WebKitFormBoundary7MA4YWf7OaKlSxkTrZu0gW\n" + + "Content-Disposition: form-data; name=\"part2\"\r\n" + + "\r\n" + + "&ᄈᄎ￙ᅱᅢO\r\n" + + "--WebKitFormBoundary7MA4YWf7OaKlSxkTrZu0gW--"); parser.parse(data, true); assertThat(parser.getState(), is(State.END)); assertThat(handler.fields.size(), is(2)); - } - - + static class TestHandler implements MultiPartParser.Handler { List fields = new ArrayList<>(); @@ -715,7 +703,9 @@ public class MultiPartParserTest { StringBuilder sb = new StringBuilder(); for (String s : content) + { sb.append(s); + } return sb.toString(); } @@ -735,7 +725,7 @@ public class MultiPartParserTest content.add("<>"); return last; } - + public void clear() { fields.clear(); diff --git a/jetty-http/src/test/java/org/eclipse/jetty/http/QuotedCSVTest.java b/jetty-http/src/test/java/org/eclipse/jetty/http/QuotedCSVTest.java index 8d946712010..310750770c4 100644 --- a/jetty-http/src/test/java/org/eclipse/jetty/http/QuotedCSVTest.java +++ b/jetty-http/src/test/java/org/eclipse/jetty/http/QuotedCSVTest.java @@ -36,61 +36,61 @@ public class QuotedCSVTest { QuotedCSV values = new QuotedCSV(); values.addValue(" value 0.5 ; pqy = vwz ; q =0.5 , value 1.0 , other ; param "); - assertThat(values,Matchers.contains( - "value 0.5;pqy=vwz;q=0.5", - "value 1.0", - "other;param")); + assertThat(values, Matchers.contains( + "value 0.5;pqy=vwz;q=0.5", + "value 1.0", + "other;param")); } - + @Test public void testEmpty() { QuotedCSV values = new QuotedCSV(); values.addValue(",aaaa, , bbbb ,,cccc,"); - assertThat(values,Matchers.contains( - "aaaa", - "bbbb", - "cccc")); + assertThat(values, Matchers.contains( + "aaaa", + "bbbb", + "cccc")); } - + @Test public void testQuoted() { QuotedCSV values = new QuotedCSV(); values.addValue("A;p=\"v\",B,\"C, D\""); - assertThat(values,Matchers.contains( - "A;p=\"v\"", - "B", - "\"C, D\"")); + assertThat(values, Matchers.contains( + "A;p=\"v\"", + "B", + "\"C, D\"")); } - + @Test public void testOpenQuote() { QuotedCSV values = new QuotedCSV(); values.addValue("value;p=\"v"); - assertThat(values,Matchers.contains( - "value;p=\"v")); + assertThat(values, Matchers.contains( + "value;p=\"v")); } - + @Test public void testQuotedNoQuotes() { QuotedCSV values = new QuotedCSV(false); values.addValue("A;p=\"v\",B,\"C, D\""); - assertThat(values,Matchers.contains( - "A;p=v", - "B", - "C, D")); + assertThat(values, Matchers.contains( + "A;p=v", + "B", + "C, D")); } - + @Test public void testOpenQuoteNoQuotes() { QuotedCSV values = new QuotedCSV(false); values.addValue("value;p=\"v"); - assertThat(values,Matchers.contains( - "value;p=v")); + assertThat(values, Matchers.contains( + "value;p=v")); } @Test @@ -98,10 +98,10 @@ public class QuotedCSVTest { QuotedCSV values = new QuotedCSV(false); values.addValue("for=192.0.2.43, for=\"[2001:db8:cafe::17]\", for=unknown"); - assertThat(values,Matchers.contains( - "for=192.0.2.43", - "for=[2001:db8:cafe::17]", - "for=unknown")); + assertThat(values, Matchers.contains( + "for=192.0.2.43", + "for=[2001:db8:cafe::17]", + "for=unknown")); } @Test @@ -130,40 +130,38 @@ public class QuotedCSVTest @Override protected void parsedParam(StringBuffer buffer, int valueLength, int paramName, int paramValue) { - String name = paramValue>0?buffer.substring(paramName,paramValue-1):buffer.substring(paramName); + String name = paramValue > 0 ? buffer.substring(paramName, paramValue - 1) : buffer.substring(paramName); if ("IGNORE".equals(name)) - buffer.setLength(paramName-1); + buffer.setLength(paramName - 1); } - }; - + values.addValue("normal;param=val, testAPPENDandDELETEvalue ; n=v; IGNORE = this; x=y "); - assertThat(values,Matchers.contains( - "normal;param=val", - "testAppendandvalue!;n=v;x=y")); + assertThat(values, Matchers.contains( + "normal;param=val", + "testAppendandvalue!;n=v;x=y")); } - - + @Test public void testUnQuote() { - assertThat(QuotedCSV.unquote(""),is("")); - assertThat(QuotedCSV.unquote("\"\""),is("")); - assertThat(QuotedCSV.unquote("foo"),is("foo")); - assertThat(QuotedCSV.unquote("\"foo\""),is("foo")); - assertThat(QuotedCSV.unquote("f\"o\"o"),is("foo")); - assertThat(QuotedCSV.unquote("\"\\\"foo\""),is("\"foo")); - assertThat(QuotedCSV.unquote("\\foo"),is("\\foo")); + assertThat(QuotedCSV.unquote(""), is("")); + assertThat(QuotedCSV.unquote("\"\""), is("")); + assertThat(QuotedCSV.unquote("foo"), is("foo")); + assertThat(QuotedCSV.unquote("\"foo\""), is("foo")); + assertThat(QuotedCSV.unquote("f\"o\"o"), is("foo")); + assertThat(QuotedCSV.unquote("\"\\\"foo\""), is("\"foo")); + assertThat(QuotedCSV.unquote("\\foo"), is("\\foo")); } @Test public void testJoin() { - assertThat(QuotedCSV.join((String)null),nullValue()); - assertThat(QuotedCSV.join(Collections.emptyList()),is(emptyString())); - assertThat(QuotedCSV.join(Collections.singletonList("hi")),is("hi")); - assertThat(QuotedCSV.join("hi","ho"),is("hi, ho")); - assertThat(QuotedCSV.join("h i","h,o"),is("\"h i\", \"h,o\"")); - assertThat(QuotedCSV.join("h\"i","h\to"),is("\"h\\\"i\", \"h\\to\"")); + assertThat(QuotedCSV.join((String)null), nullValue()); + assertThat(QuotedCSV.join(Collections.emptyList()), is(emptyString())); + assertThat(QuotedCSV.join(Collections.singletonList("hi")), is("hi")); + assertThat(QuotedCSV.join("hi", "ho"), is("hi, ho")); + assertThat(QuotedCSV.join("h i", "h,o"), is("\"h i\", \"h,o\"")); + assertThat(QuotedCSV.join("h\"i", "h\to"), is("\"h\\\"i\", \"h\\to\"")); } } diff --git a/jetty-http/src/test/java/org/eclipse/jetty/http/QuotedQualityCSVTest.java b/jetty-http/src/test/java/org/eclipse/jetty/http/QuotedQualityCSVTest.java index f03657ba3e5..67497db75df 100644 --- a/jetty-http/src/test/java/org/eclipse/jetty/http/QuotedQualityCSVTest.java +++ b/jetty-http/src/test/java/org/eclipse/jetty/http/QuotedQualityCSVTest.java @@ -18,13 +18,12 @@ package org.eclipse.jetty.http; +import java.util.ArrayList; +import java.util.List; import org.hamcrest.Matchers; import org.junit.jupiter.api.Test; -import java.util.ArrayList; -import java.util.List; - import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.contains; @@ -36,7 +35,7 @@ public class QuotedQualityCSVTest { QuotedQualityCSV values = new QuotedQualityCSV(); values.addValue(" audio/*; q=0.2, audio/basic"); - assertThat(values,Matchers.contains("audio/basic","audio/*")); + assertThat(values, Matchers.contains("audio/basic", "audio/*")); } @Test @@ -45,43 +44,43 @@ public class QuotedQualityCSVTest QuotedQualityCSV values = new QuotedQualityCSV(); values.addValue("text/plain; q=0.5, text/html,"); values.addValue("text/x-dvi; q=0.8, text/x-c"); - assertThat(values,Matchers.contains("text/html","text/x-c","text/x-dvi","text/plain")); + assertThat(values, Matchers.contains("text/html", "text/x-c", "text/x-dvi", "text/plain")); } - + @Test public void test7231_5_3_2_example3() { QuotedQualityCSV values = new QuotedQualityCSV(); values.addValue("text/*, text/plain, text/plain;format=flowed, */*"); - + // Note this sort is only on quality and not the most specific type as per 5.3.2 - assertThat(values,Matchers.contains("text/*","text/plain","text/plain;format=flowed","*/*")); + assertThat(values, Matchers.contains("text/*", "text/plain", "text/plain;format=flowed", "*/*")); } - + @Test public void test7231_5_3_2_example3_most_specific() { QuotedQualityCSV values = new QuotedQualityCSV(QuotedQualityCSV.MOST_SPECIFIC_MIME_ORDERING); values.addValue("text/*, text/plain, text/plain;format=flowed, */*"); - - assertThat(values,Matchers.contains("text/plain;format=flowed","text/plain","text/*","*/*")); + + assertThat(values, Matchers.contains("text/plain;format=flowed", "text/plain", "text/*", "*/*")); } - + @Test public void test7231_5_3_2_example4() { QuotedQualityCSV values = new QuotedQualityCSV(); values.addValue("text/*;q=0.3, text/html;q=0.7, text/html;level=1,"); values.addValue("text/html;level=2;q=0.4, */*;q=0.5"); - assertThat(values,Matchers.contains( - "text/html;level=1", - "text/html", - "*/*", - "text/html;level=2", - "text/*" - )); + assertThat(values, Matchers.contains( + "text/html;level=1", + "text/html", + "*/*", + "text/html;level=2", + "text/*" + )); } - + @Test public void test7231_5_3_4_example1() { @@ -91,16 +90,16 @@ public class QuotedQualityCSVTest values.addValue("*"); values.addValue("compress;q=0.5, gzip;q=1.0"); values.addValue("gzip;q=1.0, identity; q=0.5, *;q=0"); - - assertThat(values,Matchers.contains( - "compress", - "gzip", - "*", - "gzip", - "gzip", - "compress", - "identity" - )); + + assertThat(values, Matchers.contains( + "compress", + "gzip", + "*", + "gzip", + "gzip", + "compress", + "identity" + )); } @Test @@ -108,66 +107,65 @@ public class QuotedQualityCSVTest { QuotedQualityCSV values = new QuotedQualityCSV(); values.addValue(" value 0.5 ; p = v ; q =0.5 , value 1.0 "); - assertThat(values,Matchers.contains( - "value 1.0", - "value 0.5;p=v")); + assertThat(values, Matchers.contains( + "value 1.0", + "value 0.5;p=v")); } - + @Test public void testEmpty() { QuotedQualityCSV values = new QuotedQualityCSV(); values.addValue(",aaaa, , bbbb ,,cccc,"); - assertThat(values,Matchers.contains( - "aaaa", - "bbbb", - "cccc")); + assertThat(values, Matchers.contains( + "aaaa", + "bbbb", + "cccc")); } - + @Test public void testQuoted() { QuotedQualityCSV values = new QuotedQualityCSV(); values.addValue(" value 0.5 ; p = \"v ; q = \\\"0.5\\\" , value 1.0 \" "); - assertThat(values,Matchers.contains( - "value 0.5;p=\"v ; q = \\\"0.5\\\" , value 1.0 \"")); + assertThat(values, Matchers.contains( + "value 0.5;p=\"v ; q = \\\"0.5\\\" , value 1.0 \"")); } - + @Test public void testOpenQuote() { QuotedQualityCSV values = new QuotedQualityCSV(); values.addValue("value;p=\"v"); - assertThat(values,Matchers.contains( - "value;p=\"v")); + assertThat(values, Matchers.contains( + "value;p=\"v")); } - + @Test public void testQuotedQuality() { QuotedQualityCSV values = new QuotedQualityCSV(); values.addValue(" value 0.5 ; p = v ; q = \"0.5\" , value 1.0 "); - assertThat(values,Matchers.contains( - "value 1.0", - "value 0.5;p=v")); + assertThat(values, Matchers.contains( + "value 1.0", + "value 0.5;p=v")); } - + @Test public void testBadQuality() { QuotedQualityCSV values = new QuotedQualityCSV(); values.addValue("value0.5;p=v;q=0.5,value1.0,valueBad;q=X"); - assertThat(values,Matchers.contains( - "value1.0", - "value0.5;p=v")); + assertThat(values, Matchers.contains( + "value1.0", + "value0.5;p=v")); } - + @Test public void testBad() { QuotedQualityCSV values = new QuotedQualityCSV(); - // None of these should throw exceptions values.addValue(null); values.addValue(""); @@ -223,13 +221,10 @@ public class QuotedQualityCSVTest values.addValue("q="); values.addValue("q=,"); values.addValue("q=;"); - } - /* ------------------------------------------------------------ */ - - private static final String[] preferBrotli = {"br","gzip"}; - private static final String[] preferGzip = {"gzip","br"}; + private static final String[] preferBrotli = {"br", "gzip"}; + private static final String[] preferGzip = {"gzip", "br"}; private static final String[] noFormats = {}; @Test @@ -295,14 +290,13 @@ public class QuotedQualityCSVTest values.addValue("gzip, *"); assertThat(values, contains("*", "gzip")); } - @Test public void testSameQuality() { QuotedQualityCSV values = new QuotedQualityCSV(); values.addValue("one;q=0.5,two;q=0.5,three;q=0.5"); - assertThat(values.getValues(),Matchers.contains("one","two","three")); + assertThat(values.getValues(), Matchers.contains("one", "two", "three")); } @Test @@ -310,10 +304,9 @@ public class QuotedQualityCSVTest { QuotedQualityCSV values = new QuotedQualityCSV(); values.addValue("one,two;,three;x=y"); - assertThat(values.getValues(),Matchers.contains("one","two","three;x=y")); + assertThat(values.getValues(), Matchers.contains("one", "two", "three;x=y")); } - @Test public void testQuality() { @@ -339,19 +332,15 @@ public class QuotedQualityCSVTest } }; - // The provided string is not legal according to some RFCs ( not a token because of = and not a parameter because not preceded by ; ) // The string is legal according to RFC7239 which allows for just parameters (called forwarded-pairs) values.addValue("p=0.5,q=0.5"); - // The QuotedCSV implementation is lenient and adopts the later interpretation and thus sees q=0.5 and p=0.5 both as parameters - assertThat(results,contains("parsedValue: ", "parsedParam: p=0.5", - "parsedValue: ", "parsedParam: q=0.5")); - + assertThat(results, contains("parsedValue: ", "parsedParam: p=0.5", + "parsedValue: ", "parsedParam: q=0.5")); // However the QuotedQualityCSV only handles the q parameter and that is consumed from the parameter string. - assertThat(values,contains("p=0.5", "")); - + assertThat(values, contains("p=0.5", "")); } } diff --git a/jetty-http/src/test/java/org/eclipse/jetty/http/SyntaxTest.java b/jetty-http/src/test/java/org/eclipse/jetty/http/SyntaxTest.java index cf2fed2dd33..1f18cf82e17 100644 --- a/jetty-http/src/test/java/org/eclipse/jetty/http/SyntaxTest.java +++ b/jetty-http/src/test/java/org/eclipse/jetty/http/SyntaxTest.java @@ -31,39 +31,39 @@ public class SyntaxTest public void testRequireValidRFC2616Token_Good() { String tokens[] = { - "name", - "", - null, - "n.a.m.e", - "na-me", - "+name", - "na*me", - "na$me", - "#name" + "name", + "", + null, + "n.a.m.e", + "na-me", + "+name", + "na*me", + "na$me", + "#name" }; - + for (String token : tokens) { Syntax.requireValidRFC2616Token(token, "Test Based"); // No exception should occur here } } - + @Test public void testRequireValidRFC2616Token_Bad() { String tokens[] = { - "\"name\"", - "name\t", - "na me", - "name\u0082", - "na\tme", - "na;me", - "{name}", - "[name]", - "\"" + "\"name\"", + "name\t", + "na me", + "name\u0082", + "na\tme", + "na;me", + "{name}", + "[name]", + "\"" }; - + for (String token : tokens) { try @@ -74,50 +74,50 @@ public class SyntaxTest catch (IllegalArgumentException e) { assertThat("Testing Bad RFC2616 Token [" + token + "]", e.getMessage(), - allOf(containsString("Test Based"), - containsString("RFC2616"))); + allOf(containsString("Test Based"), + containsString("RFC2616"))); } } } - + @Test public void testRequireValidRFC6265CookieValue_Good() { String values[] = { - "value", - "", - null, - "val=ue", - "val-ue", - "\"value\"", - "val/ue", - "v.a.l.u.e" + "value", + "", + null, + "val=ue", + "val-ue", + "\"value\"", + "val/ue", + "v.a.l.u.e" }; - + for (String value : values) { Syntax.requireValidRFC6265CookieValue(value); // No exception should occur here } } - + @Test public void testRequireValidRFC6265CookieValue_Bad() { String values[] = { - "va\tlue", - "\t", - "value\u0000", - "val\u0082ue", - "va lue", - "va;lue", - "\"value", - "value\"", - "val\\ue", - "val\"ue", - "\"" + "va\tlue", + "\t", + "value\u0000", + "val\u0082ue", + "va lue", + "va;lue", + "\"value", + "value\"", + "val\\ue", + "val\"ue", + "\"" }; - + for (String value : values) { try diff --git a/jetty-http/src/test/java/org/eclipse/jetty/http/pathmap/PathMappingsTest.java b/jetty-http/src/test/java/org/eclipse/jetty/http/pathmap/PathMappingsTest.java index fbc010b7a4d..018dc430f43 100644 --- a/jetty-http/src/test/java/org/eclipse/jetty/http/pathmap/PathMappingsTest.java +++ b/jetty-http/src/test/java/org/eclipse/jetty/http/pathmap/PathMappingsTest.java @@ -18,32 +18,32 @@ package org.eclipse.jetty.http.pathmap; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; + import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.notNullValue; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; -import org.junit.jupiter.api.Test; -import org.junit.jupiter.params.ParameterizedTest; -import org.junit.jupiter.params.provider.ValueSource; - public class PathMappingsTest { private void assertMatch(PathMappings pathmap, String path, String expectedValue) { - String msg = String.format(".getMatch(\"%s\")",path); + String msg = String.format(".getMatch(\"%s\")", path); MappedResource match = pathmap.getMatch(path); - assertThat(msg,match,notNullValue()); + assertThat(msg, match, notNullValue()); String actualMatch = match.getResource(); - assertEquals(expectedValue,actualMatch,msg); + assertEquals(expectedValue, actualMatch, msg); } public void dumpMappings(PathMappings p) { for (MappedResource res : p) { - System.out.printf(" %s%n",res); + System.out.printf(" %s%n", res); } } @@ -61,26 +61,26 @@ public class PathMappingsTest { PathMappings p = new PathMappings<>(); - p.put(new ServletPathSpec("/"),"default"); - p.put(new ServletPathSpec("/animal/bird/*"),"birds"); - p.put(new ServletPathSpec("/animal/fish/*"),"fishes"); - p.put(new ServletPathSpec("/animal/*"),"animals"); - p.put(new RegexPathSpec("^/animal/.*/chat$"),"animalChat"); - p.put(new RegexPathSpec("^/animal/.*/cam$"),"animalCam"); - p.put(new RegexPathSpec("^/entrance/cam$"),"entranceCam"); + p.put(new ServletPathSpec("/"), "default"); + p.put(new ServletPathSpec("/animal/bird/*"), "birds"); + p.put(new ServletPathSpec("/animal/fish/*"), "fishes"); + p.put(new ServletPathSpec("/animal/*"), "animals"); + p.put(new RegexPathSpec("^/animal/.*/chat$"), "animalChat"); + p.put(new RegexPathSpec("^/animal/.*/cam$"), "animalCam"); + p.put(new RegexPathSpec("^/entrance/cam$"), "entranceCam"); // dumpMappings(p); - assertMatch(p,"/animal/bird/eagle","birds"); - assertMatch(p,"/animal/fish/bass/sea","fishes"); - assertMatch(p,"/animal/peccary/javalina/evolution","animals"); - assertMatch(p,"/","default"); - assertMatch(p,"/animal/bird/eagle/chat","animalChat"); - assertMatch(p,"/animal/bird/penguin/chat","animalChat"); - assertMatch(p,"/animal/fish/trout/cam","animalCam"); - assertMatch(p,"/entrance/cam","entranceCam"); + assertMatch(p, "/animal/bird/eagle", "birds"); + assertMatch(p, "/animal/fish/bass/sea", "fishes"); + assertMatch(p, "/animal/peccary/javalina/evolution", "animals"); + assertMatch(p, "/", "default"); + assertMatch(p, "/animal/bird/eagle/chat", "animalChat"); + assertMatch(p, "/animal/bird/penguin/chat", "animalChat"); + assertMatch(p, "/animal/fish/trout/cam", "animalCam"); + assertMatch(p, "/entrance/cam", "entranceCam"); } - + /** * Test the match order rules imposed by the Servlet API (default vs any) */ @@ -89,15 +89,15 @@ public class PathMappingsTest { PathMappings p = new PathMappings<>(); - p.put(new ServletPathSpec("/"),"default"); - p.put(new ServletPathSpec("/*"),"any"); + p.put(new ServletPathSpec("/"), "default"); + p.put(new ServletPathSpec("/*"), "any"); - assertMatch(p,"/abs/path","any"); - assertMatch(p,"/abs/path/xxx","any"); - assertMatch(p,"/animal/bird/eagle/bald","any"); - assertMatch(p,"/","any"); + assertMatch(p, "/abs/path", "any"); + assertMatch(p, "/abs/path/xxx", "any"); + assertMatch(p, "/animal/bird/eagle/bald", "any"); + assertMatch(p, "/", "any"); } - + /** * Test the match order rules with a mixed Servlet and URI Template path specs *

      @@ -112,24 +112,24 @@ public class PathMappingsTest { PathMappings p = new PathMappings<>(); - p.put(new ServletPathSpec("/"),"default"); - p.put(new ServletPathSpec("/animal/bird/*"),"birds"); - p.put(new ServletPathSpec("/animal/fish/*"),"fishes"); - p.put(new ServletPathSpec("/animal/*"),"animals"); - p.put(new UriTemplatePathSpec("/animal/{type}/{name}/chat"),"animalChat"); - p.put(new UriTemplatePathSpec("/animal/{type}/{name}/cam"),"animalCam"); - p.put(new UriTemplatePathSpec("/entrance/cam"),"entranceCam"); + p.put(new ServletPathSpec("/"), "default"); + p.put(new ServletPathSpec("/animal/bird/*"), "birds"); + p.put(new ServletPathSpec("/animal/fish/*"), "fishes"); + p.put(new ServletPathSpec("/animal/*"), "animals"); + p.put(new UriTemplatePathSpec("/animal/{type}/{name}/chat"), "animalChat"); + p.put(new UriTemplatePathSpec("/animal/{type}/{name}/cam"), "animalCam"); + p.put(new UriTemplatePathSpec("/entrance/cam"), "entranceCam"); // dumpMappings(p); - assertMatch(p,"/animal/bird/eagle","birds"); - assertMatch(p,"/animal/fish/bass/sea","fishes"); - assertMatch(p,"/animal/peccary/javalina/evolution","animals"); - assertMatch(p,"/","default"); - assertMatch(p,"/animal/bird/eagle/chat","animalChat"); - assertMatch(p,"/animal/bird/penguin/chat","animalChat"); - assertMatch(p,"/animal/fish/trout/cam","animalCam"); - assertMatch(p,"/entrance/cam","entranceCam"); + assertMatch(p, "/animal/bird/eagle", "birds"); + assertMatch(p, "/animal/fish/bass/sea", "fishes"); + assertMatch(p, "/animal/peccary/javalina/evolution", "animals"); + assertMatch(p, "/", "default"); + assertMatch(p, "/animal/bird/eagle/chat", "animalChat"); + assertMatch(p, "/animal/bird/penguin/chat", "animalChat"); + assertMatch(p, "/animal/fish/trout/cam", "animalCam"); + assertMatch(p, "/entrance/cam", "entranceCam"); } /** @@ -146,19 +146,19 @@ public class PathMappingsTest { PathMappings p = new PathMappings<>(); - p.put(new UriTemplatePathSpec("/a/{var}/c"),"endpointA"); - p.put(new UriTemplatePathSpec("/a/b/c"),"endpointB"); - p.put(new UriTemplatePathSpec("/a/{var1}/{var2}"),"endpointC"); - p.put(new UriTemplatePathSpec("/{var1}/d"),"endpointD"); - p.put(new UriTemplatePathSpec("/b/{var2}"),"endpointE"); + p.put(new UriTemplatePathSpec("/a/{var}/c"), "endpointA"); + p.put(new UriTemplatePathSpec("/a/b/c"), "endpointB"); + p.put(new UriTemplatePathSpec("/a/{var1}/{var2}"), "endpointC"); + p.put(new UriTemplatePathSpec("/{var1}/d"), "endpointD"); + p.put(new UriTemplatePathSpec("/b/{var2}"), "endpointE"); // dumpMappings(p); - assertMatch(p,"/a/b/c","endpointB"); - assertMatch(p,"/a/d/c","endpointA"); - assertMatch(p,"/a/x/y","endpointC"); + assertMatch(p, "/a/b/c", "endpointB"); + assertMatch(p, "/a/d/c", "endpointA"); + assertMatch(p, "/a/x/y", "endpointC"); - assertMatch(p,"/b/d","endpointE"); + assertMatch(p, "/b/d", "endpointE"); } @Test @@ -192,7 +192,7 @@ public class PathMappingsTest assertEquals(null, new ServletPathSpec("/Foo/*").getPathInfo("/Foo"), "pathInfo prefix"); assertEquals(null, new ServletPathSpec("*.ext").getPathInfo("/Foo/bar.ext"), "pathInfo suffix"); assertEquals(null, new ServletPathSpec("/").getPathInfo("/Foo/bar.ext"), "pathInfo default"); - + p.put(new ServletPathSpec("/*"), "0"); // assertEquals("1", p.get("/abs/path"), "Get absolute path"); @@ -233,12 +233,13 @@ public class PathMappingsTest assertTrue(!new ServletPathSpec("*.foo").matches("anything.bar"), "!match *.foo"); assertEquals("10", p.getMatch("/").getResource(), "match / with ''"); - - assertTrue(new ServletPathSpec("").matches("/"),"match \"\""); + + assertTrue(new ServletPathSpec("").matches("/"), "match \"\""); } /** * See JIRA issue: JETTY-88. + * * @throws Exception failed test */ @Test @@ -264,35 +265,36 @@ public class PathMappingsTest public void testPrecidenceVsOrdering() throws Exception { PathMappings p = new PathMappings<>(); - p.put(new ServletPathSpec("/dump/gzip/*"),"prefix"); - p.put(new ServletPathSpec("*.txt"),"suffix"); - - assertEquals(null,p.getMatch("/foo/bar")); - assertEquals("prefix",p.getMatch("/dump/gzip/something").getResource()); - assertEquals("suffix",p.getMatch("/foo/something.txt").getResource()); - assertEquals("prefix",p.getMatch("/dump/gzip/something.txt").getResource()); - + p.put(new ServletPathSpec("/dump/gzip/*"), "prefix"); + p.put(new ServletPathSpec("*.txt"), "suffix"); + + assertEquals(null, p.getMatch("/foo/bar")); + assertEquals("prefix", p.getMatch("/dump/gzip/something").getResource()); + assertEquals("suffix", p.getMatch("/foo/something.txt").getResource()); + assertEquals("prefix", p.getMatch("/dump/gzip/something.txt").getResource()); + p = new PathMappings<>(); - p.put(new ServletPathSpec("*.txt"),"suffix"); - p.put(new ServletPathSpec("/dump/gzip/*"),"prefix"); - - assertEquals(null,p.getMatch("/foo/bar")); - assertEquals("prefix",p.getMatch("/dump/gzip/something").getResource()); - assertEquals("suffix",p.getMatch("/foo/something.txt").getResource()); - assertEquals("prefix",p.getMatch("/dump/gzip/something.txt").getResource()); + p.put(new ServletPathSpec("*.txt"), "suffix"); + p.put(new ServletPathSpec("/dump/gzip/*"), "prefix"); + + assertEquals(null, p.getMatch("/foo/bar")); + assertEquals("prefix", p.getMatch("/dump/gzip/something").getResource()); + assertEquals("suffix", p.getMatch("/foo/something.txt").getResource()); + assertEquals("prefix", p.getMatch("/dump/gzip/something.txt").getResource()); } - + @ParameterizedTest @ValueSource(strings = { - "*", - "/foo/*/bar", - "/foo*", - "*/foo", - "*.foo/*" + "*", + "/foo/*/bar", + "/foo*", + "*/foo", + "*.foo/*" }) public void testBadPathSpecs(String str) { - assertThrows(IllegalArgumentException.class, ()->{ + assertThrows(IllegalArgumentException.class, () -> + { new ServletPathSpec(str); }); } diff --git a/jetty-http/src/test/java/org/eclipse/jetty/http/pathmap/PathSpecAssert.java b/jetty-http/src/test/java/org/eclipse/jetty/http/pathmap/PathSpecAssert.java index 6ee46c5c29a..086a72d9ee9 100644 --- a/jetty-http/src/test/java/org/eclipse/jetty/http/pathmap/PathSpecAssert.java +++ b/jetty-http/src/test/java/org/eclipse/jetty/http/pathmap/PathSpecAssert.java @@ -18,8 +18,8 @@ package org.eclipse.jetty.http.pathmap; -import static org.hamcrest.Matchers.is; import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.is; public class PathSpecAssert { diff --git a/jetty-http/src/test/java/org/eclipse/jetty/http/pathmap/RegexPathSpecTest.java b/jetty-http/src/test/java/org/eclipse/jetty/http/pathmap/RegexPathSpecTest.java index 56d48a3e793..de09d9429cf 100644 --- a/jetty-http/src/test/java/org/eclipse/jetty/http/pathmap/RegexPathSpecTest.java +++ b/jetty-http/src/test/java/org/eclipse/jetty/http/pathmap/RegexPathSpecTest.java @@ -18,24 +18,24 @@ package org.eclipse.jetty.http.pathmap; +import org.junit.jupiter.api.Test; + +import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.is; import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.hamcrest.MatcherAssert.assertThat; - -import org.junit.jupiter.api.Test; public class RegexPathSpecTest { public static void assertMatches(PathSpec spec, String path) { - String msg = String.format("Spec(\"%s\").matches(\"%s\")",spec.getDeclaration(),path); - assertThat(msg,spec.matches(path),is(true)); + String msg = String.format("Spec(\"%s\").matches(\"%s\")", spec.getDeclaration(), path); + assertThat(msg, spec.matches(path), is(true)); } public static void assertNotMatches(PathSpec spec, String path) { - String msg = String.format("!Spec(\"%s\").matches(\"%s\")",spec.getDeclaration(),path); - assertThat(msg,spec.matches(path),is(false)); + String msg = String.format("!Spec(\"%s\").matches(\"%s\")", spec.getDeclaration(), path); + assertThat(msg, spec.matches(path), is(false)); } @Test @@ -47,10 +47,10 @@ public class RegexPathSpecTest assertEquals(1, spec.getPathDepth(), "Spec.pathDepth"); assertEquals(PathSpecGroup.EXACT, spec.group, "Spec.group"); - assertMatches(spec,"/a"); + assertMatches(spec, "/a"); - assertNotMatches(spec,"/aa"); - assertNotMatches(spec,"/a/"); + assertNotMatches(spec, "/aa"); + assertNotMatches(spec, "/a/"); } @Test @@ -62,16 +62,16 @@ public class RegexPathSpecTest assertEquals(3, spec.getPathDepth(), "Spec.pathDepth"); assertEquals(PathSpecGroup.MIDDLE_GLOB, spec.group, "Spec.group"); - assertMatches(spec,"/rest/api/list"); - assertMatches(spec,"/rest/1.0/list"); - assertMatches(spec,"/rest/2.0/list"); - assertMatches(spec,"/rest/accounts/list"); + assertMatches(spec, "/rest/api/list"); + assertMatches(spec, "/rest/1.0/list"); + assertMatches(spec, "/rest/2.0/list"); + assertMatches(spec, "/rest/accounts/list"); - assertNotMatches(spec,"/a"); - assertNotMatches(spec,"/aa"); - assertNotMatches(spec,"/aa/bb"); - assertNotMatches(spec,"/rest/admin/delete"); - assertNotMatches(spec,"/rest/list"); + assertNotMatches(spec, "/a"); + assertNotMatches(spec, "/aa"); + assertNotMatches(spec, "/aa/bb"); + assertNotMatches(spec, "/rest/admin/delete"); + assertNotMatches(spec, "/rest/list"); } @Test @@ -83,16 +83,16 @@ public class RegexPathSpecTest assertEquals(3, spec.getPathDepth(), "Spec.pathDepth"); assertEquals(PathSpecGroup.MIDDLE_GLOB, spec.group, "Spec.group"); - assertMatches(spec,"/rest/api/list"); - assertMatches(spec,"/rest/1.0/list"); - assertMatches(spec,"/rest/2.0/list"); - assertMatches(spec,"/rest/accounts/list"); + assertMatches(spec, "/rest/api/list"); + assertMatches(spec, "/rest/1.0/list"); + assertMatches(spec, "/rest/2.0/list"); + assertMatches(spec, "/rest/accounts/list"); - assertNotMatches(spec,"/a"); - assertNotMatches(spec,"/aa"); - assertNotMatches(spec,"/aa/bb"); - assertNotMatches(spec,"/rest/admin/delete"); - assertNotMatches(spec,"/rest/list"); + assertNotMatches(spec, "/a"); + assertNotMatches(spec, "/aa"); + assertNotMatches(spec, "/aa/bb"); + assertNotMatches(spec, "/rest/admin/delete"); + assertNotMatches(spec, "/rest/list"); } @Test @@ -104,13 +104,13 @@ public class RegexPathSpecTest assertEquals(2, spec.getPathDepth(), "Spec.pathDepth"); assertEquals(PathSpecGroup.PREFIX_GLOB, spec.group, "Spec.group"); - assertMatches(spec,"/a/"); - assertMatches(spec,"/a/b"); - assertMatches(spec,"/a/b/c/d/e"); + assertMatches(spec, "/a/"); + assertMatches(spec, "/a/b"); + assertMatches(spec, "/a/b/c/d/e"); - assertNotMatches(spec,"/a"); - assertNotMatches(spec,"/aa"); - assertNotMatches(spec,"/aa/bb"); + assertNotMatches(spec, "/a"); + assertNotMatches(spec, "/aa"); + assertNotMatches(spec, "/aa/bb"); } @Test @@ -122,14 +122,14 @@ public class RegexPathSpecTest assertEquals(0, spec.getPathDepth(), "Spec.pathDepth"); assertEquals(PathSpecGroup.SUFFIX_GLOB, spec.group, "Spec.group"); - assertMatches(spec,"/a.do"); - assertMatches(spec,"/a/b/c.do"); - assertMatches(spec,"/abcde.do"); - assertMatches(spec,"/abc/efg.do"); + assertMatches(spec, "/a.do"); + assertMatches(spec, "/a/b/c.do"); + assertMatches(spec, "/abcde.do"); + assertMatches(spec, "/abc/efg.do"); - assertNotMatches(spec,"/a"); - assertNotMatches(spec,"/aa"); - assertNotMatches(spec,"/aa/bb"); - assertNotMatches(spec,"/aa/bb.do/more"); + assertNotMatches(spec, "/a"); + assertNotMatches(spec, "/aa"); + assertNotMatches(spec, "/aa/bb"); + assertNotMatches(spec, "/aa/bb.do/more"); } } diff --git a/jetty-http/src/test/java/org/eclipse/jetty/http/pathmap/ServletPathSpecMatchListTest.java b/jetty-http/src/test/java/org/eclipse/jetty/http/pathmap/ServletPathSpecMatchListTest.java index 7839eda4383..88c637b489b 100644 --- a/jetty-http/src/test/java/org/eclipse/jetty/http/pathmap/ServletPathSpecMatchListTest.java +++ b/jetty-http/src/test/java/org/eclipse/jetty/http/pathmap/ServletPathSpecMatchListTest.java @@ -18,9 +18,6 @@ package org.eclipse.jetty.http.pathmap; -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.is; - import java.util.ArrayList; import java.util.List; import java.util.stream.Stream; @@ -29,6 +26,9 @@ import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.Arguments; import org.junit.jupiter.params.provider.MethodSource; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.is; + /** * Tests of {@link PathMappings#getMatches(String)} */ @@ -40,34 +40,35 @@ public class ServletPathSpecMatchListTest ArrayList data = new ArrayList<>(); // From old PathMapTest - data.add(Arguments.of( "All matches", "/animal/bird/path.tar.gz", "[/animal/bird/*=birds, /animal/*=animals, *.tar.gz=tarball, *.gz=gzipped, /=default]")); - data.add(Arguments.of( "Dir matches", "/animal/fish/", "[/animal/fish/*=fishes, /animal/*=animals, /=default]")); - data.add(Arguments.of( "Dir matches", "/animal/fish", "[/animal/fish/*=fishes, /animal/*=animals, /=default]")); - data.add(Arguments.of( "Root matches", "/", "[=root, /=default]")); - data.add(Arguments.of( "Dir matches", "", "[/=default]")); + data.add(Arguments.of("All matches", "/animal/bird/path.tar.gz", "[/animal/bird/*=birds, /animal/*=animals, *.tar.gz=tarball, *.gz=gzipped, /=default]")); + data.add(Arguments.of("Dir matches", "/animal/fish/", "[/animal/fish/*=fishes, /animal/*=animals, /=default]")); + data.add(Arguments.of("Dir matches", "/animal/fish", "[/animal/fish/*=fishes, /animal/*=animals, /=default]")); + data.add(Arguments.of("Root matches", "/", "[=root, /=default]")); + data.add(Arguments.of("Dir matches", "", "[/=default]")); return data.stream(); } private static PathMappings mappings; - - static { + + static + { mappings = new PathMappings<>(); // From old PathMapTest - mappings.put(new ServletPathSpec("/abs/path"),"abspath"); // 1 - mappings.put(new ServletPathSpec("/abs/path/longer"),"longpath"); // 2 - mappings.put(new ServletPathSpec("/animal/bird/*"),"birds"); // 3 - mappings.put(new ServletPathSpec("/animal/fish/*"),"fishes"); // 4 - mappings.put(new ServletPathSpec("/animal/*"),"animals"); // 5 - mappings.put(new ServletPathSpec("*.tar.gz"),"tarball"); // 6 - mappings.put(new ServletPathSpec("*.gz"),"gzipped"); // 7 - mappings.put(new ServletPathSpec("/"),"default"); // 8 + mappings.put(new ServletPathSpec("/abs/path"), "abspath"); // 1 + mappings.put(new ServletPathSpec("/abs/path/longer"), "longpath"); // 2 + mappings.put(new ServletPathSpec("/animal/bird/*"), "birds"); // 3 + mappings.put(new ServletPathSpec("/animal/fish/*"), "fishes"); // 4 + mappings.put(new ServletPathSpec("/animal/*"), "animals"); // 5 + mappings.put(new ServletPathSpec("*.tar.gz"), "tarball"); // 6 + mappings.put(new ServletPathSpec("*.gz"), "gzipped"); // 7 + mappings.put(new ServletPathSpec("/"), "default"); // 8 // 9 was the old Jetty ":" spec delimited case (no longer valid) - mappings.put(new ServletPathSpec(""),"root"); // 10 - mappings.put(new ServletPathSpec("/\u20ACuro/*"),"money"); // 11 + mappings.put(new ServletPathSpec(""), "root"); // 10 + mappings.put(new ServletPathSpec("/\u20ACuro/*"), "money"); // 11 } - + @ParameterizedTest @MethodSource("data") public void testGetMatches(String message, String inputPath, String expectedListing) @@ -86,6 +87,6 @@ public class ServletPathSpecMatchListTest } actual.append(']'); - assertThat(message + " on [" + inputPath + "]",actual.toString(),is(expectedListing)); + assertThat(message + " on [" + inputPath + "]", actual.toString(), is(expectedListing)); } } diff --git a/jetty-http/src/test/java/org/eclipse/jetty/http/pathmap/ServletPathSpecOrderTest.java b/jetty-http/src/test/java/org/eclipse/jetty/http/pathmap/ServletPathSpecOrderTest.java index 8d859699425..2859dcd0a1f 100644 --- a/jetty-http/src/test/java/org/eclipse/jetty/http/pathmap/ServletPathSpecOrderTest.java +++ b/jetty-http/src/test/java/org/eclipse/jetty/http/pathmap/ServletPathSpecOrderTest.java @@ -18,9 +18,6 @@ package org.eclipse.jetty.http.pathmap; -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.is; - import java.util.ArrayList; import java.util.stream.Stream; @@ -28,6 +25,9 @@ import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.Arguments; import org.junit.jupiter.params.provider.MethodSource; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.is; + /** * Tests of {@link PathMappings#getMatch(String)}, with a focus on correct mapping selection order */ @@ -39,57 +39,58 @@ public class ServletPathSpecOrderTest ArrayList data = new ArrayList<>(); // From old PathMapTest - data.add(Arguments.of("/abs/path","abspath")); - data.add(Arguments.of("/abs/path/xxx","default")); - data.add(Arguments.of("/abs/pith","default")); - data.add(Arguments.of("/abs/path/longer","longpath")); - data.add(Arguments.of("/abs/path/","default")); - data.add(Arguments.of("/abs/path/foo","default")); - data.add(Arguments.of("/animal/bird/eagle/bald","birds")); - data.add(Arguments.of("/animal/fish/shark/hammerhead","fishes")); - data.add(Arguments.of("/animal/insect/ladybug","animals")); - data.add(Arguments.of("/animal","animals")); - data.add(Arguments.of("/animal/","animals")); - data.add(Arguments.of("/animal/other","animals")); - data.add(Arguments.of("/animal/*","animals")); - data.add(Arguments.of("/downloads/distribution.tar.gz","tarball")); - data.add(Arguments.of("/downloads/script.gz","gzipped")); - data.add(Arguments.of("/animal/arhive.gz","animals")); - data.add(Arguments.of("/Other/path","default")); - data.add(Arguments.of("/\u20ACuro/path","money")); - data.add(Arguments.of("/","root")); + data.add(Arguments.of("/abs/path", "abspath")); + data.add(Arguments.of("/abs/path/xxx", "default")); + data.add(Arguments.of("/abs/pith", "default")); + data.add(Arguments.of("/abs/path/longer", "longpath")); + data.add(Arguments.of("/abs/path/", "default")); + data.add(Arguments.of("/abs/path/foo", "default")); + data.add(Arguments.of("/animal/bird/eagle/bald", "birds")); + data.add(Arguments.of("/animal/fish/shark/hammerhead", "fishes")); + data.add(Arguments.of("/animal/insect/ladybug", "animals")); + data.add(Arguments.of("/animal", "animals")); + data.add(Arguments.of("/animal/", "animals")); + data.add(Arguments.of("/animal/other", "animals")); + data.add(Arguments.of("/animal/*", "animals")); + data.add(Arguments.of("/downloads/distribution.tar.gz", "tarball")); + data.add(Arguments.of("/downloads/script.gz", "gzipped")); + data.add(Arguments.of("/animal/arhive.gz", "animals")); + data.add(Arguments.of("/Other/path", "default")); + data.add(Arguments.of("/\u20ACuro/path", "money")); + data.add(Arguments.of("/", "root")); // Extra tests - data.add(Arguments.of("/downloads/readme.txt","default")); - data.add(Arguments.of("/downloads/logs.tgz","default")); - data.add(Arguments.of("/main.css","default")); + data.add(Arguments.of("/downloads/readme.txt", "default")); + data.add(Arguments.of("/downloads/logs.tgz", "default")); + data.add(Arguments.of("/main.css", "default")); return data.stream(); } private static PathMappings mappings; - - static { + + static + { mappings = new PathMappings<>(); // From old PathMapTest - mappings.put(new ServletPathSpec("/abs/path"),"abspath"); // 1 - mappings.put(new ServletPathSpec("/abs/path/longer"),"longpath"); // 2 - mappings.put(new ServletPathSpec("/animal/bird/*"),"birds"); // 3 - mappings.put(new ServletPathSpec("/animal/fish/*"),"fishes"); // 4 - mappings.put(new ServletPathSpec("/animal/*"),"animals"); // 5 - mappings.put(new ServletPathSpec("*.tar.gz"),"tarball"); // 6 - mappings.put(new ServletPathSpec("*.gz"),"gzipped"); // 7 - mappings.put(new ServletPathSpec("/"),"default"); // 8 + mappings.put(new ServletPathSpec("/abs/path"), "abspath"); // 1 + mappings.put(new ServletPathSpec("/abs/path/longer"), "longpath"); // 2 + mappings.put(new ServletPathSpec("/animal/bird/*"), "birds"); // 3 + mappings.put(new ServletPathSpec("/animal/fish/*"), "fishes"); // 4 + mappings.put(new ServletPathSpec("/animal/*"), "animals"); // 5 + mappings.put(new ServletPathSpec("*.tar.gz"), "tarball"); // 6 + mappings.put(new ServletPathSpec("*.gz"), "gzipped"); // 7 + mappings.put(new ServletPathSpec("/"), "default"); // 8 // 9 was the old Jetty ":" spec delimited case (no longer valid) - mappings.put(new ServletPathSpec(""),"root"); // 10 - mappings.put(new ServletPathSpec("/\u20ACuro/*"),"money"); // 11 + mappings.put(new ServletPathSpec(""), "root"); // 10 + mappings.put(new ServletPathSpec("/\u20ACuro/*"), "money"); // 11 } - + @ParameterizedTest @MethodSource("data") public void testMatch(String inputPath, String expectedResource) { - assertThat("Match on ["+ inputPath+ "]", mappings.getMatch(inputPath).getResource(), is(expectedResource)); + assertThat("Match on [" + inputPath + "]", mappings.getMatch(inputPath).getResource(), is(expectedResource)); } } diff --git a/jetty-http/src/test/java/org/eclipse/jetty/http/pathmap/ServletPathSpecTest.java b/jetty-http/src/test/java/org/eclipse/jetty/http/pathmap/ServletPathSpecTest.java index b575079f0f0..51d1c74509b 100644 --- a/jetty-http/src/test/java/org/eclipse/jetty/http/pathmap/ServletPathSpecTest.java +++ b/jetty-http/src/test/java/org/eclipse/jetty/http/pathmap/ServletPathSpecTest.java @@ -18,13 +18,13 @@ package org.eclipse.jetty.http.pathmap; +import org.junit.jupiter.api.Test; + +import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.is; import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.hamcrest.MatcherAssert.assertThat; import static org.junit.jupiter.api.Assertions.fail; -import org.junit.jupiter.api.Test; - public class ServletPathSpecTest { private void assertBadServletPathSpec(String pathSpec) @@ -43,14 +43,14 @@ public class ServletPathSpecTest private void assertMatches(ServletPathSpec spec, String path) { - String msg = String.format("Spec(\"%s\").matches(\"%s\")",spec.getDeclaration(),path); - assertThat(msg,spec.matches(path),is(true)); + String msg = String.format("Spec(\"%s\").matches(\"%s\")", spec.getDeclaration(), path); + assertThat(msg, spec.matches(path), is(true)); } private void assertNotMatches(ServletPathSpec spec, String path) { - String msg = String.format("!Spec(\"%s\").matches(\"%s\")",spec.getDeclaration(),path); - assertThat(msg,spec.matches(path),is(false)); + String msg = String.format("!Spec(\"%s\").matches(\"%s\")", spec.getDeclaration(), path); + assertThat(msg, spec.matches(path), is(false)); } @Test @@ -98,13 +98,13 @@ public class ServletPathSpecTest assertEquals("/abs/path", spec.getDeclaration(), "Spec.pathSpec"); assertEquals(2, spec.getPathDepth(), "Spec.pathDepth"); - assertMatches(spec,"/abs/path"); - - assertNotMatches(spec,"/abs/path/"); - assertNotMatches(spec,"/abs/path/more"); - assertNotMatches(spec,"/foo"); - assertNotMatches(spec,"/foo/abs/path"); - assertNotMatches(spec,"/foo/abs/path/"); + assertMatches(spec, "/abs/path"); + + assertNotMatches(spec, "/abs/path/"); + assertNotMatches(spec, "/abs/path/more"); + assertNotMatches(spec, "/foo"); + assertNotMatches(spec, "/foo/abs/path"); + assertNotMatches(spec, "/foo/abs/path/"); } @Test @@ -128,7 +128,7 @@ public class ServletPathSpecTest assertEquals("", spec.getDeclaration(), "Spec.pathSpec"); assertEquals(-1, spec.getPathDepth(), "Spec.pathDepth"); } - + @Test public void testRootPathSpec() { @@ -157,12 +157,12 @@ public class ServletPathSpecTest assertEquals("/downloads/*", spec.getDeclaration(), "Spec.pathSpec"); assertEquals(2, spec.getPathDepth(), "Spec.pathDepth"); - assertMatches(spec,"/downloads/logo.jpg"); - assertMatches(spec,"/downloads/distribution.tar.gz"); - assertMatches(spec,"/downloads/distribution.tgz"); - assertMatches(spec,"/downloads/distribution.zip"); + assertMatches(spec, "/downloads/logo.jpg"); + assertMatches(spec, "/downloads/distribution.tar.gz"); + assertMatches(spec, "/downloads/distribution.tgz"); + assertMatches(spec, "/downloads/distribution.zip"); - assertMatches(spec,"/downloads"); + assertMatches(spec, "/downloads"); assertEquals("/", spec.getPathInfo("/downloads/"), "Spec.pathInfo"); assertEquals("/distribution.zip", spec.getPathInfo("/downloads/distribution.zip"), "Spec.pathInfo"); @@ -176,12 +176,12 @@ public class ServletPathSpecTest assertEquals("*.gz", spec.getDeclaration(), "Spec.pathSpec"); assertEquals(0, spec.getPathDepth(), "Spec.pathDepth"); - assertMatches(spec,"/downloads/distribution.tar.gz"); - assertMatches(spec,"/downloads/jetty.log.gz"); + assertMatches(spec, "/downloads/distribution.tar.gz"); + assertMatches(spec, "/downloads/jetty.log.gz"); - assertNotMatches(spec,"/downloads/distribution.zip"); - assertNotMatches(spec,"/downloads/distribution.tgz"); - assertNotMatches(spec,"/abs/path"); + assertNotMatches(spec, "/downloads/distribution.zip"); + assertNotMatches(spec, "/downloads/distribution.tgz"); + assertNotMatches(spec, "/abs/path"); assertEquals(null, spec.getPathInfo("/downloads/distribution.tar.gz"), "Spec.pathInfo"); } diff --git a/jetty-http/src/test/java/org/eclipse/jetty/http/pathmap/UriTemplatePathSpecBadSpecsTest.java b/jetty-http/src/test/java/org/eclipse/jetty/http/pathmap/UriTemplatePathSpecBadSpecsTest.java index 2201d2c9b07..55f3989a8b5 100644 --- a/jetty-http/src/test/java/org/eclipse/jetty/http/pathmap/UriTemplatePathSpecBadSpecsTest.java +++ b/jetty-http/src/test/java/org/eclipse/jetty/http/pathmap/UriTemplatePathSpecBadSpecsTest.java @@ -18,14 +18,14 @@ package org.eclipse.jetty.http.pathmap; -import static org.junit.jupiter.api.Assertions.assertThrows; - import java.util.stream.Stream; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.Arguments; import org.junit.jupiter.params.provider.MethodSource; +import static org.junit.jupiter.api.Assertions.assertThrows; + /** * Tests for bad path specs on ServerEndpoint Path Param / URI Template */ @@ -54,10 +54,10 @@ public class UriTemplatePathSpecBadSpecsTest return Stream.of(badSpecs).map(Arguments::of); } - @ParameterizedTest(name="[{index}] {0}") + @ParameterizedTest(name = "[{index}] {0}") @MethodSource("data") public void testBadPathSpec(String pathSpec) { - assertThrows(IllegalArgumentException.class, ()-> new UriTemplatePathSpec(pathSpec)); + assertThrows(IllegalArgumentException.class, () -> new UriTemplatePathSpec(pathSpec)); } } diff --git a/jetty-http/src/test/java/org/eclipse/jetty/http/pathmap/UriTemplatePathSpecTest.java b/jetty-http/src/test/java/org/eclipse/jetty/http/pathmap/UriTemplatePathSpecTest.java index 38efbb059fc..afc20b78301 100644 --- a/jetty-http/src/test/java/org/eclipse/jetty/http/pathmap/UriTemplatePathSpecTest.java +++ b/jetty-http/src/test/java/org/eclipse/jetty/http/pathmap/UriTemplatePathSpecTest.java @@ -18,15 +18,15 @@ package org.eclipse.jetty.http.pathmap; -import static org.hamcrest.Matchers.is; -import static org.hamcrest.Matchers.notNullValue; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.hamcrest.MatcherAssert.assertThat; - import java.util.Map; import org.junit.jupiter.api.Test; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.is; +import static org.hamcrest.Matchers.notNullValue; +import static org.junit.jupiter.api.Assertions.assertEquals; + /** * Tests for URI Template Path Specs */ @@ -34,25 +34,25 @@ public class UriTemplatePathSpecTest { private void assertDetectedVars(UriTemplatePathSpec spec, String... expectedVars) { - String prefix = String.format("Spec(\"%s\")",spec.getDeclaration()); + String prefix = String.format("Spec(\"%s\")", spec.getDeclaration()); assertEquals(expectedVars.length, spec.getVariableCount(), prefix + ".variableCount"); assertEquals(expectedVars.length, spec.getVariables().length, prefix + ".variable.length"); for (int i = 0; i < expectedVars.length; i++) { - assertThat(String.format("%s.variable[%d]",prefix,i),spec.getVariables()[i],is(expectedVars[i])); + assertThat(String.format("%s.variable[%d]", prefix, i), spec.getVariables()[i], is(expectedVars[i])); } } private void assertMatches(PathSpec spec, String path) { - String msg = String.format("Spec(\"%s\").matches(\"%s\")",spec.getDeclaration(),path); - assertThat(msg,spec.matches(path),is(true)); + String msg = String.format("Spec(\"%s\").matches(\"%s\")", spec.getDeclaration(), path); + assertThat(msg, spec.matches(path), is(true)); } private void assertNotMatches(PathSpec spec, String path) { - String msg = String.format("!Spec(\"%s\").matches(\"%s\")",spec.getDeclaration(),path); - assertThat(msg,spec.matches(path),is(false)); + String msg = String.format("!Spec(\"%s\").matches(\"%s\")", spec.getDeclaration(), path); + assertThat(msg, spec.matches(path), is(false)); } @Test @@ -76,16 +76,16 @@ public class UriTemplatePathSpecTest assertEquals("^/a$", spec.getPattern().pattern(), "Spec.pattern"); assertEquals(1, spec.getPathDepth(), "Spec.pathDepth"); assertEquals(PathSpecGroup.EXACT, spec.getGroup(), "Spec.group"); - - assertMatches(spec,"/a"); - assertMatches(spec,"/a?type=other"); - assertNotMatches(spec,"/a/b"); - assertNotMatches(spec,"/a/"); + + assertMatches(spec, "/a"); + assertMatches(spec, "/a?type=other"); + assertNotMatches(spec, "/a/b"); + assertNotMatches(spec, "/a/"); assertEquals(0, spec.getVariableCount(), "Spec.variableCount"); assertEquals(0, spec.getVariables().length, "Spec.variable.length"); } - + @Test public void testExactPathSpec_TestWebapp() { @@ -94,14 +94,14 @@ public class UriTemplatePathSpecTest assertEquals("^/deep\\.thought/$", spec.getPattern().pattern(), "Spec.pattern"); assertEquals(1, spec.getPathDepth(), "Spec.pathDepth"); assertEquals(PathSpecGroup.EXACT, spec.getGroup(), "Spec.group"); - - assertMatches(spec,"/deep.thought/"); - assertNotMatches(spec,"/deep.thought"); + + assertMatches(spec, "/deep.thought/"); + assertNotMatches(spec, "/deep.thought"); assertEquals(0, spec.getVariableCount(), "Spec.variableCount"); assertEquals(0, spec.getVariables().length, "Spec.variable.length"); } - + @Test public void testExactTwoPathSpec() { @@ -114,11 +114,11 @@ public class UriTemplatePathSpecTest assertEquals(0, spec.getVariableCount(), "Spec.variableCount"); assertEquals(0, spec.getVariables().length, "Spec.variable.length"); - assertMatches(spec,"/a/b"); + assertMatches(spec, "/a/b"); - assertNotMatches(spec,"/a/b/"); - assertNotMatches(spec,"/a/"); - assertNotMatches(spec,"/a/bb"); + assertNotMatches(spec, "/a/b/"); + assertNotMatches(spec, "/a/"); + assertNotMatches(spec, "/a/bb"); } @Test @@ -130,18 +130,18 @@ public class UriTemplatePathSpecTest assertEquals(3, spec.getPathDepth(), "Spec.pathDepth"); assertEquals(PathSpecGroup.MIDDLE_GLOB, spec.getGroup(), "Spec.group"); - assertDetectedVars(spec,"var"); + assertDetectedVars(spec, "var"); - assertMatches(spec,"/a/b/c"); - assertMatches(spec,"/a/zz/c"); - assertMatches(spec,"/a/hello+world/c"); - assertNotMatches(spec,"/a/bc"); - assertNotMatches(spec,"/a/b/"); - assertNotMatches(spec,"/a/b"); + assertMatches(spec, "/a/b/c"); + assertMatches(spec, "/a/zz/c"); + assertMatches(spec, "/a/hello+world/c"); + assertNotMatches(spec, "/a/bc"); + assertNotMatches(spec, "/a/b/"); + assertNotMatches(spec, "/a/b"); Map mapped = spec.getPathParams("/a/b/c"); - assertThat("Spec.pathParams",mapped,notNullValue()); - assertThat("Spec.pathParams.size",mapped.size(),is(1)); + assertThat("Spec.pathParams", mapped, notNullValue()); + assertThat("Spec.pathParams.size", mapped.size(), is(1)); assertEquals("b", mapped.get("var"), "Spec.pathParams[var]"); } @@ -154,15 +154,15 @@ public class UriTemplatePathSpecTest assertEquals(2, spec.getPathDepth(), "Spec.pathDepth"); assertEquals(PathSpecGroup.PREFIX_GLOB, spec.getGroup(), "Spec.group"); - assertDetectedVars(spec,"foo"); + assertDetectedVars(spec, "foo"); - assertMatches(spec,"/a/b"); - assertNotMatches(spec,"/a/"); - assertNotMatches(spec,"/a"); + assertMatches(spec, "/a/b"); + assertNotMatches(spec, "/a/"); + assertNotMatches(spec, "/a"); Map mapped = spec.getPathParams("/a/b"); - assertThat("Spec.pathParams",mapped,notNullValue()); - assertThat("Spec.pathParams.size",mapped.size(),is(1)); + assertThat("Spec.pathParams", mapped, notNullValue()); + assertThat("Spec.pathParams.size", mapped.size(), is(1)); assertEquals("b", mapped.get("foo"), "Spec.pathParams[foo]"); } @@ -175,18 +175,18 @@ public class UriTemplatePathSpecTest assertEquals(3, spec.getPathDepth(), "Spec.pathDepth"); assertEquals(PathSpecGroup.SUFFIX_GLOB, spec.getGroup(), "Spec.group"); - assertDetectedVars(spec,"var"); + assertDetectedVars(spec, "var"); - assertMatches(spec,"/a/b/c"); - assertMatches(spec,"/az/b/c"); - assertMatches(spec,"/hello+world/b/c"); - assertNotMatches(spec,"/a/bc"); - assertNotMatches(spec,"/a/b/"); - assertNotMatches(spec,"/a/b"); + assertMatches(spec, "/a/b/c"); + assertMatches(spec, "/az/b/c"); + assertMatches(spec, "/hello+world/b/c"); + assertNotMatches(spec, "/a/bc"); + assertNotMatches(spec, "/a/b/"); + assertNotMatches(spec, "/a/b"); Map mapped = spec.getPathParams("/a/b/c"); - assertThat("Spec.pathParams",mapped,notNullValue()); - assertThat("Spec.pathParams.size",mapped.size(),is(1)); + assertThat("Spec.pathParams", mapped, notNullValue()); + assertThat("Spec.pathParams.size", mapped.size(), is(1)); assertEquals("a", mapped.get("var"), "Spec.pathParams[var]"); } @@ -199,16 +199,16 @@ public class UriTemplatePathSpecTest assertEquals(5, spec.getPathDepth(), "Spec.pathDepth"); assertEquals(PathSpecGroup.MIDDLE_GLOB, spec.getGroup(), "Spec.group"); - assertDetectedVars(spec,"var1","var2"); + assertDetectedVars(spec, "var1", "var2"); - assertMatches(spec,"/a/b/c/d/e"); - assertNotMatches(spec,"/a/bc/d/e"); - assertNotMatches(spec,"/a/b/d/e"); - assertNotMatches(spec,"/a/b//d/e"); + assertMatches(spec, "/a/b/c/d/e"); + assertNotMatches(spec, "/a/bc/d/e"); + assertNotMatches(spec, "/a/b/d/e"); + assertNotMatches(spec, "/a/b//d/e"); Map mapped = spec.getPathParams("/a/b/c/d/e"); - assertThat("Spec.pathParams",mapped,notNullValue()); - assertThat("Spec.pathParams.size",mapped.size(),is(2)); + assertThat("Spec.pathParams", mapped, notNullValue()); + assertThat("Spec.pathParams.size", mapped.size(), is(2)); assertEquals("b", mapped.get("var1"), "Spec.pathParams[var1]"); assertEquals("d", mapped.get("var2"), "Spec.pathParams[var2]"); } @@ -222,16 +222,16 @@ public class UriTemplatePathSpecTest assertEquals(4, spec.getPathDepth(), "Spec.pathDepth"); assertEquals(PathSpecGroup.MIDDLE_GLOB, spec.getGroup(), "Spec.group"); - assertDetectedVars(spec,"var1","var2","var3"); + assertDetectedVars(spec, "var1", "var2", "var3"); - assertMatches(spec,"/a/b/c/d"); - assertNotMatches(spec,"/a/bc/d/e"); - assertNotMatches(spec,"/a/c/d/e"); - assertNotMatches(spec,"/a//d/e"); + assertMatches(spec, "/a/b/c/d"); + assertNotMatches(spec, "/a/bc/d/e"); + assertNotMatches(spec, "/a/c/d/e"); + assertNotMatches(spec, "/a//d/e"); Map mapped = spec.getPathParams("/a/b/c/d"); - assertThat("Spec.pathParams",mapped,notNullValue()); - assertThat("Spec.pathParams.size",mapped.size(),is(3)); + assertThat("Spec.pathParams", mapped, notNullValue()); + assertThat("Spec.pathParams.size", mapped.size(), is(3)); assertEquals("a", mapped.get("var1"), "Spec.pathParams[var1]"); assertEquals("c", mapped.get("var2"), "Spec.pathParams[var2]"); assertEquals("d", mapped.get("var3"), "Spec.pathParams[var3]"); @@ -246,16 +246,16 @@ public class UriTemplatePathSpecTest assertEquals(3, spec.getPathDepth(), "Spec.pathDepth"); assertEquals(PathSpecGroup.PREFIX_GLOB, spec.getGroup(), "Spec.group"); - assertDetectedVars(spec,"var1","var2"); + assertDetectedVars(spec, "var1", "var2"); - assertMatches(spec,"/a/b/c"); - assertNotMatches(spec,"/a/bc"); - assertNotMatches(spec,"/a/b/"); - assertNotMatches(spec,"/a/b"); + assertMatches(spec, "/a/b/c"); + assertNotMatches(spec, "/a/bc"); + assertNotMatches(spec, "/a/b/"); + assertNotMatches(spec, "/a/b"); Map mapped = spec.getPathParams("/a/b/c"); - assertThat("Spec.pathParams",mapped,notNullValue()); - assertThat("Spec.pathParams.size",mapped.size(),is(2)); + assertThat("Spec.pathParams", mapped, notNullValue()); + assertThat("Spec.pathParams.size", mapped.size(), is(2)); assertEquals("b", mapped.get("var1"), "Spec.pathParams[var1]"); assertEquals("c", mapped.get("var2"), "Spec.pathParams[var2]"); } @@ -269,16 +269,16 @@ public class UriTemplatePathSpecTest assertEquals(1, spec.getPathDepth(), "Spec.pathDepth"); assertEquals(PathSpecGroup.PREFIX_GLOB, spec.getGroup(), "Spec.group"); - assertDetectedVars(spec,"var1"); + assertDetectedVars(spec, "var1"); - assertMatches(spec,"/a"); - assertNotMatches(spec,"/"); - assertNotMatches(spec,"/a/b"); - assertNotMatches(spec,"/a/b/c"); + assertMatches(spec, "/a"); + assertNotMatches(spec, "/"); + assertNotMatches(spec, "/a/b"); + assertNotMatches(spec, "/a/b/c"); Map mapped = spec.getPathParams("/a"); - assertThat("Spec.pathParams",mapped,notNullValue()); - assertThat("Spec.pathParams.size",mapped.size(),is(1)); + assertThat("Spec.pathParams", mapped, notNullValue()); + assertThat("Spec.pathParams.size", mapped.size(), is(1)); assertEquals("a", mapped.get("var1"), "Spec.pathParams[var1]"); } } diff --git a/jetty-http2/http2-client/pom.xml b/jetty-http2/http2-client/pom.xml index 39a188c80bf..d8dcc21ccc3 100644 --- a/jetty-http2/http2-client/pom.xml +++ b/jetty-http2/http2-client/pom.xml @@ -1,6 +1,5 @@ - + org.eclipse.jetty.http2 http2-parent @@ -21,9 +20,7 @@ maven-surefire-plugin - @{argLine} ${jetty.surefire.argLine} - --add-reads org.eclipse.jetty.http2.client=jetty.servlet.api - --add-modules jetty.servlet.api + @{argLine} ${jetty.surefire.argLine} --add-reads org.eclipse.jetty.http2.client=jetty.servlet.api --add-modules jetty.servlet.api diff --git a/jetty-http2/http2-client/src/main/java/org/eclipse/jetty/http2/client/HTTP2ClientConnectionFactory.java b/jetty-http2/http2-client/src/main/java/org/eclipse/jetty/http2/client/HTTP2ClientConnectionFactory.java index 5236e9e143e..10111da82a0 100644 --- a/jetty-http2/http2-client/src/main/java/org/eclipse/jetty/http2/client/HTTP2ClientConnectionFactory.java +++ b/jetty-http2/http2-client/src/main/java/org/eclipse/jetty/http2/client/HTTP2ClientConnectionFactory.java @@ -69,7 +69,7 @@ public class HTTP2ClientConnectionFactory implements ClientConnectionFactory parser.setMaxSettingsKeys(client.getMaxSettingsKeys()); HTTP2ClientConnection connection = new HTTP2ClientConnection(client, byteBufferPool, executor, endPoint, - parser, session, client.getInputBufferSize(), promise, listener); + parser, session, client.getInputBufferSize(), promise, listener); connection.addListener(connectionListener); return customize(connection, context); } diff --git a/jetty-http2/http2-client/src/test/java/org/eclipse/jetty/http2/client/AbstractTest.java b/jetty-http2/http2-client/src/test/java/org/eclipse/jetty/http2/client/AbstractTest.java index f056d1835a1..0d620a0ecee 100644 --- a/jetty-http2/http2-client/src/test/java/org/eclipse/jetty/http2/client/AbstractTest.java +++ b/jetty-http2/http2-client/src/test/java/org/eclipse/jetty/http2/client/AbstractTest.java @@ -20,7 +20,6 @@ package org.eclipse.jetty.http2.client; import java.net.InetSocketAddress; import java.util.concurrent.TimeUnit; - import javax.servlet.http.HttpServlet; import org.eclipse.jetty.http.HostPortHttpField; diff --git a/jetty-http2/http2-client/src/test/java/org/eclipse/jetty/http2/client/AsyncIOTest.java b/jetty-http2/http2-client/src/test/java/org/eclipse/jetty/http2/client/AsyncIOTest.java index 75a329ed132..a1e3050ce97 100644 --- a/jetty-http2/http2-client/src/test/java/org/eclipse/jetty/http2/client/AsyncIOTest.java +++ b/jetty-http2/http2-client/src/test/java/org/eclipse/jetty/http2/client/AsyncIOTest.java @@ -18,16 +18,12 @@ package org.eclipse.jetty.http2.client; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertTrue; - import java.io.IOException; import java.io.InterruptedIOException; import java.nio.ByteBuffer; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; - import javax.servlet.AsyncContext; import javax.servlet.ReadListener; import javax.servlet.ServletException; @@ -44,9 +40,11 @@ import org.eclipse.jetty.http2.frames.DataFrame; import org.eclipse.jetty.http2.frames.HeadersFrame; import org.eclipse.jetty.util.Callback; import org.eclipse.jetty.util.FuturePromise; - import org.junit.jupiter.api.Test; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + public class AsyncIOTest extends AbstractTest { @Test diff --git a/jetty-http2/http2-client/src/test/java/org/eclipse/jetty/http2/client/AsyncServletTest.java b/jetty-http2/http2-client/src/test/java/org/eclipse/jetty/http2/client/AsyncServletTest.java index 67e67cbedbf..f461659cafb 100644 --- a/jetty-http2/http2-client/src/test/java/org/eclipse/jetty/http2/client/AsyncServletTest.java +++ b/jetty-http2/http2-client/src/test/java/org/eclipse/jetty/http2/client/AsyncServletTest.java @@ -18,18 +18,12 @@ package org.eclipse.jetty.http2.client; -import static org.junit.jupiter.api.Assertions.assertArrayEquals; -import static org.junit.jupiter.api.Assertions.assertFalse; -import static org.junit.jupiter.api.Assertions.assertThrows; -import static org.junit.jupiter.api.Assertions.assertTrue; - import java.io.ByteArrayOutputStream; import java.io.IOException; import java.util.Random; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicReference; - import javax.servlet.AsyncContext; import javax.servlet.AsyncEvent; import javax.servlet.AsyncListener; @@ -60,9 +54,13 @@ import org.eclipse.jetty.util.BufferUtil; import org.eclipse.jetty.util.Callback; import org.eclipse.jetty.util.FuturePromise; import org.eclipse.jetty.util.Promise; - import org.junit.jupiter.api.Test; +import static org.junit.jupiter.api.Assertions.assertArrayEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + public class AsyncServletTest extends AbstractTest { @Test @@ -237,11 +235,12 @@ public class AsyncServletTest extends AbstractTest ServletOutputStream output = response.getOutputStream(); assertThrows(IOException.class, - () -> { - // Large writes or explicit flush() must - // fail because the stream has been reset. - output.flush(); - }); + () -> + { + // Large writes or explicit flush() must + // fail because the stream has been reset. + output.flush(); + }); } @Test diff --git a/jetty-http2/http2-client/src/test/java/org/eclipse/jetty/http2/client/ConnectTimeoutTest.java b/jetty-http2/http2-client/src/test/java/org/eclipse/jetty/http2/client/ConnectTimeoutTest.java index 4e84108c705..9b8c6a3daa3 100644 --- a/jetty-http2/http2-client/src/test/java/org/eclipse/jetty/http2/client/ConnectTimeoutTest.java +++ b/jetty-http2/http2-client/src/test/java/org/eclipse/jetty/http2/client/ConnectTimeoutTest.java @@ -18,10 +18,6 @@ package org.eclipse.jetty.http2.client; -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.instanceOf; -import static org.junit.jupiter.api.Assertions.assertTrue; - import java.io.IOException; import java.net.InetSocketAddress; import java.net.Socket; @@ -35,6 +31,10 @@ import org.eclipse.jetty.util.Promise; import org.junit.jupiter.api.Assumptions; import org.junit.jupiter.api.Test; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.instanceOf; +import static org.junit.jupiter.api.Assertions.assertTrue; + public class ConnectTimeoutTest extends AbstractTest { @Test @@ -66,7 +66,7 @@ public class ConnectTimeoutTest extends AbstractTest private void assumeConnectTimeout(String host, int port, int connectTimeout) throws IOException { boolean socketTimeout = false; - + try (Socket socket = new Socket()) { // Try to connect to a private address in the 10.x.y.z range. @@ -86,7 +86,7 @@ public class ConnectTimeoutTest extends AbstractTest // Useful when debugging x.printStackTrace(System.err); } - + // Abort the test if we can connect. Assumptions.assumeTrue(socketTimeout, "Should have seen connect timeout"); } diff --git a/jetty-http2/http2-client/src/test/java/org/eclipse/jetty/http2/client/EmptyHttpServlet.java b/jetty-http2/http2-client/src/test/java/org/eclipse/jetty/http2/client/EmptyHttpServlet.java index 9f52bff7abf..630110034d3 100644 --- a/jetty-http2/http2-client/src/test/java/org/eclipse/jetty/http2/client/EmptyHttpServlet.java +++ b/jetty-http2/http2-client/src/test/java/org/eclipse/jetty/http2/client/EmptyHttpServlet.java @@ -19,7 +19,6 @@ package org.eclipse.jetty.http2.client; import java.io.IOException; - import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; diff --git a/jetty-http2/http2-client/src/test/java/org/eclipse/jetty/http2/client/FlowControlStalledTest.java b/jetty-http2/http2-client/src/test/java/org/eclipse/jetty/http2/client/FlowControlStalledTest.java index 095fe315c17..cf8608d6748 100644 --- a/jetty-http2/http2-client/src/test/java/org/eclipse/jetty/http2/client/FlowControlStalledTest.java +++ b/jetty-http2/http2-client/src/test/java/org/eclipse/jetty/http2/client/FlowControlStalledTest.java @@ -18,9 +18,6 @@ package org.eclipse.jetty.http2.client; -import static org.junit.jupiter.api.Assertions.assertFalse; -import static org.junit.jupiter.api.Assertions.assertTrue; - import java.net.InetSocketAddress; import java.nio.ByteBuffer; import java.util.ArrayDeque; @@ -56,9 +53,11 @@ import org.eclipse.jetty.util.FuturePromise; import org.eclipse.jetty.util.Promise; import org.eclipse.jetty.util.thread.QueuedThreadPool; import org.junit.jupiter.api.AfterEach; - import org.junit.jupiter.api.Test; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; + public class FlowControlStalledTest { protected ServerConnector connector; diff --git a/jetty-http2/http2-client/src/test/java/org/eclipse/jetty/http2/client/FlowControlStrategyTest.java b/jetty-http2/http2-client/src/test/java/org/eclipse/jetty/http2/client/FlowControlStrategyTest.java index 1d188e6d459..9fe509df5f2 100644 --- a/jetty-http2/http2-client/src/test/java/org/eclipse/jetty/http2/client/FlowControlStrategyTest.java +++ b/jetty-http2/http2-client/src/test/java/org/eclipse/jetty/http2/client/FlowControlStrategyTest.java @@ -18,13 +18,6 @@ package org.eclipse.jetty.http2.client; -import static org.junit.jupiter.api.Assertions.assertArrayEquals; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertFalse; -import static org.junit.jupiter.api.Assertions.assertThrows; -import static org.junit.jupiter.api.Assertions.assertTrue; -import static org.junit.jupiter.api.Assertions.fail; - import java.net.InetSocketAddress; import java.nio.ByteBuffer; import java.util.ArrayList; @@ -74,10 +67,15 @@ import org.eclipse.jetty.util.FuturePromise; import org.eclipse.jetty.util.Promise; import org.eclipse.jetty.util.thread.QueuedThreadPool; import org.junit.jupiter.api.AfterEach; - -import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.Test; +import static org.junit.jupiter.api.Assertions.assertArrayEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.fail; + public abstract class FlowControlStrategyTest { protected ServerConnector connector; @@ -505,7 +503,7 @@ public abstract class FlowControlStrategyTest private void checkThatWeAreFlowControlStalled(Exchanger exchanger) throws Exception { assertThrows(TimeoutException.class, - () -> exchanger.exchange(null, 1, TimeUnit.SECONDS)); + () -> exchanger.exchange(null, 1, TimeUnit.SECONDS)); } @Test @@ -605,7 +603,9 @@ public abstract class FlowControlStrategyTest // Consume the data of the first response. // This will open up the session window, allowing the fourth stream to send data. for (Callback callback : callbacks1) + { callback.succeeded(); + } assertTrue(latch.await(5, TimeUnit.SECONDS)); } diff --git a/jetty-http2/http2-client/src/test/java/org/eclipse/jetty/http2/client/FlowControlWindowsTest.java b/jetty-http2/http2-client/src/test/java/org/eclipse/jetty/http2/client/FlowControlWindowsTest.java index f96f714b07d..2b2bb275cd6 100644 --- a/jetty-http2/http2-client/src/test/java/org/eclipse/jetty/http2/client/FlowControlWindowsTest.java +++ b/jetty-http2/http2-client/src/test/java/org/eclipse/jetty/http2/client/FlowControlWindowsTest.java @@ -18,9 +18,6 @@ package org.eclipse.jetty.http2.client; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertTrue; - import java.net.InetSocketAddress; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; @@ -48,6 +45,9 @@ import org.eclipse.jetty.util.thread.QueuedThreadPool; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.Test; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + public class FlowControlWindowsTest { private Server server; diff --git a/jetty-http2/http2-client/src/test/java/org/eclipse/jetty/http2/client/HTTP2Test.java b/jetty-http2/http2-client/src/test/java/org/eclipse/jetty/http2/client/HTTP2Test.java index 367332b1b0d..132733ee8c2 100644 --- a/jetty-http2/http2-client/src/test/java/org/eclipse/jetty/http2/client/HTTP2Test.java +++ b/jetty-http2/http2-client/src/test/java/org/eclipse/jetty/http2/client/HTTP2Test.java @@ -18,10 +18,6 @@ package org.eclipse.jetty.http2.client; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertFalse; -import static org.junit.jupiter.api.Assertions.assertTrue; - import java.io.IOException; import java.nio.ByteBuffer; import java.nio.channels.WritePendingException; @@ -31,7 +27,6 @@ import java.util.Map; import java.util.Random; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; - import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; @@ -61,9 +56,12 @@ import org.eclipse.jetty.util.FuturePromise; import org.eclipse.jetty.util.IO; import org.eclipse.jetty.util.Jetty; import org.eclipse.jetty.util.Promise; - import org.junit.jupiter.api.Test; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; + public class HTTP2Test extends AbstractTest { @Test diff --git a/jetty-http2/http2-client/src/test/java/org/eclipse/jetty/http2/client/IdleTimeoutTest.java b/jetty-http2/http2-client/src/test/java/org/eclipse/jetty/http2/client/IdleTimeoutTest.java index a645ee64479..aaf8a7af2b0 100644 --- a/jetty-http2/http2-client/src/test/java/org/eclipse/jetty/http2/client/IdleTimeoutTest.java +++ b/jetty-http2/http2-client/src/test/java/org/eclipse/jetty/http2/client/IdleTimeoutTest.java @@ -16,22 +16,14 @@ // ======================================================================== // - package org.eclipse.jetty.http2.client; -import static org.hamcrest.MatcherAssert.assertThat; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertFalse; -import static org.junit.jupiter.api.Assertions.assertTrue; -import static org.junit.jupiter.api.Assertions.fail; - import java.io.IOException; import java.nio.ByteBuffer; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; import java.util.concurrent.atomic.AtomicReference; - import javax.servlet.ServletException; import javax.servlet.ServletInputStream; import javax.servlet.http.HttpServlet; @@ -63,9 +55,14 @@ import org.eclipse.jetty.util.Promise; import org.eclipse.jetty.util.log.Log; import org.eclipse.jetty.util.thread.QueuedThreadPool; import org.hamcrest.Matchers; - import org.junit.jupiter.api.Test; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.fail; + public class IdleTimeoutTest extends AbstractTest { private final int idleTimeout = 1000; diff --git a/jetty-http2/http2-client/src/test/java/org/eclipse/jetty/http2/client/InterleavingTest.java b/jetty-http2/http2-client/src/test/java/org/eclipse/jetty/http2/client/InterleavingTest.java index f6dcc5f0bd6..306278c822a 100644 --- a/jetty-http2/http2-client/src/test/java/org/eclipse/jetty/http2/client/InterleavingTest.java +++ b/jetty-http2/http2-client/src/test/java/org/eclipse/jetty/http2/client/InterleavingTest.java @@ -18,12 +18,6 @@ package org.eclipse.jetty.http2.client; -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.lessThanOrEqualTo; -import static org.junit.jupiter.api.Assertions.assertArrayEquals; -import static org.junit.jupiter.api.Assertions.assertTrue; -import static org.junit.jupiter.api.Assertions.fail; - import java.io.ByteArrayOutputStream; import java.nio.ByteBuffer; import java.util.ArrayList; @@ -55,6 +49,12 @@ import org.eclipse.jetty.util.log.Log; import org.eclipse.jetty.util.log.Logger; import org.junit.jupiter.api.Test; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.lessThanOrEqualTo; +import static org.junit.jupiter.api.Assertions.assertArrayEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.fail; + public class InterleavingTest extends AbstractTest { @Test @@ -195,7 +195,9 @@ public class InterleavingTest extends AbstractTest { logger.debug("stream {} interleaved lengths = {}", stream, lengths); for (Integer length : lengths) + { assertThat(length, lessThanOrEqualTo(maxFrameSize)); + } }); } diff --git a/jetty-http2/http2-client/src/test/java/org/eclipse/jetty/http2/client/InvalidServerTest.java b/jetty-http2/http2-client/src/test/java/org/eclipse/jetty/http2/client/InvalidServerTest.java index 82c2eaac274..6aeca90b8bd 100644 --- a/jetty-http2/http2-client/src/test/java/org/eclipse/jetty/http2/client/InvalidServerTest.java +++ b/jetty-http2/http2-client/src/test/java/org/eclipse/jetty/http2/client/InvalidServerTest.java @@ -18,9 +18,6 @@ package org.eclipse.jetty.http2.client; -import static org.junit.jupiter.api.Assertions.assertNotNull; -import static org.junit.jupiter.api.Assertions.assertTrue; - import java.io.InputStream; import java.io.OutputStream; import java.net.InetSocketAddress; @@ -34,6 +31,9 @@ import org.eclipse.jetty.http2.api.Session; import org.eclipse.jetty.util.Promise; import org.junit.jupiter.api.Test; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertTrue; + public class InvalidServerTest extends AbstractTest { @Test diff --git a/jetty-http2/http2-client/src/test/java/org/eclipse/jetty/http2/client/MaxPushedStreamsTest.java b/jetty-http2/http2-client/src/test/java/org/eclipse/jetty/http2/client/MaxPushedStreamsTest.java index 3bb52113d99..1890fd36458 100644 --- a/jetty-http2/http2-client/src/test/java/org/eclipse/jetty/http2/client/MaxPushedStreamsTest.java +++ b/jetty-http2/http2-client/src/test/java/org/eclipse/jetty/http2/client/MaxPushedStreamsTest.java @@ -65,49 +65,57 @@ public class MaxPushedStreamsTest extends AbstractTest // Trick the server into thinking it can push unlimited streams. ((HTTP2Session)stream.getSession()).setMaxLocalStreams(-1); - BiFunction, Stream, List> add = (l, s) -> { l.add(s); return l; }; - BinaryOperator> addAll = (l1, l2) -> { l1.addAll(l2); return l1; }; + BiFunction, Stream, List> add = (l, s) -> + { + l.add(s); + return l; + }; + BinaryOperator> addAll = (l1, l2) -> + { + l1.addAll(l2); + return l1; + }; CompletableFuture> result = CompletableFuture.completedFuture(new ArrayList<>()); // Push maxPushed resources... IntStream.range(0, maxPushed) - .mapToObj(i -> new PushPromiseFrame(stream.getId(), 0, newRequest("GET", "/push_" + i, new HttpFields()))) - .map(pushFrame -> + .mapToObj(i -> new PushPromiseFrame(stream.getId(), 0, newRequest("GET", "/push_" + i, new HttpFields()))) + .map(pushFrame -> + { + Promise.Completable promise = new Promise.Completable<>(); + stream.push(pushFrame, promise, new Stream.Listener.Adapter()); + return promise; + }) + // ... wait for the pushed streams... + .reduce(result, (cfList, cfStream) -> cfList.thenCombine(cfStream, add), + (cfList1, cfList2) -> cfList1.thenCombine(cfList2, addAll)) + // ... then push one extra stream, the client must reject it... + .thenApply(streams -> + { + PushPromiseFrame extraPushFrame = new PushPromiseFrame(stream.getId(), 0, newRequest("GET", "/push_extra", new HttpFields())); + FuturePromise extraPromise = new FuturePromise<>(); + stream.push(extraPushFrame, extraPromise, new Stream.Listener.Adapter() { - Promise.Completable promise = new Promise.Completable<>(); - stream.push(pushFrame, promise, new Stream.Listener.Adapter()); - return promise; - }) - // ... wait for the pushed streams... - .reduce(result, (cfList, cfStream) -> cfList.thenCombine(cfStream, add), - (cfList1, cfList2) -> cfList1.thenCombine(cfList2, addAll)) - // ... then push one extra stream, the client must reject it... - .thenApply(streams -> - { - PushPromiseFrame extraPushFrame = new PushPromiseFrame(stream.getId(), 0, newRequest("GET", "/push_extra", new HttpFields())); - FuturePromise extraPromise = new FuturePromise<>(); - stream.push(extraPushFrame, extraPromise, new Stream.Listener.Adapter() + @Override + public void onReset(Stream stream, ResetFrame frame) { - @Override - public void onReset(Stream stream, ResetFrame frame) - { - assertEquals(ErrorCode.REFUSED_STREAM_ERROR.code, frame.getError()); - resetLatch.countDown(); - } - }); - return streams; - }) - // ... then send the data for the valid pushed streams... - .thenAccept(streams -> streams.forEach(pushedStream -> - { - DataFrame data = new DataFrame(pushedStream.getId(), BufferUtil.EMPTY_BUFFER, true); - pushedStream.data(data, Callback.NOOP); - })) - // ... then send the response. - .thenRun(() -> - { - MetaData.Response response = new MetaData.Response(HttpVersion.HTTP_2, HttpStatus.OK_200, new HttpFields()); - stream.headers(new HeadersFrame(stream.getId(), response, null, true), Callback.NOOP); + assertEquals(ErrorCode.REFUSED_STREAM_ERROR.code, frame.getError()); + resetLatch.countDown(); + } }); + return streams; + }) + // ... then send the data for the valid pushed streams... + .thenAccept(streams -> streams.forEach(pushedStream -> + { + DataFrame data = new DataFrame(pushedStream.getId(), BufferUtil.EMPTY_BUFFER, true); + pushedStream.data(data, Callback.NOOP); + })) + // ... then send the response. + .thenRun(() -> + { + MetaData.Response response = new MetaData.Response(HttpVersion.HTTP_2, HttpStatus.OK_200, new HttpFields()); + stream.headers(new HeadersFrame(stream.getId(), response, null, true), Callback.NOOP); + }); return null; } }); diff --git a/jetty-http2/http2-client/src/test/java/org/eclipse/jetty/http2/client/PingTest.java b/jetty-http2/http2-client/src/test/java/org/eclipse/jetty/http2/client/PingTest.java index 0480950b9fd..61e4ef15a79 100644 --- a/jetty-http2/http2-client/src/test/java/org/eclipse/jetty/http2/client/PingTest.java +++ b/jetty-http2/http2-client/src/test/java/org/eclipse/jetty/http2/client/PingTest.java @@ -18,9 +18,6 @@ package org.eclipse.jetty.http2.client; -import static org.junit.jupiter.api.Assertions.assertArrayEquals; -import static org.junit.jupiter.api.Assertions.assertTrue; - import java.util.Random; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; @@ -29,9 +26,11 @@ import org.eclipse.jetty.http2.api.Session; import org.eclipse.jetty.http2.api.server.ServerSessionListener; import org.eclipse.jetty.http2.frames.PingFrame; import org.eclipse.jetty.util.Callback; - import org.junit.jupiter.api.Test; +import static org.junit.jupiter.api.Assertions.assertArrayEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + public class PingTest extends AbstractTest { @Test diff --git a/jetty-http2/http2-client/src/test/java/org/eclipse/jetty/http2/client/PrefaceTest.java b/jetty-http2/http2-client/src/test/java/org/eclipse/jetty/http2/client/PrefaceTest.java index 44b61f22123..6177fd68b95 100644 --- a/jetty-http2/http2-client/src/test/java/org/eclipse/jetty/http2/client/PrefaceTest.java +++ b/jetty-http2/http2-client/src/test/java/org/eclipse/jetty/http2/client/PrefaceTest.java @@ -18,12 +18,6 @@ package org.eclipse.jetty.http2.client; -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.greaterThanOrEqualTo; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertFalse; -import static org.junit.jupiter.api.Assertions.assertTrue; - import java.net.InetSocketAddress; import java.nio.ByteBuffer; import java.nio.channels.SocketChannel; @@ -65,6 +59,12 @@ import org.eclipse.jetty.util.Callback; import org.eclipse.jetty.util.Promise; import org.junit.jupiter.api.Test; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.greaterThanOrEqualTo; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; + public class PrefaceTest extends AbstractTest { @Test @@ -238,8 +238,8 @@ public class PrefaceTest extends AbstractTest { socket.connect(new InetSocketAddress("localhost", connector.getLocalPort())); - String upgradeRequest = "" + - "GET /one HTTP/1.1\r\n" + + String upgradeRequest = + "GET /one HTTP/1.1\r\n" + "Host: localhost\r\n" + "Connection: Upgrade, HTTP2-Settings\r\n" + "Upgrade: h2c\r\n" + @@ -254,7 +254,8 @@ public class PrefaceTest extends AbstractTest // The 101 response is the reply to the client preface SETTINGS frame. ByteBuffer buffer = byteBufferPool.acquire(1024, true); - http1: while (true) + http1: + while (true) { BufferUtil.clearToFill(buffer); int read = socket.read(buffer); diff --git a/jetty-http2/http2-client/src/test/java/org/eclipse/jetty/http2/client/PriorityTest.java b/jetty-http2/http2-client/src/test/java/org/eclipse/jetty/http2/client/PriorityTest.java index 14fb95436cf..25a80e45f54 100644 --- a/jetty-http2/http2-client/src/test/java/org/eclipse/jetty/http2/client/PriorityTest.java +++ b/jetty-http2/http2-client/src/test/java/org/eclipse/jetty/http2/client/PriorityTest.java @@ -18,10 +18,6 @@ package org.eclipse.jetty.http2.client; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertNotNull; -import static org.junit.jupiter.api.Assertions.assertTrue; - import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; @@ -36,9 +32,12 @@ import org.eclipse.jetty.http2.frames.PriorityFrame; import org.eclipse.jetty.util.Callback; import org.eclipse.jetty.util.FuturePromise; import org.eclipse.jetty.util.Promise; - import org.junit.jupiter.api.Test; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertTrue; + public class PriorityTest extends AbstractTest { @Test diff --git a/jetty-http2/http2-client/src/test/java/org/eclipse/jetty/http2/client/ProxyProtocolTest.java b/jetty-http2/http2-client/src/test/java/org/eclipse/jetty/http2/client/ProxyProtocolTest.java index d63ab045dd5..e5557b1ae91 100644 --- a/jetty-http2/http2-client/src/test/java/org/eclipse/jetty/http2/client/ProxyProtocolTest.java +++ b/jetty-http2/http2-client/src/test/java/org/eclipse/jetty/http2/client/ProxyProtocolTest.java @@ -96,12 +96,12 @@ public class ProxyProtocolTest { try { - assertEquals("1.2.3.4",request.getRemoteAddr()); - assertEquals(1111,request.getRemotePort()); - assertEquals("5.6.7.8",request.getLocalAddr()); - assertEquals(2222,request.getLocalPort()); + assertEquals("1.2.3.4", request.getRemoteAddr()); + assertEquals(1111, request.getRemotePort()); + assertEquals("5.6.7.8", request.getLocalAddr()); + assertEquals(2222, request.getLocalPort()); } - catch(Throwable th) + catch (Throwable th) { th.printStackTrace(); response.setStatus(500); @@ -137,7 +137,7 @@ public class ProxyProtocolTest }); assertTrue(latch.await(5, TimeUnit.SECONDS)); } - + @Test public void test_PROXY_GET_v2() throws Exception { @@ -148,16 +148,16 @@ public class ProxyProtocolTest { try { - assertEquals("10.0.0.4",request.getRemoteAddr()); - assertEquals(33824,request.getRemotePort()); - assertEquals("10.0.0.5",request.getLocalAddr()); - assertEquals(8888,request.getLocalPort()); + assertEquals("10.0.0.4", request.getRemoteAddr()); + assertEquals(33824, request.getRemotePort()); + assertEquals("10.0.0.5", request.getLocalAddr()); + assertEquals(8888, request.getLocalPort()); EndPoint endPoint = baseRequest.getHttpChannel().getEndPoint(); assertThat(endPoint, instanceOf(ProxyConnectionFactory.ProxyEndPoint.class)); ProxyConnectionFactory.ProxyEndPoint proxyEndPoint = (ProxyConnectionFactory.ProxyEndPoint)endPoint; assertNotNull(proxyEndPoint.getAttribute(ProxyConnectionFactory.TLS_VERSION)); } - catch(Throwable th) + catch (Throwable th) { th.printStackTrace(); response.setStatus(500); diff --git a/jetty-http2/http2-client/src/test/java/org/eclipse/jetty/http2/client/ProxyTest.java b/jetty-http2/http2-client/src/test/java/org/eclipse/jetty/http2/client/ProxyTest.java index 3afb7645fed..1790ce2c1bd 100644 --- a/jetty-http2/http2-client/src/test/java/org/eclipse/jetty/http2/client/ProxyTest.java +++ b/jetty-http2/http2-client/src/test/java/org/eclipse/jetty/http2/client/ProxyTest.java @@ -18,15 +18,12 @@ package org.eclipse.jetty.http2.client; -import static org.junit.jupiter.api.Assertions.assertTrue; - import java.io.IOException; import java.net.InetSocketAddress; import java.util.HashMap; import java.util.Map; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; - import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; @@ -56,6 +53,8 @@ import org.eclipse.jetty.util.thread.QueuedThreadPool; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.Test; +import static org.junit.jupiter.api.Assertions.assertTrue; + public class ProxyTest { private HTTP2Client client; diff --git a/jetty-http2/http2-client/src/test/java/org/eclipse/jetty/http2/client/PushCacheFilterTest.java b/jetty-http2/http2-client/src/test/java/org/eclipse/jetty/http2/client/PushCacheFilterTest.java index f62ac44d2bd..795ff56237a 100644 --- a/jetty-http2/http2-client/src/test/java/org/eclipse/jetty/http2/client/PushCacheFilterTest.java +++ b/jetty-http2/http2-client/src/test/java/org/eclipse/jetty/http2/client/PushCacheFilterTest.java @@ -25,7 +25,6 @@ import java.util.HashMap; import java.util.Map; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; - import javax.servlet.DispatcherType; import javax.servlet.ServletOutputStream; import javax.servlet.http.HttpServlet; @@ -742,7 +741,7 @@ public class PushCacheFilterTest extends AbstractTest { String name = "foo"; String value = "bar"; - final String primaryResource = "/primary.html?"+name + "=" +value; + final String primaryResource = "/primary.html?" + name + "=" + value; final String secondaryResource = "/secondary.html?" + name + "=" + value; start(new HttpServlet() { diff --git a/jetty-http2/http2-client/src/test/java/org/eclipse/jetty/http2/client/RawHTTP2ProxyTest.java b/jetty-http2/http2-client/src/test/java/org/eclipse/jetty/http2/client/RawHTTP2ProxyTest.java index 6d3a6e1d37e..2f5f47c6ecd 100644 --- a/jetty-http2/http2-client/src/test/java/org/eclipse/jetty/http2/client/RawHTTP2ProxyTest.java +++ b/jetty-http2/http2-client/src/test/java/org/eclipse/jetty/http2/client/RawHTTP2ProxyTest.java @@ -18,9 +18,6 @@ package org.eclipse.jetty.http2.client; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertTrue; - import java.net.InetSocketAddress; import java.nio.ByteBuffer; import java.util.ArrayDeque; @@ -60,9 +57,11 @@ import org.eclipse.jetty.util.log.Log; import org.eclipse.jetty.util.log.Logger; import org.eclipse.jetty.util.thread.QueuedThreadPool; import org.junit.jupiter.api.AfterEach; - import org.junit.jupiter.api.Test; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + public class RawHTTP2ProxyTest { private static final Logger LOGGER = Log.getLogger(RawHTTP2ProxyTest.class); @@ -110,7 +109,6 @@ public class RawHTTP2ProxyTest } } - @Test public void testRawHTTP2Proxy() throws Exception { @@ -569,7 +567,7 @@ public class RawHTTP2ProxyTest if (frameInfo != null) { serverToProxyStream = entry.getKey(); - proxyToClientStream = streams.get(serverToProxyStream); + proxyToClientStream = streams.get(serverToProxyStream); break; } } diff --git a/jetty-http2/http2-client/src/test/java/org/eclipse/jetty/http2/client/SessionFailureTest.java b/jetty-http2/http2-client/src/test/java/org/eclipse/jetty/http2/client/SessionFailureTest.java index 8dfbe455862..e0ea4b8b880 100644 --- a/jetty-http2/http2-client/src/test/java/org/eclipse/jetty/http2/client/SessionFailureTest.java +++ b/jetty-http2/http2-client/src/test/java/org/eclipse/jetty/http2/client/SessionFailureTest.java @@ -18,10 +18,6 @@ package org.eclipse.jetty.http2.client; -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.lessThanOrEqualTo; -import static org.junit.jupiter.api.Assertions.assertTrue; - import java.io.InputStream; import java.io.OutputStream; import java.net.Socket; @@ -38,6 +34,10 @@ import org.eclipse.jetty.util.Callback; import org.eclipse.jetty.util.Promise; import org.junit.jupiter.api.Test; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.lessThanOrEqualTo; +import static org.junit.jupiter.api.Assertions.assertTrue; + public class SessionFailureTest extends AbstractTest { @Test @@ -125,7 +125,7 @@ public class SessionFailureTest extends AbstractTest long now = System.nanoTime(); while (((HTTP2Session)session).getEndPoint().isOpen()) { - assertThat(TimeUnit.NANOSECONDS.toSeconds(now-start), lessThanOrEqualTo(5L)); + assertThat(TimeUnit.NANOSECONDS.toSeconds(now - start), lessThanOrEqualTo(5L)); Thread.sleep(10); now = System.nanoTime(); diff --git a/jetty-http2/http2-client/src/test/java/org/eclipse/jetty/http2/client/SmallThreadPoolLoadTest.java b/jetty-http2/http2-client/src/test/java/org/eclipse/jetty/http2/client/SmallThreadPoolLoadTest.java index 622e14523d3..e6a682af0c8 100644 --- a/jetty-http2/http2-client/src/test/java/org/eclipse/jetty/http2/client/SmallThreadPoolLoadTest.java +++ b/jetty-http2/http2-client/src/test/java/org/eclipse/jetty/http2/client/SmallThreadPoolLoadTest.java @@ -18,9 +18,6 @@ package org.eclipse.jetty.http2.client; -import static org.hamcrest.MatcherAssert.assertThat; -import static org.junit.jupiter.api.Assertions.assertTrue; - import java.io.IOException; import java.nio.ByteBuffer; import java.util.Locale; @@ -30,7 +27,6 @@ import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicLong; import java.util.stream.IntStream; - import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; @@ -55,10 +51,12 @@ import org.eclipse.jetty.util.log.Logger; import org.eclipse.jetty.util.thread.QueuedThreadPool; import org.eclipse.jetty.util.thread.Scheduler; import org.hamcrest.Matchers; - import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.Test; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.junit.jupiter.api.Assertions.assertTrue; + @Disabled public class SmallThreadPoolLoadTest extends AbstractTest { @@ -88,10 +86,10 @@ public class SmallThreadPoolLoadTest extends AbstractTest int runs = 10; int iterations = 512; boolean result = IntStream.range(0, 16).parallel() - .mapToObj(i -> IntStream.range(0, runs) - .mapToObj(j -> run(session, iterations)) - .reduce(true, (acc, res) -> acc && res)) - .reduce(true, (acc, res) -> acc && res); + .mapToObj(i -> IntStream.range(0, runs) + .mapToObj(j -> run(session, iterations)) + .reduce(true, (acc, res) -> acc && res)) + .reduce(true, (acc, res) -> acc && res); assertTrue(result); } @@ -108,8 +106,8 @@ public class SmallThreadPoolLoadTest extends AbstractTest Scheduler.Task task = client.getScheduler().schedule(() -> { logger.warn("Interrupting test, it is taking too long{}Server:{}{}{}Client:{}{}", - System.lineSeparator(), System.lineSeparator(), server.dump(), - System.lineSeparator(), System.lineSeparator(), client.dump()); + System.lineSeparator(), System.lineSeparator(), server.dump(), + System.lineSeparator(), System.lineSeparator(), client.dump()); testThread.interrupt(); }, iterations * factor, TimeUnit.MILLISECONDS); @@ -128,9 +126,9 @@ public class SmallThreadPoolLoadTest extends AbstractTest task.cancel(); long elapsed = TimeUnit.NANOSECONDS.toMillis(end - begin); logger.info("{} requests in {} ms, {}/{} success/failure, {} req/s", - iterations, elapsed, - successes, iterations - successes, - elapsed > 0 ? iterations * 1000 / elapsed : -1); + iterations, elapsed, + successes, iterations - successes, + elapsed > 0 ? iterations * 1000 / elapsed : -1); return true; } catch (Exception x) @@ -193,8 +191,8 @@ public class SmallThreadPoolLoadTest extends AbstractTest latch.countDown(); else logger.warn("Request {} took too long{}Server:{}{}{}Client:{}{}", requestId, - System.lineSeparator(), System.lineSeparator(), server.dump(), - System.lineSeparator(), System.lineSeparator(), client.dump()); + System.lineSeparator(), System.lineSeparator(), server.dump(), + System.lineSeparator(), System.lineSeparator(), client.dump()); return !reset.get(); } @@ -215,10 +213,10 @@ public class SmallThreadPoolLoadTest extends AbstractTest } case "POST": { - int content_length=request.getContentLength(); - ByteArrayOutputStream2 bout = new ByteArrayOutputStream2(content_length>0?content_length:16*1024); + int content_length = request.getContentLength(); + ByteArrayOutputStream2 bout = new ByteArrayOutputStream2(content_length > 0 ? content_length : 16 * 1024); IO.copy(request.getInputStream(), bout); - response.getOutputStream().write(bout.getBuf(),0,bout.getCount()); + response.getOutputStream().write(bout.getBuf(), 0, bout.getCount()); break; } } diff --git a/jetty-http2/http2-client/src/test/java/org/eclipse/jetty/http2/client/StreamCloseTest.java b/jetty-http2/http2-client/src/test/java/org/eclipse/jetty/http2/client/StreamCloseTest.java index 6d7306736e6..bb2c05fee59 100644 --- a/jetty-http2/http2-client/src/test/java/org/eclipse/jetty/http2/client/StreamCloseTest.java +++ b/jetty-http2/http2-client/src/test/java/org/eclipse/jetty/http2/client/StreamCloseTest.java @@ -18,10 +18,6 @@ package org.eclipse.jetty.http2.client; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertFalse; -import static org.junit.jupiter.api.Assertions.assertTrue; - import java.nio.ByteBuffer; import java.util.ArrayList; import java.util.List; @@ -45,9 +41,12 @@ import org.eclipse.jetty.http2.frames.ResetFrame; import org.eclipse.jetty.util.Callback; import org.eclipse.jetty.util.FuturePromise; import org.eclipse.jetty.util.Promise; - import org.junit.jupiter.api.Test; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; + public class StreamCloseTest extends AbstractTest { @Test @@ -355,6 +354,8 @@ public class StreamCloseTest extends AbstractTest assertEquals(0, serverSession.getStreams().size()); for (Stream stream : streams) + { assertTrue(stream.isClosed()); + } } } diff --git a/jetty-http2/http2-client/src/test/java/org/eclipse/jetty/http2/client/StreamCountTest.java b/jetty-http2/http2-client/src/test/java/org/eclipse/jetty/http2/client/StreamCountTest.java index fa007d27a62..5227219e067 100644 --- a/jetty-http2/http2-client/src/test/java/org/eclipse/jetty/http2/client/StreamCountTest.java +++ b/jetty-http2/http2-client/src/test/java/org/eclipse/jetty/http2/client/StreamCountTest.java @@ -18,9 +18,6 @@ package org.eclipse.jetty.http2.client; -import static org.junit.jupiter.api.Assertions.assertThrows; -import static org.junit.jupiter.api.Assertions.assertTrue; - import java.util.HashMap; import java.util.Map; import java.util.concurrent.CountDownLatch; @@ -41,9 +38,11 @@ import org.eclipse.jetty.http2.frames.SettingsFrame; import org.eclipse.jetty.util.BufferUtil; import org.eclipse.jetty.util.Callback; import org.eclipse.jetty.util.FuturePromise; - import org.junit.jupiter.api.Test; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + public class StreamCountTest extends AbstractTest { @Test @@ -115,7 +114,7 @@ public class StreamCountTest extends AbstractTest session.newStream(frame2, streamPromise2, new Stream.Listener.Adapter()); assertThrows(ExecutionException.class, - () -> streamPromise2.get(5, TimeUnit.SECONDS)); + () -> streamPromise2.get(5, TimeUnit.SECONDS)); stream1.data(new DataFrame(stream1.getId(), BufferUtil.EMPTY_BUFFER, true), Callback.NOOP); assertTrue(responseLatch.await(5, TimeUnit.SECONDS)); diff --git a/jetty-http2/http2-client/src/test/java/org/eclipse/jetty/http2/client/StreamResetTest.java b/jetty-http2/http2-client/src/test/java/org/eclipse/jetty/http2/client/StreamResetTest.java index ccd3e31f968..f025e90f38b 100644 --- a/jetty-http2/http2-client/src/test/java/org/eclipse/jetty/http2/client/StreamResetTest.java +++ b/jetty-http2/http2-client/src/test/java/org/eclipse/jetty/http2/client/StreamResetTest.java @@ -18,12 +18,6 @@ package org.eclipse.jetty.http2.client; -import static org.hamcrest.MatcherAssert.assertThat; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertFalse; -import static org.junit.jupiter.api.Assertions.assertNotNull; -import static org.junit.jupiter.api.Assertions.assertTrue; - import java.io.IOException; import java.io.InterruptedIOException; import java.nio.ByteBuffer; @@ -38,7 +32,6 @@ import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicLong; import java.util.concurrent.atomic.AtomicReference; - import javax.servlet.AsyncContext; import javax.servlet.ServletOutputStream; import javax.servlet.WriteListener; @@ -79,9 +72,14 @@ import org.eclipse.jetty.util.IO; import org.eclipse.jetty.util.log.StacklessLogging; import org.eclipse.jetty.util.thread.QueuedThreadPool; import org.hamcrest.Matchers; - import org.junit.jupiter.api.Test; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertTrue; + public class StreamResetTest extends AbstractTest { @Test @@ -167,14 +165,14 @@ public class StreamResetTest extends AbstractTest { callback.succeeded(); completable.thenRun(() -> - stream.data(new DataFrame(stream.getId(), ByteBuffer.allocate(16), true), new Callback() + stream.data(new DataFrame(stream.getId(), ByteBuffer.allocate(16), true), new Callback() + { + @Override + public void succeeded() { - @Override - public void succeeded() - { - serverDataLatch.countDown(); - } - })); + serverDataLatch.countDown(); + } + })); } @Override @@ -570,7 +568,7 @@ public class StreamResetTest extends AbstractTest }); Session client = newClient(new Session.Listener.Adapter()); - + MetaData.Request request = newRequest("GET", new HttpFields()); HeadersFrame frame = new HeadersFrame(request, null, false); FuturePromise promise = new FuturePromise<>(); diff --git a/jetty-http2/http2-client/src/test/java/org/eclipse/jetty/http2/client/TrailersTest.java b/jetty-http2/http2-client/src/test/java/org/eclipse/jetty/http2/client/TrailersTest.java index 3c268aa0478..1c756042634 100644 --- a/jetty-http2/http2-client/src/test/java/org/eclipse/jetty/http2/client/TrailersTest.java +++ b/jetty-http2/http2-client/src/test/java/org/eclipse/jetty/http2/client/TrailersTest.java @@ -26,7 +26,6 @@ import java.util.List; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; import java.util.stream.Collectors; - import javax.servlet.ServletInputStream; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; @@ -252,7 +251,7 @@ public class TrailersTest extends AbstractTest Response jettyResponse = jettyRequest.getResponse(); HttpFields trailers = new HttpFields(); jettyResponse.setTrailerFields(() -> - trailers.stream().collect(Collectors.toMap(HttpField::getName, HttpField::getValue))); + trailers.stream().collect(Collectors.toMap(HttpField::getName, HttpField::getValue))); jettyResponse.getOutputStream().write("hello_trailers".getBytes(StandardCharsets.UTF_8)); jettyResponse.flushBuffer(); @@ -340,7 +339,7 @@ public class TrailersTest extends AbstractTest } }); Stream stream = promise.get(5, TimeUnit.SECONDS); - ByteBuffer data = ByteBuffer.wrap( StringUtil.getUtf8Bytes( "hello")); + ByteBuffer data = ByteBuffer.wrap(StringUtil.getUtf8Bytes("hello")); Callback.Completable completable = new Callback.Completable(); stream.data(new DataFrame(stream.getId(), data, false), completable); completable.thenRun(() -> diff --git a/jetty-http2/http2-common/src/main/java/org/eclipse/jetty/http2/BufferingFlowControlStrategy.java b/jetty-http2/http2-common/src/main/java/org/eclipse/jetty/http2/BufferingFlowControlStrategy.java index 993f314b423..a5a57fa2666 100644 --- a/jetty-http2/http2-common/src/main/java/org/eclipse/jetty/http2/BufferingFlowControlStrategy.java +++ b/jetty-http2/http2-common/src/main/java/org/eclipse/jetty/http2/BufferingFlowControlStrategy.java @@ -201,11 +201,11 @@ public class BufferingFlowControlStrategy extends AbstractFlowControlStrategy public String toString() { return String.format("%s@%x[ratio=%.2f,sessionLevel=%s,sessionStallTime=%dms,streamsStallTime=%dms]", - getClass().getSimpleName(), - hashCode(), - bufferRatio, - sessionLevel, - getSessionStallTime(), - getStreamsStallTime()); + getClass().getSimpleName(), + hashCode(), + bufferRatio, + sessionLevel, + getSessionStallTime(), + getStreamsStallTime()); } } diff --git a/jetty-http2/http2-common/src/main/java/org/eclipse/jetty/http2/HTTP2Cipher.java b/jetty-http2/http2-common/src/main/java/org/eclipse/jetty/http2/HTTP2Cipher.java index f3247f73064..5936d246279 100644 --- a/jetty-http2/http2-common/src/main/java/org/eclipse/jetty/http2/HTTP2Cipher.java +++ b/jetty-http2/http2-common/src/main/java/org/eclipse/jetty/http2/HTTP2Cipher.java @@ -27,300 +27,299 @@ public class HTTP2Cipher { public static final Comparator COMPARATOR = new CipherComparator(); - private final static Trie __blackProtocols = new ArrayTrie<>(6*5); - private final static Trie __blackCiphers = new ArrayTrie<>(275*40); + private static final Trie __blackProtocols = new ArrayTrie<>(6 * 5); + private static final Trie __blackCiphers = new ArrayTrie<>(275 * 40); static { - for (String p : new String[] + String[] protocols = {"TLSv1.2", "TLSv1.1", "TLSv1", "SSL", "SSLv2", "SSLv3"}; + for (String p : protocols) { - "TLSv1.2","TLSv1.1", "TLSv1", "SSL", "SSLv2", "SSLv3" - }) - { - __blackProtocols.put(p,Boolean.TRUE); + __blackProtocols.put(p, Boolean.TRUE); } - for (String c : new String[] + String[] ciphers = + { + "TLS_NULL_WITH_NULL_NULL", + "TLS_RSA_WITH_NULL_MD5", + "TLS_RSA_WITH_NULL_SHA", + "TLS_RSA_EXPORT_WITH_RC4_40_MD5", + "TLS_RSA_WITH_RC4_128_MD5", + "TLS_RSA_WITH_RC4_128_SHA", + "TLS_RSA_EXPORT_WITH_RC2_CBC_40_MD5", + "TLS_RSA_WITH_IDEA_CBC_SHA", + "TLS_RSA_EXPORT_WITH_DES40_CBC_SHA", + "TLS_RSA_WITH_DES_CBC_SHA", + "TLS_RSA_WITH_3DES_EDE_CBC_SHA", + "TLS_DH_DSS_EXPORT_WITH_DES40_CBC_SHA", + "TLS_DH_DSS_WITH_DES_CBC_SHA", + "TLS_DH_DSS_WITH_3DES_EDE_CBC_SHA", + "TLS_DH_RSA_EXPORT_WITH_DES40_CBC_SHA", + "TLS_DH_RSA_WITH_DES_CBC_SHA", + "TLS_DH_RSA_WITH_3DES_EDE_CBC_SHA", + "TLS_DHE_DSS_EXPORT_WITH_DES40_CBC_SHA", + "TLS_DHE_DSS_WITH_DES_CBC_SHA", + "TLS_DHE_DSS_WITH_3DES_EDE_CBC_SHA", + "TLS_DHE_RSA_EXPORT_WITH_DES40_CBC_SHA", + "TLS_DHE_RSA_WITH_DES_CBC_SHA", + "TLS_DHE_RSA_WITH_3DES_EDE_CBC_SHA", + "TLS_DH_anon_EXPORT_WITH_RC4_40_MD5", + "TLS_DH_anon_WITH_RC4_128_MD5", + "TLS_DH_anon_EXPORT_WITH_DES40_CBC_SHA", + "TLS_DH_anon_WITH_DES_CBC_SHA", + "TLS_DH_anon_WITH_3DES_EDE_CBC_SHA", + "TLS_KRB5_WITH_DES_CBC_SHA", + "TLS_KRB5_WITH_3DES_EDE_CBC_SHA", + "TLS_KRB5_WITH_RC4_128_SHA", + "TLS_KRB5_WITH_IDEA_CBC_SHA", + "TLS_KRB5_WITH_DES_CBC_MD5", + "TLS_KRB5_WITH_3DES_EDE_CBC_MD5", + "TLS_KRB5_WITH_RC4_128_MD5", + "TLS_KRB5_WITH_IDEA_CBC_MD5", + "TLS_KRB5_EXPORT_WITH_DES_CBC_40_SHA", + "TLS_KRB5_EXPORT_WITH_RC2_CBC_40_SHA", + "TLS_KRB5_EXPORT_WITH_RC4_40_SHA", + "TLS_KRB5_EXPORT_WITH_DES_CBC_40_MD5", + "TLS_KRB5_EXPORT_WITH_RC2_CBC_40_MD5", + "TLS_KRB5_EXPORT_WITH_RC4_40_MD5", + "TLS_PSK_WITH_NULL_SHA", + "TLS_DHE_PSK_WITH_NULL_SHA", + "TLS_RSA_PSK_WITH_NULL_SHA", + "TLS_RSA_WITH_AES_128_CBC_SHA", + "TLS_DH_DSS_WITH_AES_128_CBC_SHA", + "TLS_DH_RSA_WITH_AES_128_CBC_SHA", + "TLS_DHE_DSS_WITH_AES_128_CBC_SHA", + "TLS_DHE_RSA_WITH_AES_128_CBC_SHA", + "TLS_DH_anon_WITH_AES_128_CBC_SHA", + "TLS_RSA_WITH_AES_256_CBC_SHA", + "TLS_DH_DSS_WITH_AES_256_CBC_SHA", + "TLS_DH_RSA_WITH_AES_256_CBC_SHA", + "TLS_DHE_DSS_WITH_AES_256_CBC_SHA", + "TLS_DHE_RSA_WITH_AES_256_CBC_SHA", + "TLS_DH_anon_WITH_AES_256_CBC_SHA", + "TLS_RSA_WITH_NULL_SHA256", + "TLS_RSA_WITH_AES_128_CBC_SHA256", + "TLS_RSA_WITH_AES_256_CBC_SHA256", + "TLS_DH_DSS_WITH_AES_128_CBC_SHA256", + "TLS_DH_RSA_WITH_AES_128_CBC_SHA256", + "TLS_DHE_DSS_WITH_AES_128_CBC_SHA256", + "TLS_RSA_WITH_CAMELLIA_128_CBC_SHA", + "TLS_DH_DSS_WITH_CAMELLIA_128_CBC_SHA", + "TLS_DH_RSA_WITH_CAMELLIA_128_CBC_SHA", + "TLS_DHE_DSS_WITH_CAMELLIA_128_CBC_SHA", + "TLS_DHE_RSA_WITH_CAMELLIA_128_CBC_SHA", + "TLS_DH_anon_WITH_CAMELLIA_128_CBC_SHA", + "TLS_DHE_RSA_WITH_AES_128_CBC_SHA256", + "TLS_DH_DSS_WITH_AES_256_CBC_SHA256", + "TLS_DH_RSA_WITH_AES_256_CBC_SHA256", + "TLS_DHE_DSS_WITH_AES_256_CBC_SHA256", + "TLS_DHE_RSA_WITH_AES_256_CBC_SHA256", + "TLS_DH_anon_WITH_AES_128_CBC_SHA256", + "TLS_DH_anon_WITH_AES_256_CBC_SHA256", + "TLS_RSA_WITH_CAMELLIA_256_CBC_SHA", + "TLS_DH_DSS_WITH_CAMELLIA_256_CBC_SHA", + "TLS_DH_RSA_WITH_CAMELLIA_256_CBC_SHA", + "TLS_DHE_DSS_WITH_CAMELLIA_256_CBC_SHA", + "TLS_DHE_RSA_WITH_CAMELLIA_256_CBC_SHA", + "TLS_DH_anon_WITH_CAMELLIA_256_CBC_SHA", + "TLS_PSK_WITH_RC4_128_SHA", + "TLS_PSK_WITH_3DES_EDE_CBC_SHA", + "TLS_PSK_WITH_AES_128_CBC_SHA", + "TLS_PSK_WITH_AES_256_CBC_SHA", + "TLS_DHE_PSK_WITH_RC4_128_SHA", + "TLS_DHE_PSK_WITH_3DES_EDE_CBC_SHA", + "TLS_DHE_PSK_WITH_AES_128_CBC_SHA", + "TLS_DHE_PSK_WITH_AES_256_CBC_SHA", + "TLS_RSA_PSK_WITH_RC4_128_SHA", + "TLS_RSA_PSK_WITH_3DES_EDE_CBC_SHA", + "TLS_RSA_PSK_WITH_AES_128_CBC_SHA", + "TLS_RSA_PSK_WITH_AES_256_CBC_SHA", + "TLS_RSA_WITH_SEED_CBC_SHA", + "TLS_DH_DSS_WITH_SEED_CBC_SHA", + "TLS_DH_RSA_WITH_SEED_CBC_SHA", + "TLS_DHE_DSS_WITH_SEED_CBC_SHA", + "TLS_DHE_RSA_WITH_SEED_CBC_SHA", + "TLS_DH_anon_WITH_SEED_CBC_SHA", + "TLS_RSA_WITH_AES_128_GCM_SHA256", + "TLS_RSA_WITH_AES_256_GCM_SHA384", + "TLS_DH_RSA_WITH_AES_128_GCM_SHA256", + "TLS_DH_RSA_WITH_AES_256_GCM_SHA384", + "TLS_DH_DSS_WITH_AES_128_GCM_SHA256", + "TLS_DH_DSS_WITH_AES_256_GCM_SHA384", + "TLS_DH_anon_WITH_AES_128_GCM_SHA256", + "TLS_DH_anon_WITH_AES_256_GCM_SHA384", + "TLS_PSK_WITH_AES_128_GCM_SHA256", + "TLS_PSK_WITH_AES_256_GCM_SHA384", + "TLS_RSA_PSK_WITH_AES_128_GCM_SHA256", + "TLS_RSA_PSK_WITH_AES_256_GCM_SHA384", + "TLS_PSK_WITH_AES_128_CBC_SHA256", + "TLS_PSK_WITH_AES_256_CBC_SHA384", + "TLS_PSK_WITH_NULL_SHA256", + "TLS_PSK_WITH_NULL_SHA384", + "TLS_DHE_PSK_WITH_AES_128_CBC_SHA256", + "TLS_DHE_PSK_WITH_AES_256_CBC_SHA384", + "TLS_DHE_PSK_WITH_NULL_SHA256", + "TLS_DHE_PSK_WITH_NULL_SHA384", + "TLS_RSA_PSK_WITH_AES_128_CBC_SHA256", + "TLS_RSA_PSK_WITH_AES_256_CBC_SHA384", + "TLS_RSA_PSK_WITH_NULL_SHA256", + "TLS_RSA_PSK_WITH_NULL_SHA384", + "TLS_RSA_WITH_CAMELLIA_128_CBC_SHA256", + "TLS_DH_DSS_WITH_CAMELLIA_128_CBC_SHA256", + "TLS_DH_RSA_WITH_CAMELLIA_128_CBC_SHA256", + "TLS_DHE_DSS_WITH_CAMELLIA_128_CBC_SHA256", + "TLS_DHE_RSA_WITH_CAMELLIA_128_CBC_SHA256", + "TLS_DH_anon_WITH_CAMELLIA_128_CBC_SHA256", + "TLS_RSA_WITH_CAMELLIA_256_CBC_SHA256", + "TLS_DH_DSS_WITH_CAMELLIA_256_CBC_SHA256", + "TLS_DH_RSA_WITH_CAMELLIA_256_CBC_SHA256", + "TLS_DHE_DSS_WITH_CAMELLIA_256_CBC_SHA256", + "TLS_DHE_RSA_WITH_CAMELLIA_256_CBC_SHA256", + "TLS_DH_anon_WITH_CAMELLIA_256_CBC_SHA256", + "TLS_EMPTY_RENEGOTIATION_INFO_SCSV", + "TLS_ECDH_ECDSA_WITH_NULL_SHA", + "TLS_ECDH_ECDSA_WITH_RC4_128_SHA", + "TLS_ECDH_ECDSA_WITH_3DES_EDE_CBC_SHA", + "TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA", + "TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA", + "TLS_ECDHE_ECDSA_WITH_NULL_SHA", + "TLS_ECDHE_ECDSA_WITH_RC4_128_SHA", + "TLS_ECDHE_ECDSA_WITH_3DES_EDE_CBC_SHA", + "TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA", + "TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA", + "TLS_ECDH_RSA_WITH_NULL_SHA", + "TLS_ECDH_RSA_WITH_RC4_128_SHA", + "TLS_ECDH_RSA_WITH_3DES_EDE_CBC_SHA", + "TLS_ECDH_RSA_WITH_AES_128_CBC_SHA", + "TLS_ECDH_RSA_WITH_AES_256_CBC_SHA", + "TLS_ECDHE_RSA_WITH_NULL_SHA", + "TLS_ECDHE_RSA_WITH_RC4_128_SHA", + "TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA", + "TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA", + "TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA", + "TLS_ECDH_anon_WITH_NULL_SHA", + "TLS_ECDH_anon_WITH_RC4_128_SHA", + "TLS_ECDH_anon_WITH_3DES_EDE_CBC_SHA", + "TLS_ECDH_anon_WITH_AES_128_CBC_SHA", + "TLS_ECDH_anon_WITH_AES_256_CBC_SHA", + "TLS_SRP_SHA_WITH_3DES_EDE_CBC_SHA", + "TLS_SRP_SHA_RSA_WITH_3DES_EDE_CBC_SHA", + "TLS_SRP_SHA_DSS_WITH_3DES_EDE_CBC_SHA", + "TLS_SRP_SHA_WITH_AES_128_CBC_SHA", + "TLS_SRP_SHA_RSA_WITH_AES_128_CBC_SHA", + "TLS_SRP_SHA_DSS_WITH_AES_128_CBC_SHA", + "TLS_SRP_SHA_WITH_AES_256_CBC_SHA", + "TLS_SRP_SHA_RSA_WITH_AES_256_CBC_SHA", + "TLS_SRP_SHA_DSS_WITH_AES_256_CBC_SHA", + "TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256", + "TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA384", + "TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA256", + "TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA384", + "TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256", + "TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA384", + "TLS_ECDH_RSA_WITH_AES_128_CBC_SHA256", + "TLS_ECDH_RSA_WITH_AES_256_CBC_SHA384", + "TLS_ECDH_ECDSA_WITH_AES_128_GCM_SHA256", + "TLS_ECDH_ECDSA_WITH_AES_256_GCM_SHA384", + "TLS_ECDH_RSA_WITH_AES_128_GCM_SHA256", + "TLS_ECDH_RSA_WITH_AES_256_GCM_SHA384", + "TLS_ECDHE_PSK_WITH_RC4_128_SHA", + "TLS_ECDHE_PSK_WITH_3DES_EDE_CBC_SHA", + "TLS_ECDHE_PSK_WITH_AES_128_CBC_SHA", + "TLS_ECDHE_PSK_WITH_AES_256_CBC_SHA", + "TLS_ECDHE_PSK_WITH_AES_128_CBC_SHA256", + "TLS_ECDHE_PSK_WITH_AES_256_CBC_SHA384", + "TLS_ECDHE_PSK_WITH_NULL_SHA", + "TLS_ECDHE_PSK_WITH_NULL_SHA256", + "TLS_ECDHE_PSK_WITH_NULL_SHA384", + "TLS_RSA_WITH_ARIA_128_CBC_SHA256", + "TLS_RSA_WITH_ARIA_256_CBC_SHA384", + "TLS_DH_DSS_WITH_ARIA_128_CBC_SHA256", + "TLS_DH_DSS_WITH_ARIA_256_CBC_SHA384", + "TLS_DH_RSA_WITH_ARIA_128_CBC_SHA256", + "TLS_DH_RSA_WITH_ARIA_256_CBC_SHA384", + "TLS_DHE_DSS_WITH_ARIA_128_CBC_SHA256", + "TLS_DHE_DSS_WITH_ARIA_256_CBC_SHA384", + "TLS_DHE_RSA_WITH_ARIA_128_CBC_SHA256", + "TLS_DHE_RSA_WITH_ARIA_256_CBC_SHA384", + "TLS_DH_anon_WITH_ARIA_128_CBC_SHA256", + "TLS_DH_anon_WITH_ARIA_256_CBC_SHA384", + "TLS_ECDHE_ECDSA_WITH_ARIA_128_CBC_SHA256", + "TLS_ECDHE_ECDSA_WITH_ARIA_256_CBC_SHA384", + "TLS_ECDH_ECDSA_WITH_ARIA_128_CBC_SHA256", + "TLS_ECDH_ECDSA_WITH_ARIA_256_CBC_SHA384", + "TLS_ECDHE_RSA_WITH_ARIA_128_CBC_SHA256", + "TLS_ECDHE_RSA_WITH_ARIA_256_CBC_SHA384", + "TLS_ECDH_RSA_WITH_ARIA_128_CBC_SHA256", + "TLS_ECDH_RSA_WITH_ARIA_256_CBC_SHA384", + "TLS_RSA_WITH_ARIA_128_GCM_SHA256", + "TLS_RSA_WITH_ARIA_256_GCM_SHA384", + "TLS_DH_RSA_WITH_ARIA_128_GCM_SHA256", + "TLS_DH_RSA_WITH_ARIA_256_GCM_SHA384", + "TLS_DH_DSS_WITH_ARIA_128_GCM_SHA256", + "TLS_DH_DSS_WITH_ARIA_256_GCM_SHA384", + "TLS_DH_anon_WITH_ARIA_128_GCM_SHA256", + "TLS_DH_anon_WITH_ARIA_256_GCM_SHA384", + "TLS_ECDH_ECDSA_WITH_ARIA_128_GCM_SHA256", + "TLS_ECDH_ECDSA_WITH_ARIA_256_GCM_SHA384", + "TLS_ECDH_RSA_WITH_ARIA_128_GCM_SHA256", + "TLS_ECDH_RSA_WITH_ARIA_256_GCM_SHA384", + "TLS_PSK_WITH_ARIA_128_CBC_SHA256", + "TLS_PSK_WITH_ARIA_256_CBC_SHA384", + "TLS_DHE_PSK_WITH_ARIA_128_CBC_SHA256", + "TLS_DHE_PSK_WITH_ARIA_256_CBC_SHA384", + "TLS_RSA_PSK_WITH_ARIA_128_CBC_SHA256", + "TLS_RSA_PSK_WITH_ARIA_256_CBC_SHA384", + "TLS_PSK_WITH_ARIA_128_GCM_SHA256", + "TLS_PSK_WITH_ARIA_256_GCM_SHA384", + "TLS_RSA_PSK_WITH_ARIA_128_GCM_SHA256", + "TLS_RSA_PSK_WITH_ARIA_256_GCM_SHA384", + "TLS_ECDHE_PSK_WITH_ARIA_128_CBC_SHA256", + "TLS_ECDHE_PSK_WITH_ARIA_256_CBC_SHA384", + "TLS_ECDHE_ECDSA_WITH_CAMELLIA_128_CBC_SHA256", + "TLS_ECDHE_ECDSA_WITH_CAMELLIA_256_CBC_SHA384", + "TLS_ECDH_ECDSA_WITH_CAMELLIA_128_CBC_SHA256", + "TLS_ECDH_ECDSA_WITH_CAMELLIA_256_CBC_SHA384", + "TLS_ECDHE_RSA_WITH_CAMELLIA_128_CBC_SHA256", + "TLS_ECDHE_RSA_WITH_CAMELLIA_256_CBC_SHA384", + "TLS_ECDH_RSA_WITH_CAMELLIA_128_CBC_SHA256", + "TLS_ECDH_RSA_WITH_CAMELLIA_256_CBC_SHA384", + "TLS_RSA_WITH_CAMELLIA_128_GCM_SHA256", + "TLS_RSA_WITH_CAMELLIA_256_GCM_SHA384", + "TLS_DH_RSA_WITH_CAMELLIA_128_GCM_SHA256", + "TLS_DH_RSA_WITH_CAMELLIA_256_GCM_SHA384", + "TLS_DH_DSS_WITH_CAMELLIA_128_GCM_SHA256", + "TLS_DH_DSS_WITH_CAMELLIA_256_GCM_SHA384", + "TLS_DH_anon_WITH_CAMELLIA_128_GCM_SHA256", + "TLS_DH_anon_WITH_CAMELLIA_256_GCM_SHA384", + "TLS_ECDH_ECDSA_WITH_CAMELLIA_128_GCM_SHA256", + "TLS_ECDH_ECDSA_WITH_CAMELLIA_256_GCM_SHA384", + "TLS_ECDH_RSA_WITH_CAMELLIA_128_GCM_SHA256", + "TLS_ECDH_RSA_WITH_CAMELLIA_256_GCM_SHA384", + "TLS_PSK_WITH_CAMELLIA_128_GCM_SHA256", + "TLS_PSK_WITH_CAMELLIA_256_GCM_SHA384", + "TLS_RSA_PSK_WITH_CAMELLIA_128_GCM_SHA256", + "TLS_RSA_PSK_WITH_CAMELLIA_256_GCM_SHA384", + "TLS_PSK_WITH_CAMELLIA_128_CBC_SHA256", + "TLS_PSK_WITH_CAMELLIA_256_CBC_SHA384", + "TLS_DHE_PSK_WITH_CAMELLIA_128_CBC_SHA256", + "TLS_DHE_PSK_WITH_CAMELLIA_256_CBC_SHA384", + "TLS_RSA_PSK_WITH_CAMELLIA_128_CBC_SHA256", + "TLS_RSA_PSK_WITH_CAMELLIA_256_CBC_SHA384", + "TLS_ECDHE_PSK_WITH_CAMELLIA_128_CBC_SHA256", + "TLS_ECDHE_PSK_WITH_CAMELLIA_256_CBC_SHA384", + "TLS_RSA_WITH_AES_128_CCM", + "TLS_RSA_WITH_AES_256_CCM", + "TLS_RSA_WITH_AES_128_CCM_8", + "TLS_RSA_WITH_AES_256_CCM_8", + "TLS_PSK_WITH_AES_128_CCM", + "TLS_PSK_WITH_AES_256_CCM", + "TLS_PSK_WITH_AES_128_CCM_8", + "TLS_PSK_WITH_AES_256_CCM_8" + }; + for (String c : ciphers) { - "TLS_NULL_WITH_NULL_NULL", - "TLS_RSA_WITH_NULL_MD5", - "TLS_RSA_WITH_NULL_SHA", - "TLS_RSA_EXPORT_WITH_RC4_40_MD5", - "TLS_RSA_WITH_RC4_128_MD5", - "TLS_RSA_WITH_RC4_128_SHA", - "TLS_RSA_EXPORT_WITH_RC2_CBC_40_MD5", - "TLS_RSA_WITH_IDEA_CBC_SHA", - "TLS_RSA_EXPORT_WITH_DES40_CBC_SHA", - "TLS_RSA_WITH_DES_CBC_SHA", - "TLS_RSA_WITH_3DES_EDE_CBC_SHA", - "TLS_DH_DSS_EXPORT_WITH_DES40_CBC_SHA", - "TLS_DH_DSS_WITH_DES_CBC_SHA", - "TLS_DH_DSS_WITH_3DES_EDE_CBC_SHA", - "TLS_DH_RSA_EXPORT_WITH_DES40_CBC_SHA", - "TLS_DH_RSA_WITH_DES_CBC_SHA", - "TLS_DH_RSA_WITH_3DES_EDE_CBC_SHA", - "TLS_DHE_DSS_EXPORT_WITH_DES40_CBC_SHA", - "TLS_DHE_DSS_WITH_DES_CBC_SHA", - "TLS_DHE_DSS_WITH_3DES_EDE_CBC_SHA", - "TLS_DHE_RSA_EXPORT_WITH_DES40_CBC_SHA", - "TLS_DHE_RSA_WITH_DES_CBC_SHA", - "TLS_DHE_RSA_WITH_3DES_EDE_CBC_SHA", - "TLS_DH_anon_EXPORT_WITH_RC4_40_MD5", - "TLS_DH_anon_WITH_RC4_128_MD5", - "TLS_DH_anon_EXPORT_WITH_DES40_CBC_SHA", - "TLS_DH_anon_WITH_DES_CBC_SHA", - "TLS_DH_anon_WITH_3DES_EDE_CBC_SHA", - "TLS_KRB5_WITH_DES_CBC_SHA", - "TLS_KRB5_WITH_3DES_EDE_CBC_SHA", - "TLS_KRB5_WITH_RC4_128_SHA", - "TLS_KRB5_WITH_IDEA_CBC_SHA", - "TLS_KRB5_WITH_DES_CBC_MD5", - "TLS_KRB5_WITH_3DES_EDE_CBC_MD5", - "TLS_KRB5_WITH_RC4_128_MD5", - "TLS_KRB5_WITH_IDEA_CBC_MD5", - "TLS_KRB5_EXPORT_WITH_DES_CBC_40_SHA", - "TLS_KRB5_EXPORT_WITH_RC2_CBC_40_SHA", - "TLS_KRB5_EXPORT_WITH_RC4_40_SHA", - "TLS_KRB5_EXPORT_WITH_DES_CBC_40_MD5", - "TLS_KRB5_EXPORT_WITH_RC2_CBC_40_MD5", - "TLS_KRB5_EXPORT_WITH_RC4_40_MD5", - "TLS_PSK_WITH_NULL_SHA", - "TLS_DHE_PSK_WITH_NULL_SHA", - "TLS_RSA_PSK_WITH_NULL_SHA", - "TLS_RSA_WITH_AES_128_CBC_SHA", - "TLS_DH_DSS_WITH_AES_128_CBC_SHA", - "TLS_DH_RSA_WITH_AES_128_CBC_SHA", - "TLS_DHE_DSS_WITH_AES_128_CBC_SHA", - "TLS_DHE_RSA_WITH_AES_128_CBC_SHA", - "TLS_DH_anon_WITH_AES_128_CBC_SHA", - "TLS_RSA_WITH_AES_256_CBC_SHA", - "TLS_DH_DSS_WITH_AES_256_CBC_SHA", - "TLS_DH_RSA_WITH_AES_256_CBC_SHA", - "TLS_DHE_DSS_WITH_AES_256_CBC_SHA", - "TLS_DHE_RSA_WITH_AES_256_CBC_SHA", - "TLS_DH_anon_WITH_AES_256_CBC_SHA", - "TLS_RSA_WITH_NULL_SHA256", - "TLS_RSA_WITH_AES_128_CBC_SHA256", - "TLS_RSA_WITH_AES_256_CBC_SHA256", - "TLS_DH_DSS_WITH_AES_128_CBC_SHA256", - "TLS_DH_RSA_WITH_AES_128_CBC_SHA256", - "TLS_DHE_DSS_WITH_AES_128_CBC_SHA256", - "TLS_RSA_WITH_CAMELLIA_128_CBC_SHA", - "TLS_DH_DSS_WITH_CAMELLIA_128_CBC_SHA", - "TLS_DH_RSA_WITH_CAMELLIA_128_CBC_SHA", - "TLS_DHE_DSS_WITH_CAMELLIA_128_CBC_SHA", - "TLS_DHE_RSA_WITH_CAMELLIA_128_CBC_SHA", - "TLS_DH_anon_WITH_CAMELLIA_128_CBC_SHA", - "TLS_DHE_RSA_WITH_AES_128_CBC_SHA256", - "TLS_DH_DSS_WITH_AES_256_CBC_SHA256", - "TLS_DH_RSA_WITH_AES_256_CBC_SHA256", - "TLS_DHE_DSS_WITH_AES_256_CBC_SHA256", - "TLS_DHE_RSA_WITH_AES_256_CBC_SHA256", - "TLS_DH_anon_WITH_AES_128_CBC_SHA256", - "TLS_DH_anon_WITH_AES_256_CBC_SHA256", - "TLS_RSA_WITH_CAMELLIA_256_CBC_SHA", - "TLS_DH_DSS_WITH_CAMELLIA_256_CBC_SHA", - "TLS_DH_RSA_WITH_CAMELLIA_256_CBC_SHA", - "TLS_DHE_DSS_WITH_CAMELLIA_256_CBC_SHA", - "TLS_DHE_RSA_WITH_CAMELLIA_256_CBC_SHA", - "TLS_DH_anon_WITH_CAMELLIA_256_CBC_SHA", - "TLS_PSK_WITH_RC4_128_SHA", - "TLS_PSK_WITH_3DES_EDE_CBC_SHA", - "TLS_PSK_WITH_AES_128_CBC_SHA", - "TLS_PSK_WITH_AES_256_CBC_SHA", - "TLS_DHE_PSK_WITH_RC4_128_SHA", - "TLS_DHE_PSK_WITH_3DES_EDE_CBC_SHA", - "TLS_DHE_PSK_WITH_AES_128_CBC_SHA", - "TLS_DHE_PSK_WITH_AES_256_CBC_SHA", - "TLS_RSA_PSK_WITH_RC4_128_SHA", - "TLS_RSA_PSK_WITH_3DES_EDE_CBC_SHA", - "TLS_RSA_PSK_WITH_AES_128_CBC_SHA", - "TLS_RSA_PSK_WITH_AES_256_CBC_SHA", - "TLS_RSA_WITH_SEED_CBC_SHA", - "TLS_DH_DSS_WITH_SEED_CBC_SHA", - "TLS_DH_RSA_WITH_SEED_CBC_SHA", - "TLS_DHE_DSS_WITH_SEED_CBC_SHA", - "TLS_DHE_RSA_WITH_SEED_CBC_SHA", - "TLS_DH_anon_WITH_SEED_CBC_SHA", - "TLS_RSA_WITH_AES_128_GCM_SHA256", - "TLS_RSA_WITH_AES_256_GCM_SHA384", - "TLS_DH_RSA_WITH_AES_128_GCM_SHA256", - "TLS_DH_RSA_WITH_AES_256_GCM_SHA384", - "TLS_DH_DSS_WITH_AES_128_GCM_SHA256", - "TLS_DH_DSS_WITH_AES_256_GCM_SHA384", - "TLS_DH_anon_WITH_AES_128_GCM_SHA256", - "TLS_DH_anon_WITH_AES_256_GCM_SHA384", - "TLS_PSK_WITH_AES_128_GCM_SHA256", - "TLS_PSK_WITH_AES_256_GCM_SHA384", - "TLS_RSA_PSK_WITH_AES_128_GCM_SHA256", - "TLS_RSA_PSK_WITH_AES_256_GCM_SHA384", - "TLS_PSK_WITH_AES_128_CBC_SHA256", - "TLS_PSK_WITH_AES_256_CBC_SHA384", - "TLS_PSK_WITH_NULL_SHA256", - "TLS_PSK_WITH_NULL_SHA384", - "TLS_DHE_PSK_WITH_AES_128_CBC_SHA256", - "TLS_DHE_PSK_WITH_AES_256_CBC_SHA384", - "TLS_DHE_PSK_WITH_NULL_SHA256", - "TLS_DHE_PSK_WITH_NULL_SHA384", - "TLS_RSA_PSK_WITH_AES_128_CBC_SHA256", - "TLS_RSA_PSK_WITH_AES_256_CBC_SHA384", - "TLS_RSA_PSK_WITH_NULL_SHA256", - "TLS_RSA_PSK_WITH_NULL_SHA384", - "TLS_RSA_WITH_CAMELLIA_128_CBC_SHA256", - "TLS_DH_DSS_WITH_CAMELLIA_128_CBC_SHA256", - "TLS_DH_RSA_WITH_CAMELLIA_128_CBC_SHA256", - "TLS_DHE_DSS_WITH_CAMELLIA_128_CBC_SHA256", - "TLS_DHE_RSA_WITH_CAMELLIA_128_CBC_SHA256", - "TLS_DH_anon_WITH_CAMELLIA_128_CBC_SHA256", - "TLS_RSA_WITH_CAMELLIA_256_CBC_SHA256", - "TLS_DH_DSS_WITH_CAMELLIA_256_CBC_SHA256", - "TLS_DH_RSA_WITH_CAMELLIA_256_CBC_SHA256", - "TLS_DHE_DSS_WITH_CAMELLIA_256_CBC_SHA256", - "TLS_DHE_RSA_WITH_CAMELLIA_256_CBC_SHA256", - "TLS_DH_anon_WITH_CAMELLIA_256_CBC_SHA256", - "TLS_EMPTY_RENEGOTIATION_INFO_SCSV", - "TLS_ECDH_ECDSA_WITH_NULL_SHA", - "TLS_ECDH_ECDSA_WITH_RC4_128_SHA", - "TLS_ECDH_ECDSA_WITH_3DES_EDE_CBC_SHA", - "TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA", - "TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA", - "TLS_ECDHE_ECDSA_WITH_NULL_SHA", - "TLS_ECDHE_ECDSA_WITH_RC4_128_SHA", - "TLS_ECDHE_ECDSA_WITH_3DES_EDE_CBC_SHA", - "TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA", - "TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA", - "TLS_ECDH_RSA_WITH_NULL_SHA", - "TLS_ECDH_RSA_WITH_RC4_128_SHA", - "TLS_ECDH_RSA_WITH_3DES_EDE_CBC_SHA", - "TLS_ECDH_RSA_WITH_AES_128_CBC_SHA", - "TLS_ECDH_RSA_WITH_AES_256_CBC_SHA", - "TLS_ECDHE_RSA_WITH_NULL_SHA", - "TLS_ECDHE_RSA_WITH_RC4_128_SHA", - "TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA", - "TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA", - "TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA", - "TLS_ECDH_anon_WITH_NULL_SHA", - "TLS_ECDH_anon_WITH_RC4_128_SHA", - "TLS_ECDH_anon_WITH_3DES_EDE_CBC_SHA", - "TLS_ECDH_anon_WITH_AES_128_CBC_SHA", - "TLS_ECDH_anon_WITH_AES_256_CBC_SHA", - "TLS_SRP_SHA_WITH_3DES_EDE_CBC_SHA", - "TLS_SRP_SHA_RSA_WITH_3DES_EDE_CBC_SHA", - "TLS_SRP_SHA_DSS_WITH_3DES_EDE_CBC_SHA", - "TLS_SRP_SHA_WITH_AES_128_CBC_SHA", - "TLS_SRP_SHA_RSA_WITH_AES_128_CBC_SHA", - "TLS_SRP_SHA_DSS_WITH_AES_128_CBC_SHA", - "TLS_SRP_SHA_WITH_AES_256_CBC_SHA", - "TLS_SRP_SHA_RSA_WITH_AES_256_CBC_SHA", - "TLS_SRP_SHA_DSS_WITH_AES_256_CBC_SHA", - "TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256", - "TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA384", - "TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA256", - "TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA384", - "TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256", - "TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA384", - "TLS_ECDH_RSA_WITH_AES_128_CBC_SHA256", - "TLS_ECDH_RSA_WITH_AES_256_CBC_SHA384", - "TLS_ECDH_ECDSA_WITH_AES_128_GCM_SHA256", - "TLS_ECDH_ECDSA_WITH_AES_256_GCM_SHA384", - "TLS_ECDH_RSA_WITH_AES_128_GCM_SHA256", - "TLS_ECDH_RSA_WITH_AES_256_GCM_SHA384", - "TLS_ECDHE_PSK_WITH_RC4_128_SHA", - "TLS_ECDHE_PSK_WITH_3DES_EDE_CBC_SHA", - "TLS_ECDHE_PSK_WITH_AES_128_CBC_SHA", - "TLS_ECDHE_PSK_WITH_AES_256_CBC_SHA", - "TLS_ECDHE_PSK_WITH_AES_128_CBC_SHA256", - "TLS_ECDHE_PSK_WITH_AES_256_CBC_SHA384", - "TLS_ECDHE_PSK_WITH_NULL_SHA", - "TLS_ECDHE_PSK_WITH_NULL_SHA256", - "TLS_ECDHE_PSK_WITH_NULL_SHA384", - "TLS_RSA_WITH_ARIA_128_CBC_SHA256", - "TLS_RSA_WITH_ARIA_256_CBC_SHA384", - "TLS_DH_DSS_WITH_ARIA_128_CBC_SHA256", - "TLS_DH_DSS_WITH_ARIA_256_CBC_SHA384", - "TLS_DH_RSA_WITH_ARIA_128_CBC_SHA256", - "TLS_DH_RSA_WITH_ARIA_256_CBC_SHA384", - "TLS_DHE_DSS_WITH_ARIA_128_CBC_SHA256", - "TLS_DHE_DSS_WITH_ARIA_256_CBC_SHA384", - "TLS_DHE_RSA_WITH_ARIA_128_CBC_SHA256", - "TLS_DHE_RSA_WITH_ARIA_256_CBC_SHA384", - "TLS_DH_anon_WITH_ARIA_128_CBC_SHA256", - "TLS_DH_anon_WITH_ARIA_256_CBC_SHA384", - "TLS_ECDHE_ECDSA_WITH_ARIA_128_CBC_SHA256", - "TLS_ECDHE_ECDSA_WITH_ARIA_256_CBC_SHA384", - "TLS_ECDH_ECDSA_WITH_ARIA_128_CBC_SHA256", - "TLS_ECDH_ECDSA_WITH_ARIA_256_CBC_SHA384", - "TLS_ECDHE_RSA_WITH_ARIA_128_CBC_SHA256", - "TLS_ECDHE_RSA_WITH_ARIA_256_CBC_SHA384", - "TLS_ECDH_RSA_WITH_ARIA_128_CBC_SHA256", - "TLS_ECDH_RSA_WITH_ARIA_256_CBC_SHA384", - "TLS_RSA_WITH_ARIA_128_GCM_SHA256", - "TLS_RSA_WITH_ARIA_256_GCM_SHA384", - "TLS_DH_RSA_WITH_ARIA_128_GCM_SHA256", - "TLS_DH_RSA_WITH_ARIA_256_GCM_SHA384", - "TLS_DH_DSS_WITH_ARIA_128_GCM_SHA256", - "TLS_DH_DSS_WITH_ARIA_256_GCM_SHA384", - "TLS_DH_anon_WITH_ARIA_128_GCM_SHA256", - "TLS_DH_anon_WITH_ARIA_256_GCM_SHA384", - "TLS_ECDH_ECDSA_WITH_ARIA_128_GCM_SHA256", - "TLS_ECDH_ECDSA_WITH_ARIA_256_GCM_SHA384", - "TLS_ECDH_RSA_WITH_ARIA_128_GCM_SHA256", - "TLS_ECDH_RSA_WITH_ARIA_256_GCM_SHA384", - "TLS_PSK_WITH_ARIA_128_CBC_SHA256", - "TLS_PSK_WITH_ARIA_256_CBC_SHA384", - "TLS_DHE_PSK_WITH_ARIA_128_CBC_SHA256", - "TLS_DHE_PSK_WITH_ARIA_256_CBC_SHA384", - "TLS_RSA_PSK_WITH_ARIA_128_CBC_SHA256", - "TLS_RSA_PSK_WITH_ARIA_256_CBC_SHA384", - "TLS_PSK_WITH_ARIA_128_GCM_SHA256", - "TLS_PSK_WITH_ARIA_256_GCM_SHA384", - "TLS_RSA_PSK_WITH_ARIA_128_GCM_SHA256", - "TLS_RSA_PSK_WITH_ARIA_256_GCM_SHA384", - "TLS_ECDHE_PSK_WITH_ARIA_128_CBC_SHA256", - "TLS_ECDHE_PSK_WITH_ARIA_256_CBC_SHA384", - "TLS_ECDHE_ECDSA_WITH_CAMELLIA_128_CBC_SHA256", - "TLS_ECDHE_ECDSA_WITH_CAMELLIA_256_CBC_SHA384", - "TLS_ECDH_ECDSA_WITH_CAMELLIA_128_CBC_SHA256", - "TLS_ECDH_ECDSA_WITH_CAMELLIA_256_CBC_SHA384", - "TLS_ECDHE_RSA_WITH_CAMELLIA_128_CBC_SHA256", - "TLS_ECDHE_RSA_WITH_CAMELLIA_256_CBC_SHA384", - "TLS_ECDH_RSA_WITH_CAMELLIA_128_CBC_SHA256", - "TLS_ECDH_RSA_WITH_CAMELLIA_256_CBC_SHA384", - "TLS_RSA_WITH_CAMELLIA_128_GCM_SHA256", - "TLS_RSA_WITH_CAMELLIA_256_GCM_SHA384", - "TLS_DH_RSA_WITH_CAMELLIA_128_GCM_SHA256", - "TLS_DH_RSA_WITH_CAMELLIA_256_GCM_SHA384", - "TLS_DH_DSS_WITH_CAMELLIA_128_GCM_SHA256", - "TLS_DH_DSS_WITH_CAMELLIA_256_GCM_SHA384", - "TLS_DH_anon_WITH_CAMELLIA_128_GCM_SHA256", - "TLS_DH_anon_WITH_CAMELLIA_256_GCM_SHA384", - "TLS_ECDH_ECDSA_WITH_CAMELLIA_128_GCM_SHA256", - "TLS_ECDH_ECDSA_WITH_CAMELLIA_256_GCM_SHA384", - "TLS_ECDH_RSA_WITH_CAMELLIA_128_GCM_SHA256", - "TLS_ECDH_RSA_WITH_CAMELLIA_256_GCM_SHA384", - "TLS_PSK_WITH_CAMELLIA_128_GCM_SHA256", - "TLS_PSK_WITH_CAMELLIA_256_GCM_SHA384", - "TLS_RSA_PSK_WITH_CAMELLIA_128_GCM_SHA256", - "TLS_RSA_PSK_WITH_CAMELLIA_256_GCM_SHA384", - "TLS_PSK_WITH_CAMELLIA_128_CBC_SHA256", - "TLS_PSK_WITH_CAMELLIA_256_CBC_SHA384", - "TLS_DHE_PSK_WITH_CAMELLIA_128_CBC_SHA256", - "TLS_DHE_PSK_WITH_CAMELLIA_256_CBC_SHA384", - "TLS_RSA_PSK_WITH_CAMELLIA_128_CBC_SHA256", - "TLS_RSA_PSK_WITH_CAMELLIA_256_CBC_SHA384", - "TLS_ECDHE_PSK_WITH_CAMELLIA_128_CBC_SHA256", - "TLS_ECDHE_PSK_WITH_CAMELLIA_256_CBC_SHA384", - "TLS_RSA_WITH_AES_128_CCM", - "TLS_RSA_WITH_AES_256_CCM", - "TLS_RSA_WITH_AES_128_CCM_8", - "TLS_RSA_WITH_AES_256_CCM_8", - "TLS_PSK_WITH_AES_128_CCM", - "TLS_PSK_WITH_AES_256_CCM", - "TLS_PSK_WITH_AES_128_CCM_8", - "TLS_PSK_WITH_AES_256_CCM_8" - }) - { - __blackCiphers.put(c,Boolean.TRUE); + __blackCiphers.put(c, Boolean.TRUE); } } @@ -344,9 +343,9 @@ public class HTTP2Cipher @Override public int compare(String c1, String c2) { - boolean b1=isBlackListCipher(c1); - boolean b2=isBlackListCipher(c2); - if (b1==b2) + boolean b1 = isBlackListCipher(c1); + boolean b2 = isBlackListCipher(c2); + if (b1 == b2) return 0; if (b1) return 1; diff --git a/jetty-http2/http2-common/src/main/java/org/eclipse/jetty/http2/HTTP2Connection.java b/jetty-http2/http2-common/src/main/java/org/eclipse/jetty/http2/HTTP2Connection.java index cd26737ebfb..5a6ba2bed13 100644 --- a/jetty-http2/http2-common/src/main/java/org/eclipse/jetty/http2/HTTP2Connection.java +++ b/jetty-http2/http2-common/src/main/java/org/eclipse/jetty/http2/HTTP2Connection.java @@ -44,10 +44,10 @@ import org.eclipse.jetty.util.thread.strategy.EatWhatYouKill; public class HTTP2Connection extends AbstractConnection implements WriteFlusher.Listener { protected static final Logger LOG = Log.getLogger(HTTP2Connection.class); - + // TODO remove this once we are sure EWYK is OK for http2 private static final boolean PEC_MODE = Boolean.getBoolean("org.eclipse.jetty.http2.PEC_MODE"); - + private final Queue tasks = new ArrayDeque<>(); private final HTTP2Producer producer = new HTTP2Producer(); private final AtomicLong bytesIn = new AtomicLong(); @@ -389,7 +389,7 @@ public class HTTP2Connection extends AbstractConnection implements WriteFlusher. { private NetworkBuffer() { - super(byteBufferPool,bufferSize,false); + super(byteBufferPool, bufferSize, false); } private void put(ByteBuffer source) diff --git a/jetty-http2/http2-common/src/main/java/org/eclipse/jetty/http2/HTTP2Flusher.java b/jetty-http2/http2-common/src/main/java/org/eclipse/jetty/http2/HTTP2Flusher.java index d12e8a8c7e2..350751ead3c 100644 --- a/jetty-http2/http2-common/src/main/java/org/eclipse/jetty/http2/HTTP2Flusher.java +++ b/jetty-http2/http2-common/src/main/java/org/eclipse/jetty/http2/HTTP2Flusher.java @@ -139,11 +139,15 @@ public class HTTP2Flusher extends IteratingCallback implements Dumpable WindowEntry windowEntry; while ((windowEntry = windows.poll()) != null) + { windowEntry.perform(); + } Entry entry; while ((entry = entries.poll()) != null) + { pendingEntries.offer(entry); + } } if (pendingEntries.isEmpty()) @@ -237,12 +241,12 @@ public class HTTP2Flusher extends IteratingCallback implements Dumpable if (LOG.isDebugEnabled()) LOG.debug("Writing {} buffers ({} bytes) - entries processed/pending {}/{}: {}/{}", - byteBuffers.size(), - lease.getTotalLength(), - processedEntries.size(), - pendingEntries.size(), - processedEntries, - pendingEntries); + byteBuffers.size(), + lease.getTotalLength(), + processedEntries.size(), + pendingEntries.size(), + processedEntries, + pendingEntries); session.getEndPoint().write(this, byteBuffers.toArray(EMPTY_BYTE_BUFFERS)); return Action.SCHEDULED; @@ -252,7 +256,9 @@ public class HTTP2Flusher extends IteratingCallback implements Dumpable { // A single EndPoint write may be flushed multiple times (for example with SSL). for (Entry entry : processedEntries) + { bytes = entry.onFlushed(bytes); + } } @Override @@ -260,11 +266,11 @@ public class HTTP2Flusher extends IteratingCallback implements Dumpable { if (LOG.isDebugEnabled()) LOG.debug("Written {} buffers - entries processed/pending {}/{}: {}/{}", - lease.getByteBuffers().size(), - processedEntries.size(), - pendingEntries.size(), - processedEntries, - pendingEntries); + lease.getByteBuffers().size(), + processedEntries.size(), + pendingEntries.size(), + processedEntries, + pendingEntries); finish(); super.succeeded(); } @@ -310,10 +316,10 @@ public class HTTP2Flusher extends IteratingCallback implements Dumpable terminated = x; if (LOG.isDebugEnabled()) LOG.debug(String.format("%s, entries processed/pending/queued=%d/%d/%d", - closed != null ? "Closing" : "Failing", - processedEntries.size(), - pendingEntries.size(), - entries.size()), x); + closed != null ? "Closing" : "Failing", + processedEntries.size(), + pendingEntries.size(), + entries.size()), x); allEntries = new HashSet<>(entries); entries.clear(); } @@ -365,14 +371,14 @@ public class HTTP2Flusher extends IteratingCallback implements Dumpable public String toString() { return String.format("%s[window_queue=%d,frame_queue=%d,processed/pending=%d/%d]", - super.toString(), - getWindowQueueSize(), - getFrameQueueSize(), - processedEntries.size(), - pendingEntries.size()); + super.toString(), + getWindowQueueSize(), + getFrameQueueSize(), + processedEntries.size(), + pendingEntries.size()); } - public static abstract class Entry extends Callback.Nested + public abstract static class Entry extends Callback.Nested { protected final Frame frame; protected final IStream stream; diff --git a/jetty-http2/http2-common/src/main/java/org/eclipse/jetty/http2/HTTP2Session.java b/jetty-http2/http2-common/src/main/java/org/eclipse/jetty/http2/HTTP2Session.java index eb20e4910d7..770f1d07f28 100644 --- a/jetty-http2/http2-common/src/main/java/org/eclipse/jetty/http2/HTTP2Session.java +++ b/jetty-http2/http2-common/src/main/java/org/eclipse/jetty/http2/HTTP2Session.java @@ -555,7 +555,7 @@ public abstract class HTTP2Session extends ContainerLifeCycle implements ISessio streamId = localStreamIds.getAndAdd(2); PriorityFrame priority = frame.getPriority(); priority = priority == null ? null : new PriorityFrame(streamId, priority.getParentStreamId(), - priority.getWeight(), priority.isExclusive()); + priority.getWeight(), priority.isExclusive()); frame = new HeadersFrame(streamId, frame.getMetaData(), priority, frame.isEndStream()); } IStream stream = createLocalStream(streamId); @@ -583,7 +583,7 @@ public abstract class HTTP2Session extends ContainerLifeCycle implements ISessio { streamId = localStreamIds.getAndAdd(2); frame = new PriorityFrame(streamId, frame.getParentStreamId(), - frame.getWeight(), frame.isExclusive()); + frame.getWeight(), frame.isExclusive()); } control(stream, callback, frame); return streamId; @@ -654,8 +654,8 @@ public abstract class HTTP2Session extends ContainerLifeCycle implements ISessio * performing their actions. * * - * @param error the error code - * @param reason the reason + * @param error the error code + * @param reason the reason * @param callback the callback to invoke when the operation is complete * @see #onGoAway(GoAwayFrame) * @see #onShutdown() @@ -731,7 +731,9 @@ public abstract class HTTP2Session extends ContainerLifeCycle implements ISessio callback = new CountingCallback(callback, 1 + length); frame(new ControlEntry(frame, stream, callback), false); for (int i = 1; i <= length; ++i) + { frame(new ControlEntry(frames[i - 1], stream, callback), i == length); + } } } @@ -1062,7 +1064,9 @@ public abstract class HTTP2Session extends ContainerLifeCycle implements ISessio { flusher.terminate(cause); for (IStream stream : streams.values()) + { stream.close(); + } streams.clear(); disconnect(); return; @@ -1214,15 +1218,15 @@ public abstract class HTTP2Session extends ContainerLifeCycle implements ISessio public String toString() { return String.format("%s@%x{l:%s <-> r:%s,sendWindow=%s,recvWindow=%s,streams=%d,%s,%s}", - getClass().getSimpleName(), - hashCode(), - getEndPoint().getLocalAddress(), - getEndPoint().getRemoteAddress(), - sendWindow, - recvWindow, - streams.size(), - closed, - closeFrame); + getClass().getSimpleName(), + hashCode(), + getEndPoint().getLocalAddress(), + getEndPoint().getRemoteAddress(), + sendWindow, + recvWindow, + streams.size(), + closed, + closeFrame); } private class ControlEntry extends HTTP2Flusher.Entry diff --git a/jetty-http2/http2-common/src/main/java/org/eclipse/jetty/http2/HTTP2Stream.java b/jetty-http2/http2-common/src/main/java/org/eclipse/jetty/http2/HTTP2Stream.java index df6932f4df0..4da6aaa8d1f 100644 --- a/jetty-http2/http2-common/src/main/java/org/eclipse/jetty/http2/HTTP2Stream.java +++ b/jetty-http2/http2-common/src/main/java/org/eclipse/jetty/http2/HTTP2Stream.java @@ -653,15 +653,15 @@ public class HTTP2Stream extends IdleTimeout implements IStream, Callback, Dumpa public String toString() { return String.format("%s@%x#%d{sendWindow=%s,recvWindow=%s,reset=%b/%b,%s,age=%d,attachment=%s}", - getClass().getSimpleName(), - hashCode(), - getId(), - sendWindow, - recvWindow, - localReset, - remoteReset, - closeState, - TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - timeStamp), - attachment); + getClass().getSimpleName(), + hashCode(), + getId(), + sendWindow, + recvWindow, + localReset, + remoteReset, + closeState, + TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - timeStamp), + attachment); } } diff --git a/jetty-http2/http2-common/src/main/java/org/eclipse/jetty/http2/ISession.java b/jetty-http2/http2-common/src/main/java/org/eclipse/jetty/http2/ISession.java index 3d788b38db0..4e4d483009f 100644 --- a/jetty-http2/http2-common/src/main/java/org/eclipse/jetty/http2/ISession.java +++ b/jetty-http2/http2-common/src/main/java/org/eclipse/jetty/http2/ISession.java @@ -49,10 +49,10 @@ public interface ISession extends Session /** *

      Enqueues the given frames to be written to the connection.

      * - * @param stream the stream the frames belong to + * @param stream the stream the frames belong to * @param callback the callback that gets notified when the frames have been sent - * @param frame the first frame to enqueue - * @param frames additional frames to enqueue + * @param frame the first frame to enqueue + * @param frames additional frames to enqueue */ public void frames(IStream stream, Callback callback, Frame frame, Frame... frames); @@ -61,9 +61,9 @@ public interface ISession extends Session *

      Differently from {@link #frames(IStream, Callback, Frame, Frame...)}, this method * generates atomically the stream id for the pushed stream.

      * - * @param stream the stream associated to the pushed stream - * @param promise the promise that gets notified of the pushed stream creation - * @param frame the PUSH_PROMISE frame to enqueue + * @param stream the stream associated to the pushed stream + * @param promise the promise that gets notified of the pushed stream creation + * @param frame the PUSH_PROMISE frame to enqueue * @param listener the listener that gets notified of pushed stream events */ public void push(IStream stream, Promise promise, PushPromiseFrame frame, Stream.Listener listener); @@ -71,9 +71,9 @@ public interface ISession extends Session /** *

      Enqueues the given DATA frame to be written to the connection.

      * - * @param stream the stream the data frame belongs to + * @param stream the stream the data frame belongs to * @param callback the callback that gets notified when the frame has been sent - * @param frame the DATA frame to send + * @param frame the DATA frame to send */ public void data(IStream stream, Callback callback, DataFrame frame); @@ -97,7 +97,7 @@ public interface ISession extends Session *

      Callback method invoked when a WINDOW_UPDATE frame has been received.

      * * @param stream the stream the window update belongs to, or null if the window update belongs to the session - * @param frame the WINDOW_UPDATE frame received + * @param frame the WINDOW_UPDATE frame received */ public void onWindowUpdate(IStream stream, WindowUpdateFrame frame); @@ -117,9 +117,9 @@ public interface ISession extends Session /** *

      Callback invoked when the idle timeout expires.

      * + * @return {@code true} if the session has expired * @see #onShutdown() * @see #close(int, String, Callback) - * @return {@code true} if the session has expired */ public boolean onIdleTimeout(); diff --git a/jetty-http2/http2-common/src/main/java/org/eclipse/jetty/http2/IStream.java b/jetty-http2/http2-common/src/main/java/org/eclipse/jetty/http2/IStream.java index e671d27b86f..cca02086afb 100644 --- a/jetty-http2/http2-common/src/main/java/org/eclipse/jetty/http2/IStream.java +++ b/jetty-http2/http2-common/src/main/java/org/eclipse/jetty/http2/IStream.java @@ -76,7 +76,7 @@ public interface IStream extends Stream, Closeable *

      Updates the close state of this stream.

      * * @param update whether to update the close state - * @param event the event that caused the close state update + * @param event the event that caused the close state update * @return whether the stream has been fully closed by this invocation */ public boolean updateClose(boolean update, CloseState.Event event); diff --git a/jetty-http2/http2-common/src/main/java/org/eclipse/jetty/http2/api/Session.java b/jetty-http2/http2-common/src/main/java/org/eclipse/jetty/http2/api/Session.java index 7eee172b9c1..39888cd8613 100644 --- a/jetty-http2/http2-common/src/main/java/org/eclipse/jetty/http2/api/Session.java +++ b/jetty-http2/http2-common/src/main/java/org/eclipse/jetty/http2/api/Session.java @@ -57,8 +57,8 @@ public interface Session /** *

      Sends the given HEADERS {@code frame} to create a new {@link Stream}.

      * - * @param frame the HEADERS frame containing the HTTP headers - * @param promise the promise that gets notified of the stream creation + * @param frame the HEADERS frame containing the HTTP headers + * @param promise the promise that gets notified of the stream creation * @param listener the listener that gets notified of stream events */ public void newStream(HeadersFrame frame, Promise promise, Stream.Listener listener); @@ -69,17 +69,17 @@ public interface Session * (for example {@code 0}), then a new {@code streamId} will be allocated, to * support unused anchor streams that act as parent for other streams.

      * - * @param frame the PRIORITY frame to send + * @param frame the PRIORITY frame to send * @param callback the callback that gets notified when the frame has been sent - * @return the new stream id generated by the PRIORITY frame, or the stream id - * that it is already referencing + * @return the new stream id generated by the PRIORITY frame, or the stream id + * that it is already referencing */ public int priority(PriorityFrame frame, Callback callback); /** *

      Sends the given SETTINGS {@code frame} to configure the session.

      * - * @param frame the SETTINGS frame to send + * @param frame the SETTINGS frame to send * @param callback the callback that gets notified when the frame has been sent */ public void settings(SettingsFrame frame, Callback callback); @@ -89,7 +89,7 @@ public interface Session *

      PING frames may be used to test the connection integrity and to measure * round-trip time.

      * - * @param frame the PING frame to send + * @param frame the PING frame to send * @param callback the callback that gets notified when the frame has been sent */ public void ping(PingFrame frame, Callback callback); @@ -100,8 +100,8 @@ public interface Session *

      The GOAWAY frame is sent only once; subsequent or concurrent attempts to * close the session will have no effect.

      * - * @param error the error code - * @param payload an optional payload (may be null) + * @param error the error code + * @param payload an optional payload (may be null) * @param callback the callback that gets notified when the frame has been sent * @return true if the frame is being sent, false if the session was already closed */ @@ -136,11 +136,11 @@ public interface Session /** *

      Callback method invoked:

      *
        - *
      • for clients, just before the preface is sent, to gather the - * SETTINGS configuration options the client wants to send to the server;
      • - *
      • for servers, just after having received the preface, to gather - * the SETTINGS configuration options the server wants to send to the - * client.
      • + *
      • for clients, just before the preface is sent, to gather the + * SETTINGS configuration options the client wants to send to the server;
      • + *
      • for servers, just after having received the preface, to gather + * the SETTINGS configuration options the server wants to send to the + * client.
      • *
      * * @param session the session @@ -162,7 +162,7 @@ public interface Session * {@link Stream.Listener#onData(Stream, DataFrame, Callback)}.

      * * @param stream the newly created stream - * @param frame the HEADERS frame received + * @param frame the HEADERS frame received * @return a {@link Stream.Listener} that will be notified of stream events */ public Stream.Listener onNewStream(Stream stream, HeadersFrame frame); @@ -171,7 +171,7 @@ public interface Session *

      Callback method invoked when a SETTINGS frame has been received.

      * * @param session the session - * @param frame the SETTINGS frame received + * @param frame the SETTINGS frame received */ public void onSettings(Session session, SettingsFrame frame); @@ -179,7 +179,7 @@ public interface Session *

      Callback method invoked when a PING frame has been received.

      * * @param session the session - * @param frame the PING frame received + * @param frame the PING frame received */ public void onPing(Session session, PingFrame frame); @@ -187,7 +187,7 @@ public interface Session *

      Callback method invoked when a RST_STREAM frame has been received for an unknown stream.

      * * @param session the session - * @param frame the RST_STREAM frame received + * @param frame the RST_STREAM frame received * @see Stream.Listener#onReset(Stream, ResetFrame) */ public void onReset(Session session, ResetFrame frame); @@ -195,8 +195,8 @@ public interface Session /** *

      Callback method invoked when a GOAWAY frame has been received.

      * - * @param session the session - * @param frame the GOAWAY frame received + * @param session the session + * @param frame the GOAWAY frame received * @param callback the callback to notify of the GOAWAY processing */ public default void onClose(Session session, GoAwayFrame frame, Callback callback) @@ -216,6 +216,7 @@ public interface Session /** *

      Callback method invoked when the idle timeout expired.

      + * * @param session the session * @return whether the session should be closed */ @@ -224,8 +225,8 @@ public interface Session /** *

      Callback method invoked when a failure has been detected for this session.

      * - * @param session the session - * @param failure the failure + * @param session the session + * @param failure the failure * @param callback the callback to notify of failure processing */ public default void onFailure(Session session, Throwable failure, Callback callback) diff --git a/jetty-http2/http2-common/src/main/java/org/eclipse/jetty/http2/api/Stream.java b/jetty-http2/http2-common/src/main/java/org/eclipse/jetty/http2/api/Stream.java index 6061e69c582..6f02b828825 100644 --- a/jetty-http2/http2-common/src/main/java/org/eclipse/jetty/http2/api/Stream.java +++ b/jetty-http2/http2-common/src/main/java/org/eclipse/jetty/http2/api/Stream.java @@ -53,7 +53,7 @@ public interface Stream /** *

      Sends the given HEADERS {@code frame} representing a HTTP response.

      * - * @param frame the HEADERS frame to send + * @param frame the HEADERS frame to send * @param callback the callback that gets notified when the frame has been sent */ public void headers(HeadersFrame frame, Callback callback); @@ -61,7 +61,7 @@ public interface Stream /** *

      Sends the given PUSH_PROMISE {@code frame}.

      * - * @param frame the PUSH_PROMISE frame to send + * @param frame the PUSH_PROMISE frame to send * @param promise the promise that gets notified of the pushed stream creation * @param listener the listener that gets notified of stream events */ @@ -70,7 +70,7 @@ public interface Stream /** *

      Sends the given DATA {@code frame}.

      * - * @param frame the DATA frame to send + * @param frame the DATA frame to send * @param callback the callback that gets notified when the frame has been sent */ public void data(DataFrame frame, Callback callback); @@ -78,7 +78,7 @@ public interface Stream /** *

      Sends the given RST_STREAM {@code frame}.

      * - * @param frame the RST_FRAME to send + * @param frame the RST_FRAME to send * @param callback the callback that gets notified when the frame has been sent */ public void reset(ResetFrame frame, Callback callback); @@ -92,7 +92,7 @@ public interface Stream public Object getAttribute(String key); /** - * @param key the attribute key + * @param key the attribute key * @param value an arbitrary object to associate with the given key to this stream * @see #getAttribute(String) * @see #removeAttribute(String) @@ -141,7 +141,7 @@ public interface Stream *

      Callback method invoked when a HEADERS frame representing the HTTP response has been received.

      * * @param stream the stream - * @param frame the HEADERS frame received + * @param frame the HEADERS frame received */ public void onHeaders(Stream stream, HeadersFrame frame); @@ -149,7 +149,7 @@ public interface Stream *

      Callback method invoked when a PUSH_PROMISE frame has been received.

      * * @param stream the stream - * @param frame the PUSH_PROMISE frame received + * @param frame the PUSH_PROMISE frame received * @return a Stream.Listener that will be notified of pushed stream events */ public Listener onPush(Stream stream, PushPromiseFrame frame); @@ -157,8 +157,8 @@ public interface Stream /** *

      Callback method invoked when a DATA frame has been received.

      * - * @param stream the stream - * @param frame the DATA frame received + * @param stream the stream + * @param frame the DATA frame received * @param callback the callback to complete when the bytes of the DATA frame have been consumed */ public void onData(Stream stream, DataFrame frame, Callback callback); @@ -167,7 +167,7 @@ public interface Stream *

      Callback method invoked when a RST_STREAM frame has been received for this stream.

      * * @param stream the stream - * @param frame the RST_FRAME received + * @param frame the RST_FRAME received * @param callback the callback to complete when the reset has been handled */ public default void onReset(Stream stream, ResetFrame frame, Callback callback) @@ -187,7 +187,7 @@ public interface Stream *

      Callback method invoked when a RST_STREAM frame has been received for this stream.

      * * @param stream the stream - * @param frame the RST_FRAME received + * @param frame the RST_FRAME received * @see Session.Listener#onReset(Session, ResetFrame) */ public default void onReset(Stream stream, ResetFrame frame) @@ -198,9 +198,9 @@ public interface Stream *

      Callback method invoked when the stream exceeds its idle timeout.

      * * @param stream the stream - * @param x the timeout failure - * @see #getIdleTimeout() + * @param x the timeout failure * @return true to reset the stream, false to ignore the idle timeout + * @see #getIdleTimeout() */ public boolean onIdleTimeout(Stream stream, Throwable x); @@ -208,7 +208,7 @@ public interface Stream *

      Callback method invoked when the stream failed.

      * * @param stream the stream - * @param error the error code + * @param error the error code * @param reason the error reason, or null * @param callback the callback to complete when the failure has been handled */ diff --git a/jetty-http2/http2-common/src/main/java/org/eclipse/jetty/http2/api/server/ServerSessionListener.java b/jetty-http2/http2-common/src/main/java/org/eclipse/jetty/http2/api/server/ServerSessionListener.java index e5c9c3cd180..d11e3251d0a 100644 --- a/jetty-http2/http2-common/src/main/java/org/eclipse/jetty/http2/api/server/ServerSessionListener.java +++ b/jetty-http2/http2-common/src/main/java/org/eclipse/jetty/http2/api/server/ServerSessionListener.java @@ -27,6 +27,7 @@ public interface ServerSessionListener extends Session.Listener { /** *

      Callback method invoked when a connection has been accepted by the server.

      + * * @param session the session */ public void onAccept(Session session); diff --git a/jetty-http2/http2-common/src/main/java/org/eclipse/jetty/http2/frames/GoAwayFrame.java b/jetty-http2/http2-common/src/main/java/org/eclipse/jetty/http2/frames/GoAwayFrame.java index 28154dcec2b..64b855f2d2e 100644 --- a/jetty-http2/http2-common/src/main/java/org/eclipse/jetty/http2/frames/GoAwayFrame.java +++ b/jetty-http2/http2-common/src/main/java/org/eclipse/jetty/http2/frames/GoAwayFrame.java @@ -77,10 +77,10 @@ public class GoAwayFrame extends Frame public String toString() { return String.format("%s,%d/%s/%s/%s", - super.toString(), - lastStreamId, - ErrorCode.toString(error, null), - tryConvertPayload(), - closeState); + super.toString(), + lastStreamId, + ErrorCode.toString(error, null), + tryConvertPayload(), + closeState); } } diff --git a/jetty-http2/http2-common/src/main/java/org/eclipse/jetty/http2/frames/HeadersFrame.java b/jetty-http2/http2-common/src/main/java/org/eclipse/jetty/http2/frames/HeadersFrame.java index ff676a1930d..d3868f7c782 100644 --- a/jetty-http2/http2-common/src/main/java/org/eclipse/jetty/http2/frames/HeadersFrame.java +++ b/jetty-http2/http2-common/src/main/java/org/eclipse/jetty/http2/frames/HeadersFrame.java @@ -32,8 +32,8 @@ public class HeadersFrame extends Frame *

      The stream {@code id} will be generated by the implementation while sending * this frame to the other peer.

      * - * @param metaData the metadata containing HTTP request information - * @param priority the PRIORITY frame associated with this HEADERS frame + * @param metaData the metadata containing HTTP request information + * @param priority the PRIORITY frame associated with this HEADERS frame * @param endStream whether this frame ends the stream */ public HeadersFrame(MetaData metaData, PriorityFrame priority, boolean endStream) @@ -46,9 +46,9 @@ public class HeadersFrame extends Frame *

      {@code HEADERS} frames with a specific stream {@code id} are typically used * in responses to request {@code HEADERS} frames.

      * - * @param streamId the stream id - * @param metaData the metadata containing HTTP request/response information - * @param priority the PRIORITY frame associated with this HEADERS frame + * @param streamId the stream id + * @param metaData the metadata containing HTTP request/response information + * @param priority the PRIORITY frame associated with this HEADERS frame * @param endStream whether this frame ends the stream */ public HeadersFrame(int streamId, MetaData metaData, PriorityFrame priority, boolean endStream) @@ -84,6 +84,6 @@ public class HeadersFrame extends Frame public String toString() { return String.format("%s#%d{end=%b}%s", super.toString(), streamId, endStream, - priority == null ? "" : String.format("+%s", priority)); + priority == null ? "" : String.format("+%s", priority)); } } diff --git a/jetty-http2/http2-common/src/main/java/org/eclipse/jetty/http2/frames/PrefaceFrame.java b/jetty-http2/http2-common/src/main/java/org/eclipse/jetty/http2/frames/PrefaceFrame.java index 07018972de7..e1aff2b723c 100644 --- a/jetty-http2/http2-common/src/main/java/org/eclipse/jetty/http2/frames/PrefaceFrame.java +++ b/jetty-http2/http2-common/src/main/java/org/eclipse/jetty/http2/frames/PrefaceFrame.java @@ -27,7 +27,7 @@ public class PrefaceFrame extends Frame * request, used in the direct upgrade. */ public static final byte[] PREFACE_PREAMBLE_BYTES = ( - "PRI * HTTP/2.0\r\n" + + "PRI * HTTP/2.0\r\n" + "\r\n" ).getBytes(StandardCharsets.US_ASCII); @@ -35,7 +35,7 @@ public class PrefaceFrame extends Frame * The HTTP/2 preface bytes. */ public static final byte[] PREFACE_BYTES = ( - "PRI * HTTP/2.0\r\n" + + "PRI * HTTP/2.0\r\n" + "\r\n" + "SM\r\n" + "\r\n" diff --git a/jetty-http2/http2-common/src/main/java/org/eclipse/jetty/http2/frames/SettingsFrame.java b/jetty-http2/http2-common/src/main/java/org/eclipse/jetty/http2/frames/SettingsFrame.java index 14b2caf5407..c4f78e1371a 100644 --- a/jetty-http2/http2-common/src/main/java/org/eclipse/jetty/http2/frames/SettingsFrame.java +++ b/jetty-http2/http2-common/src/main/java/org/eclipse/jetty/http2/frames/SettingsFrame.java @@ -30,7 +30,7 @@ public class SettingsFrame extends Frame public static final int INITIAL_WINDOW_SIZE = 4; public static final int MAX_FRAME_SIZE = 5; public static final int MAX_HEADER_LIST_SIZE = 6; - + private final Map settings; private final boolean reply; diff --git a/jetty-http2/http2-common/src/main/java/org/eclipse/jetty/http2/generator/HeadersGenerator.java b/jetty-http2/http2-common/src/main/java/org/eclipse/jetty/http2/generator/HeadersGenerator.java index 4d50b09cacb..4ff03bd28e5 100644 --- a/jetty-http2/http2-common/src/main/java/org/eclipse/jetty/http2/generator/HeadersGenerator.java +++ b/jetty-http2/http2-common/src/main/java/org/eclipse/jetty/http2/generator/HeadersGenerator.java @@ -140,7 +140,7 @@ public class HeadersGenerator extends FrameGenerator if (priority != null) { priorityGenerator.generatePriorityBody(header, priority.getStreamId(), - priority.getParentStreamId(), priority.getWeight(), priority.isExclusive()); + priority.getParentStreamId(), priority.getWeight(), priority.isExclusive()); } } } diff --git a/jetty-http2/http2-common/src/main/java/org/eclipse/jetty/http2/parser/HeaderBlockParser.java b/jetty-http2/http2-common/src/main/java/org/eclipse/jetty/http2/parser/HeaderBlockParser.java index cfea5260eef..54e4661da67 100644 --- a/jetty-http2/http2-common/src/main/java/org/eclipse/jetty/http2/parser/HeaderBlockParser.java +++ b/jetty-http2/http2-common/src/main/java/org/eclipse/jetty/http2/parser/HeaderBlockParser.java @@ -53,7 +53,7 @@ public class HeaderBlockParser /** * Parses @{code blockLength} HPACK bytes from the given {@code buffer}. * - * @param buffer the buffer to parse + * @param buffer the buffer to parse * @param blockLength the length of the HPACK block * @return null, if the buffer contains less than {@code blockLength} bytes; * {@link #STREAM_FAILURE} if parsing the HPACK block produced a stream failure; diff --git a/jetty-http2/http2-common/src/main/java/org/eclipse/jetty/http2/parser/SettingsBodyParser.java b/jetty-http2/http2-common/src/main/java/org/eclipse/jetty/http2/parser/SettingsBodyParser.java index fbaa7b4cc1c..741dd95981d 100644 --- a/jetty-http2/http2-common/src/main/java/org/eclipse/jetty/http2/parser/SettingsBodyParser.java +++ b/jetty-http2/http2-common/src/main/java/org/eclipse/jetty/http2/parser/SettingsBodyParser.java @@ -130,7 +130,7 @@ public class SettingsBodyParser extends BodyParser { settingValue = buffer.getInt(); if (LOG.isDebugEnabled()) - LOG.debug(String.format("setting %d=%d",settingId, settingValue)); + LOG.debug(String.format("setting %d=%d", settingId, settingValue)); if (!onSetting(buffer, settings, settingId, settingValue)) return false; state = State.SETTING_ID; @@ -157,7 +157,7 @@ public class SettingsBodyParser extends BodyParser if (cursor == 0) { if (LOG.isDebugEnabled()) - LOG.debug(String.format("setting %d=%d",settingId, settingValue)); + LOG.debug(String.format("setting %d=%d", settingId, settingValue)); if (!onSetting(buffer, settings, settingId, settingValue)) return false; state = State.SETTING_ID; diff --git a/jetty-http2/http2-common/src/test/java/org/eclipse/jetty/http2/frames/ContinuationParseTest.java b/jetty-http2/http2-common/src/test/java/org/eclipse/jetty/http2/frames/ContinuationParseTest.java index 0f0bfbe9b2d..4db00c3db4b 100644 --- a/jetty-http2/http2-common/src/test/java/org/eclipse/jetty/http2/frames/ContinuationParseTest.java +++ b/jetty-http2/http2-common/src/test/java/org/eclipse/jetty/http2/frames/ContinuationParseTest.java @@ -18,10 +18,6 @@ package org.eclipse.jetty.http2.frames; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertNull; -import static org.junit.jupiter.api.Assertions.assertTrue; - import java.nio.ByteBuffer; import java.util.ArrayList; import java.util.List; @@ -40,9 +36,12 @@ import org.eclipse.jetty.http2.hpack.HpackEncoder; import org.eclipse.jetty.http2.parser.Parser; import org.eclipse.jetty.io.ByteBufferPool; import org.eclipse.jetty.io.MappedByteBufferPool; - import org.junit.jupiter.api.Test; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertTrue; + public class ContinuationParseTest { @Test diff --git a/jetty-http2/http2-common/src/test/java/org/eclipse/jetty/http2/frames/DataGenerateParseTest.java b/jetty-http2/http2-common/src/test/java/org/eclipse/jetty/http2/frames/DataGenerateParseTest.java index e1e2a51dd73..3b018233a83 100644 --- a/jetty-http2/http2-common/src/test/java/org/eclipse/jetty/http2/frames/DataGenerateParseTest.java +++ b/jetty-http2/http2-common/src/test/java/org/eclipse/jetty/http2/frames/DataGenerateParseTest.java @@ -18,9 +18,6 @@ package org.eclipse.jetty.http2.frames; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertTrue; - import java.nio.ByteBuffer; import java.util.ArrayList; import java.util.List; @@ -33,9 +30,11 @@ import org.eclipse.jetty.http2.parser.Parser; import org.eclipse.jetty.io.ByteBufferPool; import org.eclipse.jetty.io.MappedByteBufferPool; import org.eclipse.jetty.util.BufferUtil; - import org.junit.jupiter.api.Test; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + public class DataGenerateParseTest { private final byte[] smallContent = new byte[128]; @@ -72,7 +71,7 @@ public class DataGenerateParseTest } @Test - public void testGenerateParseLargeContent() + public void testGenerateParseLargeContent() { ByteBuffer content = ByteBuffer.wrap(largeContent); List frames = testGenerateParse(content); diff --git a/jetty-http2/http2-common/src/test/java/org/eclipse/jetty/http2/frames/GoAwayGenerateParseTest.java b/jetty-http2/http2-common/src/test/java/org/eclipse/jetty/http2/frames/GoAwayGenerateParseTest.java index 8935cac7500..0cc7e37c870 100644 --- a/jetty-http2/http2-common/src/test/java/org/eclipse/jetty/http2/frames/GoAwayGenerateParseTest.java +++ b/jetty-http2/http2-common/src/test/java/org/eclipse/jetty/http2/frames/GoAwayGenerateParseTest.java @@ -18,10 +18,6 @@ package org.eclipse.jetty.http2.frames; -import static org.junit.jupiter.api.Assertions.assertArrayEquals; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertNull; - import java.nio.ByteBuffer; import java.util.ArrayList; import java.util.List; @@ -33,9 +29,12 @@ import org.eclipse.jetty.http2.generator.HeaderGenerator; import org.eclipse.jetty.http2.parser.Parser; import org.eclipse.jetty.io.ByteBufferPool; import org.eclipse.jetty.io.MappedByteBufferPool; - import org.junit.jupiter.api.Test; +import static org.junit.jupiter.api.Assertions.assertArrayEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; + public class GoAwayGenerateParseTest { private final ByteBufferPool byteBufferPool = new MappedByteBufferPool(); diff --git a/jetty-http2/http2-common/src/test/java/org/eclipse/jetty/http2/frames/HeadersGenerateParseTest.java b/jetty-http2/http2-common/src/test/java/org/eclipse/jetty/http2/frames/HeadersGenerateParseTest.java index eaee34f3217..b67fe45d589 100644 --- a/jetty-http2/http2-common/src/test/java/org/eclipse/jetty/http2/frames/HeadersGenerateParseTest.java +++ b/jetty-http2/http2-common/src/test/java/org/eclipse/jetty/http2/frames/HeadersGenerateParseTest.java @@ -18,10 +18,6 @@ package org.eclipse.jetty.http2.frames; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertNotNull; -import static org.junit.jupiter.api.Assertions.assertTrue; - import java.nio.ByteBuffer; import java.util.ArrayList; import java.util.List; @@ -39,9 +35,12 @@ import org.eclipse.jetty.http2.hpack.HpackEncoder; import org.eclipse.jetty.http2.parser.Parser; import org.eclipse.jetty.io.ByteBufferPool; import org.eclipse.jetty.io.MappedByteBufferPool; - import org.junit.jupiter.api.Test; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertTrue; + public class HeadersGenerateParseTest { private final ByteBufferPool byteBufferPool = new MappedByteBufferPool(); diff --git a/jetty-http2/http2-common/src/test/java/org/eclipse/jetty/http2/frames/MaxFrameSizeParseTest.java b/jetty-http2/http2-common/src/test/java/org/eclipse/jetty/http2/frames/MaxFrameSizeParseTest.java index 318b335bcc9..43a97f0da81 100644 --- a/jetty-http2/http2-common/src/test/java/org/eclipse/jetty/http2/frames/MaxFrameSizeParseTest.java +++ b/jetty-http2/http2-common/src/test/java/org/eclipse/jetty/http2/frames/MaxFrameSizeParseTest.java @@ -59,7 +59,9 @@ public class MaxFrameSizeParseTest buffer.putInt(0, maxFrameLength + 1); buffer.position(1); while (buffer.hasRemaining()) + { parser.parse(buffer); + } } assertEquals(ErrorCode.FRAME_SIZE_ERROR.code, failure.get()); diff --git a/jetty-http2/http2-common/src/test/java/org/eclipse/jetty/http2/frames/PingGenerateParseTest.java b/jetty-http2/http2-common/src/test/java/org/eclipse/jetty/http2/frames/PingGenerateParseTest.java index 7dcc138c957..0b7c31f9674 100644 --- a/jetty-http2/http2-common/src/test/java/org/eclipse/jetty/http2/frames/PingGenerateParseTest.java +++ b/jetty-http2/http2-common/src/test/java/org/eclipse/jetty/http2/frames/PingGenerateParseTest.java @@ -18,10 +18,6 @@ package org.eclipse.jetty.http2.frames; -import static org.junit.jupiter.api.Assertions.assertArrayEquals; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertTrue; - import java.nio.ByteBuffer; import java.util.ArrayList; import java.util.List; @@ -33,9 +29,12 @@ import org.eclipse.jetty.http2.generator.PingGenerator; import org.eclipse.jetty.http2.parser.Parser; import org.eclipse.jetty.io.ByteBufferPool; import org.eclipse.jetty.io.MappedByteBufferPool; - import org.junit.jupiter.api.Test; +import static org.junit.jupiter.api.Assertions.assertArrayEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + public class PingGenerateParseTest { private final ByteBufferPool byteBufferPool = new MappedByteBufferPool(); diff --git a/jetty-http2/http2-common/src/test/java/org/eclipse/jetty/http2/frames/PriorityGenerateParseTest.java b/jetty-http2/http2-common/src/test/java/org/eclipse/jetty/http2/frames/PriorityGenerateParseTest.java index f4c0bbbd7b8..ecbdd10caf8 100644 --- a/jetty-http2/http2-common/src/test/java/org/eclipse/jetty/http2/frames/PriorityGenerateParseTest.java +++ b/jetty-http2/http2-common/src/test/java/org/eclipse/jetty/http2/frames/PriorityGenerateParseTest.java @@ -18,8 +18,6 @@ package org.eclipse.jetty.http2.frames; -import static org.junit.jupiter.api.Assertions.assertEquals; - import java.nio.ByteBuffer; import java.util.ArrayList; import java.util.List; @@ -30,9 +28,10 @@ import org.eclipse.jetty.http2.generator.PriorityGenerator; import org.eclipse.jetty.http2.parser.Parser; import org.eclipse.jetty.io.ByteBufferPool; import org.eclipse.jetty.io.MappedByteBufferPool; - import org.junit.jupiter.api.Test; +import static org.junit.jupiter.api.Assertions.assertEquals; + public class PriorityGenerateParseTest { private final ByteBufferPool byteBufferPool = new MappedByteBufferPool(); diff --git a/jetty-http2/http2-common/src/test/java/org/eclipse/jetty/http2/frames/PushPromiseGenerateParseTest.java b/jetty-http2/http2-common/src/test/java/org/eclipse/jetty/http2/frames/PushPromiseGenerateParseTest.java index 55206b3d6a0..3d6d8db2938 100644 --- a/jetty-http2/http2-common/src/test/java/org/eclipse/jetty/http2/frames/PushPromiseGenerateParseTest.java +++ b/jetty-http2/http2-common/src/test/java/org/eclipse/jetty/http2/frames/PushPromiseGenerateParseTest.java @@ -18,9 +18,6 @@ package org.eclipse.jetty.http2.frames; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertTrue; - import java.nio.ByteBuffer; import java.util.ArrayList; import java.util.List; @@ -38,9 +35,11 @@ import org.eclipse.jetty.http2.hpack.HpackEncoder; import org.eclipse.jetty.http2.parser.Parser; import org.eclipse.jetty.io.ByteBufferPool; import org.eclipse.jetty.io.MappedByteBufferPool; - import org.junit.jupiter.api.Test; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + public class PushPromiseGenerateParseTest { private final ByteBufferPool byteBufferPool = new MappedByteBufferPool(); diff --git a/jetty-http2/http2-common/src/test/java/org/eclipse/jetty/http2/frames/ResetGenerateParseTest.java b/jetty-http2/http2-common/src/test/java/org/eclipse/jetty/http2/frames/ResetGenerateParseTest.java index b0073907b1d..4a2f9a35d8e 100644 --- a/jetty-http2/http2-common/src/test/java/org/eclipse/jetty/http2/frames/ResetGenerateParseTest.java +++ b/jetty-http2/http2-common/src/test/java/org/eclipse/jetty/http2/frames/ResetGenerateParseTest.java @@ -18,8 +18,6 @@ package org.eclipse.jetty.http2.frames; -import static org.junit.jupiter.api.Assertions.assertEquals; - import java.nio.ByteBuffer; import java.util.ArrayList; import java.util.List; @@ -30,9 +28,10 @@ import org.eclipse.jetty.http2.generator.ResetGenerator; import org.eclipse.jetty.http2.parser.Parser; import org.eclipse.jetty.io.ByteBufferPool; import org.eclipse.jetty.io.MappedByteBufferPool; - import org.junit.jupiter.api.Test; +import static org.junit.jupiter.api.Assertions.assertEquals; + public class ResetGenerateParseTest { private final ByteBufferPool byteBufferPool = new MappedByteBufferPool(); diff --git a/jetty-http2/http2-common/src/test/java/org/eclipse/jetty/http2/frames/SettingsGenerateParseTest.java b/jetty-http2/http2-common/src/test/java/org/eclipse/jetty/http2/frames/SettingsGenerateParseTest.java index 588b3ce0530..9fcdb743dc6 100644 --- a/jetty-http2/http2-common/src/test/java/org/eclipse/jetty/http2/frames/SettingsGenerateParseTest.java +++ b/jetty-http2/http2-common/src/test/java/org/eclipse/jetty/http2/frames/SettingsGenerateParseTest.java @@ -18,9 +18,6 @@ package org.eclipse.jetty.http2.frames; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertTrue; - import java.nio.ByteBuffer; import java.util.ArrayList; import java.util.Collections; @@ -36,9 +33,11 @@ import org.eclipse.jetty.http2.generator.SettingsGenerator; import org.eclipse.jetty.http2.parser.Parser; import org.eclipse.jetty.io.ByteBufferPool; import org.eclipse.jetty.io.MappedByteBufferPool; - import org.junit.jupiter.api.Test; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + public class SettingsGenerateParseTest { private final ByteBufferPool byteBufferPool = new MappedByteBufferPool(); @@ -207,7 +206,9 @@ public class SettingsGenerateParseTest Map settings = new HashMap<>(); for (int i = 0; i < maxSettingsKeys + 1; ++i) + { settings.put(i + 10, i); + } ByteBufferPool.Lease lease = new ByteBufferPool.Lease(byteBufferPool); generator.generateSettings(lease, settings, false); @@ -215,7 +216,9 @@ public class SettingsGenerateParseTest for (ByteBuffer buffer : lease.getByteBuffers()) { while (buffer.hasRemaining()) + { parser.parse(buffer); + } } assertEquals(ErrorCode.ENHANCE_YOUR_CALM_ERROR.code, errorRef.get()); @@ -257,7 +260,9 @@ public class SettingsGenerateParseTest buffer.flip().position(1); while (buffer.hasRemaining()) + { parser.parse(buffer); + } assertEquals(ErrorCode.ENHANCE_YOUR_CALM_ERROR.code, errorRef.get()); } @@ -285,12 +290,16 @@ public class SettingsGenerateParseTest ByteBufferPool.Lease lease = new ByteBufferPool.Lease(byteBufferPool); for (int i = 0; i < maxSettingsKeys + 1; ++i) + { generator.generateSettings(lease, settings, false); + } for (ByteBuffer buffer : lease.getByteBuffers()) { while (buffer.hasRemaining()) + { parser.parse(buffer); + } } assertEquals(ErrorCode.ENHANCE_YOUR_CALM_ERROR.code, errorRef.get()); diff --git a/jetty-http2/http2-common/src/test/java/org/eclipse/jetty/http2/frames/UnknownParseTest.java b/jetty-http2/http2-common/src/test/java/org/eclipse/jetty/http2/frames/UnknownParseTest.java index 06f132f8052..9f81bfed88d 100644 --- a/jetty-http2/http2-common/src/test/java/org/eclipse/jetty/http2/frames/UnknownParseTest.java +++ b/jetty-http2/http2-common/src/test/java/org/eclipse/jetty/http2/frames/UnknownParseTest.java @@ -68,7 +68,9 @@ public class UnknownParseTest byte[] bytes = new byte[]{0, 0x40, 0x01, 64, 0, 0, 0, 0, 0}; ByteBuffer buffer = ByteBuffer.wrap(bytes); while (buffer.hasRemaining()) + { parser.parse(buffer); + } assertEquals(ErrorCode.FRAME_SIZE_ERROR.code, failure.get()); } @@ -92,7 +94,9 @@ public class UnknownParseTest byte[] bytes = new byte[]{0, 0, 4, 64, 0, 0, 0, 0, 0, 0, 0, 0, 0}; ByteBuffer buffer = ByteBuffer.wrap(bytes); while (buffer.hasRemaining()) + { parser.parse(fn.apply(buffer)); + } } assertFalse(failure.get()); diff --git a/jetty-http2/http2-common/src/test/java/org/eclipse/jetty/http2/frames/WindowUpdateGenerateParseTest.java b/jetty-http2/http2-common/src/test/java/org/eclipse/jetty/http2/frames/WindowUpdateGenerateParseTest.java index 9e8cf261e7e..04825a5e7a6 100644 --- a/jetty-http2/http2-common/src/test/java/org/eclipse/jetty/http2/frames/WindowUpdateGenerateParseTest.java +++ b/jetty-http2/http2-common/src/test/java/org/eclipse/jetty/http2/frames/WindowUpdateGenerateParseTest.java @@ -18,8 +18,6 @@ package org.eclipse.jetty.http2.frames; -import static org.junit.jupiter.api.Assertions.assertEquals; - import java.nio.ByteBuffer; import java.util.ArrayList; import java.util.List; @@ -30,9 +28,10 @@ import org.eclipse.jetty.http2.generator.WindowUpdateGenerator; import org.eclipse.jetty.http2.parser.Parser; import org.eclipse.jetty.io.ByteBufferPool; import org.eclipse.jetty.io.MappedByteBufferPool; - import org.junit.jupiter.api.Test; +import static org.junit.jupiter.api.Assertions.assertEquals; + public class WindowUpdateGenerateParseTest { private final ByteBufferPool byteBufferPool = new MappedByteBufferPool(); diff --git a/jetty-http2/http2-hpack/src/main/java/org/eclipse/jetty/http2/hpack/AuthorityHttpField.java b/jetty-http2/http2-hpack/src/main/java/org/eclipse/jetty/http2/hpack/AuthorityHttpField.java index 175b7e00856..712b4853694 100644 --- a/jetty-http2/http2-hpack/src/main/java/org/eclipse/jetty/http2/hpack/AuthorityHttpField.java +++ b/jetty-http2/http2-hpack/src/main/java/org/eclipse/jetty/http2/hpack/AuthorityHttpField.java @@ -16,28 +16,26 @@ // ======================================================================== // - package org.eclipse.jetty.http2.hpack; import org.eclipse.jetty.http.HostPortHttpField; import org.eclipse.jetty.http.HttpHeader; - -/* ------------------------------------------------------------ */ /** + * */ public class AuthorityHttpField extends HostPortHttpField { - public final static String AUTHORITY = HpackContext.STATIC_TABLE[1][0]; - + public static final String AUTHORITY = HpackContext.STATIC_TABLE[1][0]; + public AuthorityHttpField(String authority) { - super(HttpHeader.C_AUTHORITY,AUTHORITY,authority); + super(HttpHeader.C_AUTHORITY, AUTHORITY, authority); } - + @Override public String toString() { - return String.format("%s(preparsed h=%s p=%d)",super.toString(),getHost(),getPort()); + return String.format("%s(preparsed h=%s p=%d)", super.toString(), getHost(), getPort()); } } diff --git a/jetty-http2/http2-hpack/src/main/java/org/eclipse/jetty/http2/hpack/HpackContext.java b/jetty-http2/http2-hpack/src/main/java/org/eclipse/jetty/http2/hpack/HpackContext.java index 59c1b4f6e50..675d8269e94 100644 --- a/jetty-http2/http2-hpack/src/main/java/org/eclipse/jetty/http2/hpack/HpackContext.java +++ b/jetty-http2/http2-hpack/src/main/java/org/eclipse/jetty/http2/hpack/HpackContext.java @@ -48,87 +48,88 @@ public class HpackContext public static final Logger LOG = Log.getLogger(HpackContext.class); private static final String EMPTY = ""; public static final String[][] STATIC_TABLE = - { - {null,null}, - /* 1 */ {":authority",EMPTY}, - /* 2 */ {":method","GET"}, - /* 3 */ {":method","POST"}, - /* 4 */ {":path","/"}, - /* 5 */ {":path","/index.html"}, - /* 6 */ {":scheme","http"}, - /* 7 */ {":scheme","https"}, - /* 8 */ {":status","200"}, - /* 9 */ {":status","204"}, - /* 10 */ {":status","206"}, - /* 11 */ {":status","304"}, - /* 12 */ {":status","400"}, - /* 13 */ {":status","404"}, - /* 14 */ {":status","500"}, - /* 15 */ {"accept-charset",EMPTY}, - /* 16 */ {"accept-encoding","gzip, deflate"}, - /* 17 */ {"accept-language",EMPTY}, - /* 18 */ {"accept-ranges",EMPTY}, - /* 19 */ {"accept",EMPTY}, - /* 20 */ {"access-control-allow-origin",EMPTY}, - /* 21 */ {"age",EMPTY}, - /* 22 */ {"allow",EMPTY}, - /* 23 */ {"authorization",EMPTY}, - /* 24 */ {"cache-control",EMPTY}, - /* 25 */ {"content-disposition",EMPTY}, - /* 26 */ {"content-encoding",EMPTY}, - /* 27 */ {"content-language",EMPTY}, - /* 28 */ {"content-length",EMPTY}, - /* 29 */ {"content-location",EMPTY}, - /* 30 */ {"content-range",EMPTY}, - /* 31 */ {"content-type",EMPTY}, - /* 32 */ {"cookie",EMPTY}, - /* 33 */ {"date",EMPTY}, - /* 34 */ {"etag",EMPTY}, - /* 35 */ {"expect",EMPTY}, - /* 36 */ {"expires",EMPTY}, - /* 37 */ {"from",EMPTY}, - /* 38 */ {"host",EMPTY}, - /* 39 */ {"if-match",EMPTY}, - /* 40 */ {"if-modified-since",EMPTY}, - /* 41 */ {"if-none-match",EMPTY}, - /* 42 */ {"if-range",EMPTY}, - /* 43 */ {"if-unmodified-since",EMPTY}, - /* 44 */ {"last-modified",EMPTY}, - /* 45 */ {"link",EMPTY}, - /* 46 */ {"location",EMPTY}, - /* 47 */ {"max-forwards",EMPTY}, - /* 48 */ {"proxy-authenticate",EMPTY}, - /* 49 */ {"proxy-authorization",EMPTY}, - /* 50 */ {"range",EMPTY}, - /* 51 */ {"referer",EMPTY}, - /* 52 */ {"refresh",EMPTY}, - /* 53 */ {"retry-after",EMPTY}, - /* 54 */ {"server",EMPTY}, - /* 55 */ {"set-cookie",EMPTY}, - /* 56 */ {"strict-transport-security",EMPTY}, - /* 57 */ {"transfer-encoding",EMPTY}, - /* 58 */ {"user-agent",EMPTY}, - /* 59 */ {"vary",EMPTY}, - /* 60 */ {"via",EMPTY}, - /* 61 */ {"www-authenticate",EMPTY}, - }; + { + {null, null}, + /* 1 */ {":authority", EMPTY}, + /* 2 */ {":method", "GET"}, + /* 3 */ {":method", "POST"}, + /* 4 */ {":path", "/"}, + /* 5 */ {":path", "/index.html"}, + /* 6 */ {":scheme", "http"}, + /* 7 */ {":scheme", "https"}, + /* 8 */ {":status", "200"}, + /* 9 */ {":status", "204"}, + /* 10 */ {":status", "206"}, + /* 11 */ {":status", "304"}, + /* 12 */ {":status", "400"}, + /* 13 */ {":status", "404"}, + /* 14 */ {":status", "500"}, + /* 15 */ {"accept-charset", EMPTY}, + /* 16 */ {"accept-encoding", "gzip, deflate"}, + /* 17 */ {"accept-language", EMPTY}, + /* 18 */ {"accept-ranges", EMPTY}, + /* 19 */ {"accept", EMPTY}, + /* 20 */ {"access-control-allow-origin", EMPTY}, + /* 21 */ {"age", EMPTY}, + /* 22 */ {"allow", EMPTY}, + /* 23 */ {"authorization", EMPTY}, + /* 24 */ {"cache-control", EMPTY}, + /* 25 */ {"content-disposition", EMPTY}, + /* 26 */ {"content-encoding", EMPTY}, + /* 27 */ {"content-language", EMPTY}, + /* 28 */ {"content-length", EMPTY}, + /* 29 */ {"content-location", EMPTY}, + /* 30 */ {"content-range", EMPTY}, + /* 31 */ {"content-type", EMPTY}, + /* 32 */ {"cookie", EMPTY}, + /* 33 */ {"date", EMPTY}, + /* 34 */ {"etag", EMPTY}, + /* 35 */ {"expect", EMPTY}, + /* 36 */ {"expires", EMPTY}, + /* 37 */ {"from", EMPTY}, + /* 38 */ {"host", EMPTY}, + /* 39 */ {"if-match", EMPTY}, + /* 40 */ {"if-modified-since", EMPTY}, + /* 41 */ {"if-none-match", EMPTY}, + /* 42 */ {"if-range", EMPTY}, + /* 43 */ {"if-unmodified-since", EMPTY}, + /* 44 */ {"last-modified", EMPTY}, + /* 45 */ {"link", EMPTY}, + /* 46 */ {"location", EMPTY}, + /* 47 */ {"max-forwards", EMPTY}, + /* 48 */ {"proxy-authenticate", EMPTY}, + /* 49 */ {"proxy-authorization", EMPTY}, + /* 50 */ {"range", EMPTY}, + /* 51 */ {"referer", EMPTY}, + /* 52 */ {"refresh", EMPTY}, + /* 53 */ {"retry-after", EMPTY}, + /* 54 */ {"server", EMPTY}, + /* 55 */ {"set-cookie", EMPTY}, + /* 56 */ {"strict-transport-security", EMPTY}, + /* 57 */ {"transfer-encoding", EMPTY}, + /* 58 */ {"user-agent", EMPTY}, + /* 59 */ {"vary", EMPTY}, + /* 60 */ {"via", EMPTY}, + /* 61 */ {"www-authenticate", EMPTY} + }; - private static final Map __staticFieldMap = new HashMap<>(); - private static final Trie __staticNameMap = new ArrayTernaryTrie<>(true,512); + private static final Map __staticFieldMap = new HashMap<>(); + private static final Trie __staticNameMap = new ArrayTernaryTrie<>(true, 512); private static final StaticEntry[] __staticTableByHeader = new StaticEntry[HttpHeader.UNKNOWN.ordinal()]; - private static final StaticEntry[] __staticTable=new StaticEntry[STATIC_TABLE.length]; - public static final int STATIC_SIZE = STATIC_TABLE.length-1; + private static final StaticEntry[] __staticTable = new StaticEntry[STATIC_TABLE.length]; + public static final int STATIC_SIZE = STATIC_TABLE.length - 1; + static { Set added = new HashSet<>(); - for (int i=1;i _fieldMap = new HashMap<>(); - private final Map _nameMap = new HashMap<>(); + private final Map _fieldMap = new HashMap<>(); + private final Map _nameMap = new HashMap<>(); HpackContext(int maxDynamicTableSize) { - _maxDynamicTableSizeInBytes=maxDynamicTableSize; - int guesstimateEntries = 10+maxDynamicTableSize/(32+10+10); - _dynamicTable=new DynamicTable(guesstimateEntries); + _maxDynamicTableSizeInBytes = maxDynamicTableSize; + int guesstimateEntries = 10 + maxDynamicTableSize / (32 + 10 + 10); + _dynamicTable = new DynamicTable(guesstimateEntries); if (LOG.isDebugEnabled()) - LOG.debug(String.format("HdrTbl[%x] created max=%d",hashCode(),maxDynamicTableSize)); + LOG.debug(String.format("HdrTbl[%x] created max=%d", hashCode(), maxDynamicTableSize)); } public void resize(int newMaxDynamicTableSize) { if (LOG.isDebugEnabled()) - LOG.debug(String.format("HdrTbl[%x] resized max=%d->%d",hashCode(),_maxDynamicTableSizeInBytes,newMaxDynamicTableSize)); - _maxDynamicTableSizeInBytes=newMaxDynamicTableSize; + LOG.debug(String.format("HdrTbl[%x] resized max=%d->%d", hashCode(), _maxDynamicTableSizeInBytes, newMaxDynamicTableSize)); + _maxDynamicTableSizeInBytes = newMaxDynamicTableSize; _dynamicTable.evict(); } public Entry get(HttpField field) { Entry entry = _fieldMap.get(field); - if (entry==null) - entry=__staticFieldMap.get(field); + if (entry == null) + entry = __staticFieldMap.get(field); return entry; } public Entry get(String name) { Entry entry = __staticNameMap.get(name); - if (entry!=null) + if (entry != null) return entry; return _nameMap.get(StringUtil.asciiToLowerCase(name)); } public Entry get(int index) { - if (index<=STATIC_SIZE) + if (index <= STATIC_SIZE) return __staticTable[index]; return _dynamicTable.get(index); @@ -237,7 +237,7 @@ public class HpackContext public Entry get(HttpHeader header) { Entry e = __staticTableByHeader[header.ordinal()]; - if (e==null) + if (e == null) return get(header.asString()); return e; } @@ -249,22 +249,22 @@ public class HpackContext public Entry add(HttpField field) { - Entry entry=new Entry(field); + Entry entry = new Entry(field); int size = entry.getSize(); - if (size>_maxDynamicTableSizeInBytes) + if (size > _maxDynamicTableSizeInBytes) { if (LOG.isDebugEnabled()) - LOG.debug(String.format("HdrTbl[%x] !added size %d>%d",hashCode(),size,_maxDynamicTableSizeInBytes)); + LOG.debug(String.format("HdrTbl[%x] !added size %d>%d", hashCode(), size, _maxDynamicTableSizeInBytes)); _dynamicTable.evictAll(); return null; } - _dynamicTableSizeInBytes+=size; + _dynamicTableSizeInBytes += size; _dynamicTable.add(entry); - _fieldMap.put(field,entry); - _nameMap.put(StringUtil.asciiToLowerCase(field.getName()),entry); + _fieldMap.put(field, entry); + _nameMap.put(StringUtil.asciiToLowerCase(field.getName()), entry); if (LOG.isDebugEnabled()) - LOG.debug(String.format("HdrTbl[%x] added %s",hashCode(),entry)); + LOG.debug(String.format("HdrTbl[%x] added %s", hashCode(), entry)); _dynamicTable.evict(); return entry; } @@ -295,7 +295,7 @@ public class HpackContext public int index(Entry entry) { - if (entry._slot<0) + if (entry._slot < 0) return 0; if (entry.isStatic()) return entry._slot; @@ -305,64 +305,63 @@ public class HpackContext public static int staticIndex(HttpHeader header) { - if (header==null) + if (header == null) return 0; - Entry entry=__staticNameMap.get(header.asString()); - if (entry==null) + Entry entry = __staticNameMap.get(header.asString()); + if (entry == null) return 0; return entry._slot; } - @Override public String toString() { - return String.format("HpackContext@%x{entries=%d,size=%d,max=%d}",hashCode(),_dynamicTable.size(),_dynamicTableSizeInBytes,_maxDynamicTableSizeInBytes); + return String.format("HpackContext@%x{entries=%d,size=%d,max=%d}", hashCode(), _dynamicTable.size(), _dynamicTableSizeInBytes, _maxDynamicTableSizeInBytes); } - private class DynamicTable + private class DynamicTable { Entry[] _entries; int _size; int _offset; int _growby; - + private DynamicTable(int initCapacity) { - _entries=new Entry[initCapacity]; - _growby=initCapacity; + _entries = new Entry[initCapacity]; + _growby = initCapacity; } public void add(Entry entry) { - if (_size==_entries.length) + if (_size == _entries.length) { - Entry[] entries = new Entry[_entries.length+_growby]; - for (int i=0;i<_size;i++) + Entry[] entries = new Entry[_entries.length + _growby]; + for (int i = 0; i < _size; i++) { - int slot = (_offset+i)%_entries.length; - entries[i]=_entries[slot]; - entries[i]._slot=i; + int slot = (_offset + i) % _entries.length; + entries[i] = _entries[slot]; + entries[i]._slot = i; } - _entries=entries; - _offset=0; + _entries = entries; + _offset = 0; } - int slot=(_size++ + _offset)%_entries.length; - _entries[slot]=entry; - entry._slot=slot; + int slot = (_size++ + _offset) % _entries.length; + _entries[slot] = entry; + entry._slot = slot; } public int index(Entry entry) { - return STATIC_SIZE + _size-(entry._slot-_offset+_entries.length)%_entries.length; + return STATIC_SIZE + _size - (entry._slot - _offset + _entries.length) % _entries.length; } - + public Entry get(int index) { - int d = index-STATIC_SIZE-1; - if (d<0 || d>=_size) + int d = index - STATIC_SIZE - 1; + if (d < 0 || d >= _size) return null; - int slot = (_offset+_size-d-1)%_entries.length; + int slot = (_offset + _size - d - 1) % _entries.length; return _entries[slot]; } @@ -373,36 +372,35 @@ public class HpackContext private void evict() { - while (_dynamicTableSizeInBytes>_maxDynamicTableSizeInBytes) + while (_dynamicTableSizeInBytes > _maxDynamicTableSizeInBytes) { Entry entry = _entries[_offset]; - _entries[_offset]=null; - _offset = (_offset+1)%_entries.length; + _entries[_offset] = null; + _offset = (_offset + 1) % _entries.length; _size--; if (LOG.isDebugEnabled()) - LOG.debug(String.format("HdrTbl[%x] evict %s",HpackContext.this.hashCode(),entry)); - _dynamicTableSizeInBytes-=entry.getSize(); - entry._slot=-1; + LOG.debug(String.format("HdrTbl[%x] evict %s", HpackContext.this.hashCode(), entry)); + _dynamicTableSizeInBytes -= entry.getSize(); + entry._slot = -1; _fieldMap.remove(entry.getHttpField()); - String lc=StringUtil.asciiToLowerCase(entry.getHttpField().getName()); - if (entry==_nameMap.get(lc)) + String lc = StringUtil.asciiToLowerCase(entry.getHttpField().getName()); + if (entry == _nameMap.get(lc)) _nameMap.remove(lc); - } if (LOG.isDebugEnabled()) - LOG.debug(String.format("HdrTbl[%x] entries=%d, size=%d, max=%d",HpackContext.this.hashCode(),_dynamicTable.size(),_dynamicTableSizeInBytes,_maxDynamicTableSizeInBytes)); + LOG.debug(String.format("HdrTbl[%x] entries=%d, size=%d, max=%d", HpackContext.this.hashCode(), _dynamicTable.size(), _dynamicTableSizeInBytes, _maxDynamicTableSizeInBytes)); } - + private void evictAll() { if (LOG.isDebugEnabled()) - LOG.debug(String.format("HdrTbl[%x] evictAll",HpackContext.this.hashCode())); + LOG.debug(String.format("HdrTbl[%x] evictAll", HpackContext.this.hashCode())); _fieldMap.clear(); _nameMap.clear(); _offset = 0; _size = 0; _dynamicTableSizeInBytes = 0; - Arrays.fill(_entries,null); + Arrays.fill(_entries, null); } } @@ -413,13 +411,13 @@ public class HpackContext Entry() { - _slot=-1; - _field=null; + _slot = -1; + _field = null; } Entry(HttpField field) { - _field=field; + _field = field; } public int getSize() @@ -446,7 +444,7 @@ public class HpackContext @Override public String toString() { - return String.format("{%s,%d,%s,%x}",isStatic()?"S":"D",_slot,_field,hashCode()); + return String.format("{%s,%d,%s,%x}", isStatic() ? "S" : "D", _slot, _field, hashCode()); } } @@ -455,29 +453,29 @@ public class HpackContext private final byte[] _huffmanValue; private final byte _encodedField; - StaticEntry(int index,HttpField field) + StaticEntry(int index, HttpField field) { super(field); - _slot=index; + _slot = index; String value = field.getValue(); - if (value!=null && value.length()>0) + if (value != null && value.length() > 0) { int huffmanLen = Huffman.octetsNeeded(value); - int lenLen = NBitInteger.octectsNeeded(7,huffmanLen); - _huffmanValue = new byte[1+lenLen+huffmanLen]; + int lenLen = NBitInteger.octectsNeeded(7, huffmanLen); + _huffmanValue = new byte[1 + lenLen + huffmanLen]; ByteBuffer buffer = ByteBuffer.wrap(_huffmanValue); // Indicate Huffman buffer.put((byte)0x80); // Add huffman length - NBitInteger.encode(buffer,7,huffmanLen); + NBitInteger.encode(buffer, 7, huffmanLen); // Encode value - Huffman.encode(buffer,value); + Huffman.encode(buffer, value); } else - _huffmanValue=null; + _huffmanValue = null; - _encodedField=(byte)(0x80|index); + _encodedField = (byte)(0x80 | index); } @Override diff --git a/jetty-http2/http2-hpack/src/main/java/org/eclipse/jetty/http2/hpack/HpackDecoder.java b/jetty-http2/http2-hpack/src/main/java/org/eclipse/jetty/http2/hpack/HpackDecoder.java index dc0af4d8a5b..34c47201932 100644 --- a/jetty-http2/http2-hpack/src/main/java/org/eclipse/jetty/http2/hpack/HpackDecoder.java +++ b/jetty-http2/http2-hpack/src/main/java/org/eclipse/jetty/http2/hpack/HpackDecoder.java @@ -16,7 +16,6 @@ // ======================================================================== // - package org.eclipse.jetty.http2.hpack; import java.nio.ByteBuffer; @@ -36,21 +35,21 @@ import org.eclipse.jetty.util.log.Logger; public class HpackDecoder { public static final Logger LOG = Log.getLogger(HpackDecoder.class); - public final static HttpField.LongValueHttpField CONTENT_LENGTH_0 = - new HttpField.LongValueHttpField(HttpHeader.CONTENT_LENGTH,0L); + public static final HttpField.LongValueHttpField CONTENT_LENGTH_0 = + new HttpField.LongValueHttpField(HttpHeader.CONTENT_LENGTH, 0L); private final HpackContext _context; private final MetaDataBuilder _builder; private int _localMaxDynamicTableSize; /** - * @param localMaxDynamicTableSize The maximum allowed size of the local dynamic header field table. + * @param localMaxDynamicTableSize The maximum allowed size of the local dynamic header field table. * @param maxHeaderSize The maximum allowed size of a headers block, expressed as total of all name and value characters, plus 32 per field */ public HpackDecoder(int localMaxDynamicTableSize, int maxHeaderSize) { - _context=new HpackContext(localMaxDynamicTableSize); - _localMaxDynamicTableSize=localMaxDynamicTableSize; + _context = new HpackContext(localMaxDynamicTableSize); + _localMaxDynamicTableSize = localMaxDynamicTableSize; _builder = new MetaDataBuilder(maxHeaderSize); } @@ -61,43 +60,43 @@ public class HpackDecoder public void setLocalMaxDynamicTableSize(int localMaxdynamciTableSize) { - _localMaxDynamicTableSize=localMaxdynamciTableSize; + _localMaxDynamicTableSize = localMaxdynamciTableSize; } public MetaData decode(ByteBuffer buffer) throws HpackException.SessionException, HpackException.StreamException { if (LOG.isDebugEnabled()) - LOG.debug(String.format("CtxTbl[%x] decoding %d octets",_context.hashCode(),buffer.remaining())); + LOG.debug(String.format("CtxTbl[%x] decoding %d octets", _context.hashCode(), buffer.remaining())); // If the buffer is big, don't even think about decoding it - if (buffer.remaining()>_builder.getMaxSize()) + if (buffer.remaining() > _builder.getMaxSize()) throw new HpackException.SessionException("431 Request Header Fields too large"); - + boolean emitted = false; - while(buffer.hasRemaining()) + while (buffer.hasRemaining()) { if (LOG.isDebugEnabled() && buffer.hasArray()) { - int l=Math.min(buffer.remaining(),32); + int l = Math.min(buffer.remaining(), 32); LOG.debug("decode {}{}", - TypeUtil.toHexString(buffer.array(),buffer.arrayOffset()+buffer.position(),l), - l>4); + byte f = (byte)((b & 0xF0) >> 4); String name; HttpHeader header; String value; boolean indexed; - int name_index; + int nameIndex; switch (f) { case 2: // 7.3 case 3: // 7.3 // change table size - int size = NBitInteger.decode(buffer,5); + int size = NBitInteger.decode(buffer, 5); if (LOG.isDebugEnabled()) - LOG.debug("decode resize="+size); - if (size>_localMaxDynamicTableSize) + LOG.debug("decode resize=" + size); + if (size > _localMaxDynamicTableSize) throw new IllegalArgumentException(); if (emitted) throw new HpackException.CompressionException("Dynamic table resize after fields"); @@ -142,79 +141,79 @@ public class HpackDecoder case 0: // 7.2.2 case 1: // 7.2.3 - indexed=false; - name_index=NBitInteger.decode(buffer,4); + indexed = false; + nameIndex = NBitInteger.decode(buffer, 4); break; case 4: // 7.2.1 case 5: // 7.2.1 case 6: // 7.2.1 case 7: // 7.2.1 - indexed=true; - name_index=NBitInteger.decode(buffer,6); + indexed = true; + nameIndex = NBitInteger.decode(buffer, 6); break; default: throw new IllegalStateException(); } - boolean huffmanName=false; + boolean huffmanName = false; // decode the name - if (name_index>0) + if (nameIndex > 0) { - Entry name_entry=_context.get(name_index); - name=name_entry.getHttpField().getName(); - header=name_entry.getHttpField().getHeader(); + Entry nameEntry = _context.get(nameIndex); + name = nameEntry.getHttpField().getName(); + header = nameEntry.getHttpField().getHeader(); } else { - huffmanName = (buffer.get()&0x80)==0x80; - int length = NBitInteger.decode(buffer,7); - _builder.checkSize(length,huffmanName); + huffmanName = (buffer.get() & 0x80) == 0x80; + int length = NBitInteger.decode(buffer, 7); + _builder.checkSize(length, huffmanName); if (huffmanName) - name=Huffman.decode(buffer,length); + name = Huffman.decode(buffer, length); else - name=toASCIIString(buffer,length); - for (int i=0;i='A'&&c<='Z') + char c = name.charAt(i); + if (c >= 'A' && c <= 'Z') { - _builder.streamException("Uppercase header name %s",name); + _builder.streamException("Uppercase header name %s", name); break; } } - header=HttpHeader.CACHE.get(name); + header = HttpHeader.CACHE.get(name); } // decode the value - boolean huffmanValue = (buffer.get()&0x80)==0x80; - int length = NBitInteger.decode(buffer,7); - _builder.checkSize(length,huffmanValue); + boolean huffmanValue = (buffer.get() & 0x80) == 0x80; + int length = NBitInteger.decode(buffer, 7); + _builder.checkSize(length, huffmanValue); if (huffmanValue) - value=Huffman.decode(buffer,length); + value = Huffman.decode(buffer, length); else - value=toASCIIString(buffer,length); + value = toASCIIString(buffer, length); // Make the new field HttpField field; - if (header==null) + if (header == null) { // just make a normal field and bypass header name lookup - field = new HttpField(null,name,value); + field = new HttpField(null, name, value); } else { // might be worthwhile to create a value HttpField if it is indexed // and/or of a type that may be looked up multiple times. - switch(header) + switch (header) { case C_STATUS: if (indexed) - field = new HttpField.IntValueHttpField(header,name,value); + field = new HttpField.IntValueHttpField(header, name, value); else - field = new HttpField(header,name,value); + field = new HttpField(header, name, value); break; case C_AUTHORITY: @@ -225,11 +224,11 @@ public class HpackDecoder if ("0".equals(value)) field = CONTENT_LENGTH_0; else - field = new HttpField.LongValueHttpField(header,name,value); + field = new HttpField.LongValueHttpField(header, name, value); break; default: - field = new HttpField(header,name,value); + field = new HttpField(header, name, value); break; } } @@ -237,10 +236,10 @@ public class HpackDecoder if (LOG.isDebugEnabled()) { LOG.debug("decoded '{}' by {}/{}/{}", - field, - name_index > 0 ? "IdxName" : (huffmanName ? "HuffName" : "LitName"), - huffmanValue ? "HuffVal" : "LitVal", - indexed ? "Idx" : ""); + field, + nameIndex > 0 ? "IdxName" : (huffmanName ? "HuffName" : "LitName"), + huffmanValue ? "HuffVal" : "LitVal", + indexed ? "Idx" : ""); } // emit the field @@ -256,22 +255,24 @@ public class HpackDecoder return _builder.build(); } - public static String toASCIIString(ByteBuffer buffer,int length) + public static String toASCIIString(ByteBuffer buffer, int length) { StringBuilder builder = new StringBuilder(length); - int position=buffer.position(); - int start=buffer.arrayOffset()+ position; - int end=start+length; - buffer.position(position+length); - byte[] array=buffer.array(); - for (int i=start;i __DO_NOT_HUFFMAN = - EnumSet.of( - HttpHeader.AUTHORIZATION, - HttpHeader.CONTENT_MD5, - HttpHeader.PROXY_AUTHENTICATE, - HttpHeader.PROXY_AUTHORIZATION); - final static EnumSet __DO_NOT_INDEX = - EnumSet.of( - // HttpHeader.C_PATH, // TODO more data needed - // HttpHeader.DATE, // TODO more data needed - HttpHeader.AUTHORIZATION, - HttpHeader.CONTENT_MD5, - HttpHeader.CONTENT_RANGE, - HttpHeader.ETAG, - HttpHeader.IF_MODIFIED_SINCE, - HttpHeader.IF_UNMODIFIED_SINCE, - HttpHeader.IF_NONE_MATCH, - HttpHeader.IF_RANGE, - HttpHeader.IF_MATCH, - HttpHeader.LOCATION, - HttpHeader.RANGE, - HttpHeader.RETRY_AFTER, - // HttpHeader.EXPIRES, - HttpHeader.LAST_MODIFIED, - HttpHeader.SET_COOKIE, - HttpHeader.SET_COOKIE2); - final static EnumSet __NEVER_INDEX = - EnumSet.of( - HttpHeader.AUTHORIZATION, - HttpHeader.SET_COOKIE, - HttpHeader.SET_COOKIE2); + private static final HttpField[] __status = new HttpField[599]; + static final EnumSet __DO_NOT_HUFFMAN = + EnumSet.of( + HttpHeader.AUTHORIZATION, + HttpHeader.CONTENT_MD5, + HttpHeader.PROXY_AUTHENTICATE, + HttpHeader.PROXY_AUTHORIZATION); + static final EnumSet __DO_NOT_INDEX = + EnumSet.of( + // HttpHeader.C_PATH, // TODO more data needed + // HttpHeader.DATE, // TODO more data needed + HttpHeader.AUTHORIZATION, + HttpHeader.CONTENT_MD5, + HttpHeader.CONTENT_RANGE, + HttpHeader.ETAG, + HttpHeader.IF_MODIFIED_SINCE, + HttpHeader.IF_UNMODIFIED_SINCE, + HttpHeader.IF_NONE_MATCH, + HttpHeader.IF_RANGE, + HttpHeader.IF_MATCH, + HttpHeader.LOCATION, + HttpHeader.RANGE, + HttpHeader.RETRY_AFTER, + // HttpHeader.EXPIRES, + HttpHeader.LAST_MODIFIED, + HttpHeader.SET_COOKIE, + HttpHeader.SET_COOKIE2); + static final EnumSet __NEVER_INDEX = + EnumSet.of( + HttpHeader.AUTHORIZATION, + HttpHeader.SET_COOKIE, + HttpHeader.SET_COOKIE2); private static final PreEncodedHttpField CONNECTION_TE = new PreEncodedHttpField(HttpHeader.CONNECTION, "te"); private static final PreEncodedHttpField TE_TRAILERS = new PreEncodedHttpField(HttpHeader.TE, "trailers"); private static final Trie specialHopHeaders = new ArrayTrie<>(6); @@ -83,7 +82,9 @@ public class HpackEncoder static { for (HttpStatus.Code code : HttpStatus.Code.values()) - __status[code.getCode()]=new PreEncodedHttpField(HttpHeader.C_STATUS,Integer.toString(code.getCode())); + { + __status[code.getCode()] = new PreEncodedHttpField(HttpHeader.C_STATUS, Integer.toString(code.getCode())); + } specialHopHeaders.put("close", true); specialHopHeaders.put("te", true); } @@ -97,26 +98,26 @@ public class HpackEncoder public HpackEncoder() { - this(4096,4096,-1); + this(4096, 4096, -1); } public HpackEncoder(int localMaxDynamicTableSize) { - this(localMaxDynamicTableSize,4096,-1); + this(localMaxDynamicTableSize, 4096, -1); } - - public HpackEncoder(int localMaxDynamicTableSize,int remoteMaxDynamicTableSize) + + public HpackEncoder(int localMaxDynamicTableSize, int remoteMaxDynamicTableSize) { - this(localMaxDynamicTableSize,remoteMaxDynamicTableSize,-1); + this(localMaxDynamicTableSize, remoteMaxDynamicTableSize, -1); } - - public HpackEncoder(int localMaxDynamicTableSize,int remoteMaxDynamicTableSize, int maxHeaderListSize) + + public HpackEncoder(int localMaxDynamicTableSize, int remoteMaxDynamicTableSize, int maxHeaderListSize) { - _context=new HpackContext(remoteMaxDynamicTableSize); - _remoteMaxDynamicTableSize=remoteMaxDynamicTableSize; - _localMaxDynamicTableSize=localMaxDynamicTableSize; - _maxHeaderListSize=maxHeaderListSize; - _debug=LOG.isDebugEnabled(); + _context = new HpackContext(remoteMaxDynamicTableSize); + _remoteMaxDynamicTableSize = remoteMaxDynamicTableSize; + _localMaxDynamicTableSize = localMaxDynamicTableSize; + _maxHeaderListSize = maxHeaderListSize; + _debug = LOG.isDebugEnabled(); } public int getMaxHeaderListSize() @@ -136,26 +137,26 @@ public class HpackEncoder public void setRemoteMaxDynamicTableSize(int remoteMaxDynamicTableSize) { - _remoteMaxDynamicTableSize=remoteMaxDynamicTableSize; + _remoteMaxDynamicTableSize = remoteMaxDynamicTableSize; } public void setLocalMaxDynamicTableSize(int localMaxDynamicTableSize) { - _localMaxDynamicTableSize=localMaxDynamicTableSize; + _localMaxDynamicTableSize = localMaxDynamicTableSize; } public void encode(ByteBuffer buffer, MetaData metadata) { if (LOG.isDebugEnabled()) - LOG.debug(String.format("CtxTbl[%x] encoding",_context.hashCode())); + LOG.debug(String.format("CtxTbl[%x] encoding", _context.hashCode())); - _headerListSize=0; + _headerListSize = 0; int pos = buffer.position(); // Check the dynamic table sizes! - int maxDynamicTableSize=Math.min(_remoteMaxDynamicTableSize,_localMaxDynamicTableSize); - if (maxDynamicTableSize!=_context.getMaxDynamicTableSize()) - encodeMaxDynamicTableSize(buffer,maxDynamicTableSize); + int maxDynamicTableSize = Math.min(_remoteMaxDynamicTableSize, _localMaxDynamicTableSize); + if (maxDynamicTableSize != _context.getMaxDynamicTableSize()) + encodeMaxDynamicTableSize(buffer, maxDynamicTableSize); // Add Request/response meta fields if (metadata.isRequest()) @@ -163,20 +164,20 @@ public class HpackEncoder MetaData.Request request = (MetaData.Request)metadata; // TODO optimise these to avoid HttpField creation - String scheme=request.getURI().getScheme(); - encode(buffer,new HttpField(HttpHeader.C_SCHEME,scheme==null?HttpScheme.HTTP.asString():scheme)); - encode(buffer,new HttpField(HttpHeader.C_METHOD,request.getMethod())); - encode(buffer,new HttpField(HttpHeader.C_AUTHORITY,request.getURI().getAuthority())); - encode(buffer,new HttpField(HttpHeader.C_PATH,request.getURI().getPathQuery())); + String scheme = request.getURI().getScheme(); + encode(buffer, new HttpField(HttpHeader.C_SCHEME, scheme == null ? HttpScheme.HTTP.asString() : scheme)); + encode(buffer, new HttpField(HttpHeader.C_METHOD, request.getMethod())); + encode(buffer, new HttpField(HttpHeader.C_AUTHORITY, request.getURI().getAuthority())); + encode(buffer, new HttpField(HttpHeader.C_PATH, request.getURI().getPathQuery())); } else if (metadata.isResponse()) { MetaData.Response response = (MetaData.Response)metadata; - int code=response.getStatus(); - HttpField status = code<__status.length?__status[code]:null; - if (status==null) - status=new HttpField.IntValueHttpField(HttpHeader.C_STATUS,code); - encode(buffer,status); + int code = response.getStatus(); + HttpField status = code < __status.length ? __status[code] : null; + if (status == null) + status = new HttpField.IntValueHttpField(HttpHeader.C_STATUS, code); + encode(buffer, status); } // Add all non-connection fields. @@ -184,9 +185,9 @@ public class HpackEncoder if (fields != null) { Set hopHeaders = fields.getCSV(HttpHeader.CONNECTION, false).stream() - .filter(v -> specialHopHeaders.get(v) == Boolean.TRUE) - .map(StringUtil::asciiToLowerCase) - .collect(Collectors.toSet()); + .filter(v -> specialHopHeaders.get(v) == Boolean.TRUE) + .map(StringUtil::asciiToLowerCase) + .collect(Collectors.toSet()); for (HttpField field : fields) { if (field.getHeader() == HttpHeader.CONNECTION) @@ -200,61 +201,61 @@ public class HpackEncoder encode(buffer, CONNECTION_TE); encode(buffer, TE_TRAILERS); } - encode(buffer,field); + encode(buffer, field); } } // Check size - if (_maxHeaderListSize>0 && _headerListSize>_maxHeaderListSize) + if (_maxHeaderListSize > 0 && _headerListSize > _maxHeaderListSize) { - LOG.warn("Header list size too large {} > {} for {}",_headerListSize,_maxHeaderListSize); + LOG.warn("Header list size too large {} > {} for {}", _headerListSize, _maxHeaderListSize); if (LOG.isDebugEnabled()) - LOG.debug("metadata={}",metadata); + LOG.debug("metadata={}", metadata); } - + if (LOG.isDebugEnabled()) - LOG.debug(String.format("CtxTbl[%x] encoded %d octets",_context.hashCode(), buffer.position() - pos)); + LOG.debug(String.format("CtxTbl[%x] encoded %d octets", _context.hashCode(), buffer.position() - pos)); } public void encodeMaxDynamicTableSize(ByteBuffer buffer, int maxDynamicTableSize) { - if (maxDynamicTableSize>_remoteMaxDynamicTableSize) + if (maxDynamicTableSize > _remoteMaxDynamicTableSize) throw new IllegalArgumentException(); buffer.put((byte)0x20); - NBitInteger.encode(buffer,5,maxDynamicTableSize); + NBitInteger.encode(buffer, 5, maxDynamicTableSize); _context.resize(maxDynamicTableSize); } public void encode(ByteBuffer buffer, HttpField field) { - if (field.getValue()==null) - field = new HttpField(field.getHeader(),field.getName(),""); - - int field_size = field.getName().length() + field.getValue().length(); - _headerListSize+=field_size+32; - - final int p=_debug?buffer.position():-1; + if (field.getValue() == null) + field = new HttpField(field.getHeader(), field.getName(), ""); - String encoding=null; + int fieldSize = field.getName().length() + field.getValue().length(); + _headerListSize += fieldSize + 32; + + final int p = _debug ? buffer.position() : -1; + + String encoding = null; // Is there an entry for the field? Entry entry = _context.get(field); - if (entry!=null) + if (entry != null) { // Known field entry, so encode it as indexed if (entry.isStatic()) { buffer.put(((StaticEntry)entry).getEncodedField()); if (_debug) - encoding="IdxFieldS1"; + encoding = "IdxFieldS1"; } else { - int index=_context.index(entry); + int index = _context.index(entry); buffer.put((byte)0x80); - NBitInteger.encode(buffer,7,index); + NBitInteger.encode(buffer, 7, index); if (_debug) - encoding="IdxField"+(entry.isStatic()?"S":"")+(1+NBitInteger.octectsNeeded(7,index)); + encoding = "IdxField" + (entry.isStatic() ? "S" : "") + (1 + NBitInteger.octectsNeeded(7, index)); } } else @@ -266,41 +267,41 @@ public class HpackEncoder HttpHeader header = field.getHeader(); // Select encoding strategy - if (header==null) + if (header == null) { // Select encoding strategy for unknown header names Entry name = _context.get(field.getName()); if (field instanceof PreEncodedHttpField) { - int i=buffer.position(); - ((PreEncodedHttpField)field).putTo(buffer,HttpVersion.HTTP_2); - byte b=buffer.get(i); - indexed=b<0||b>=0x40; + int i = buffer.position(); + ((PreEncodedHttpField)field).putTo(buffer, HttpVersion.HTTP_2); + byte b = buffer.get(i); + indexed = b < 0 || b >= 0x40; if (_debug) - encoding=indexed?"PreEncodedIdx":"PreEncoded"; + encoding = indexed ? "PreEncodedIdx" : "PreEncoded"; } // has the custom header name been seen before? - else if (name==null) + else if (name == null) { // unknown name and value, so let's index this just in case it is // the first time we have seen a custom name or a custom field. // unless the name is changing, this is worthwhile - indexed=true; - encodeName(buffer,(byte)0x40,6,field.getName(),null); - encodeValue(buffer,true,field.getValue()); + indexed = true; + encodeName(buffer, (byte)0x40, 6, field.getName(), null); + encodeValue(buffer, true, field.getValue()); if (_debug) - encoding="LitHuffNHuffVIdx"; + encoding = "LitHuffNHuffVIdx"; } else { // known custom name, but unknown value. // This is probably a custom field with changing value, so don't index. - indexed=false; - encodeName(buffer,(byte)0x00,4,field.getName(),null); - encodeValue(buffer,true,field.getValue()); + indexed = false; + encodeName(buffer, (byte)0x00, 4, field.getName(), null); + encodeValue(buffer, true, field.getValue()); if (_debug) - encoding="LitHuffNHuffV!Idx"; + encoding = "LitHuffNHuffV!Idx"; } } else @@ -311,47 +312,47 @@ public class HpackEncoder if (field instanceof PreEncodedHttpField) { // Preencoded field - int i=buffer.position(); - ((PreEncodedHttpField)field).putTo(buffer,HttpVersion.HTTP_2); - byte b=buffer.get(i); - indexed=b<0||b>=0x40; + int i = buffer.position(); + ((PreEncodedHttpField)field).putTo(buffer, HttpVersion.HTTP_2); + byte b = buffer.get(i); + indexed = b < 0 || b >= 0x40; if (_debug) - encoding=indexed?"PreEncodedIdx":"PreEncoded"; + encoding = indexed ? "PreEncodedIdx" : "PreEncoded"; } else if (__DO_NOT_INDEX.contains(header)) { // Non indexed field - indexed=false; - boolean never_index=__NEVER_INDEX.contains(header); - boolean huffman=!__DO_NOT_HUFFMAN.contains(header); - encodeName(buffer,never_index?(byte)0x10:(byte)0x00,4,header.asString(),name); - encodeValue(buffer,huffman,field.getValue()); + indexed = false; + boolean neverIndex = __NEVER_INDEX.contains(header); + boolean huffman = !__DO_NOT_HUFFMAN.contains(header); + encodeName(buffer, neverIndex ? (byte)0x10 : (byte)0x00, 4, header.asString(), name); + encodeValue(buffer, huffman, field.getValue()); if (_debug) - encoding="Lit"+ - ((name==null)?"HuffN":("IdxN"+(name.isStatic()?"S":"")+(1+NBitInteger.octectsNeeded(4,_context.index(name)))))+ - (huffman?"HuffV":"LitV")+ - (never_index?"!!Idx":"!Idx"); + encoding = "Lit" + + ((name == null) ? "HuffN" : ("IdxN" + (name.isStatic() ? "S" : "") + (1 + NBitInteger.octectsNeeded(4, _context.index(name))))) + + (huffman ? "HuffV" : "LitV") + + (neverIndex ? "!!Idx" : "!Idx"); } - else if (field_size>=_context.getMaxDynamicTableSize() || header==HttpHeader.CONTENT_LENGTH && field.getValue().length()>2) + else if (fieldSize >= _context.getMaxDynamicTableSize() || header == HttpHeader.CONTENT_LENGTH && field.getValue().length() > 2) { // Non indexed if field too large or a content length for 3 digits or more - indexed=false; - encodeName(buffer,(byte)0x00,4,header.asString(),name); - encodeValue(buffer,true,field.getValue()); + indexed = false; + encodeName(buffer, (byte)0x00, 4, header.asString(), name); + encodeValue(buffer, true, field.getValue()); if (_debug) - encoding="LitIdxNS"+(1+NBitInteger.octectsNeeded(4,_context.index(name)))+"HuffV!Idx"; + encoding = "LitIdxNS" + (1 + NBitInteger.octectsNeeded(4, _context.index(name))) + "HuffV!Idx"; } else { // indexed - indexed=true; - boolean huffman=!__DO_NOT_HUFFMAN.contains(header); - encodeName(buffer,(byte)0x40,6,header.asString(),name); - encodeValue(buffer,huffman,field.getValue()); + indexed = true; + boolean huffman = !__DO_NOT_HUFFMAN.contains(header); + encodeName(buffer, (byte)0x40, 6, header.asString(), name); + encodeValue(buffer, huffman, field.getValue()); if (_debug) - encoding=((name==null)?"LitHuffN":("LitIdxN"+(name.isStatic()?"S":"")+(1+NBitInteger.octectsNeeded(6,_context.index(name)))))+ - (huffman?"HuffVIdx":"LitVIdx"); + encoding = ((name == null) ? "LitHuffN" : ("LitIdxN" + (name.isStatic() ? "S" : "") + (1 + NBitInteger.octectsNeeded(6, _context.index(name))))) + + (huffman ? "HuffVIdx" : "LitVIdx"); } } @@ -362,26 +363,26 @@ public class HpackEncoder if (_debug) { - int e=buffer.position(); + int e = buffer.position(); if (LOG.isDebugEnabled()) - LOG.debug("encode {}:'{}' to '{}'",encoding,field,TypeUtil.toHexString(buffer.array(),buffer.arrayOffset()+p,e-p)); + LOG.debug("encode {}:'{}' to '{}'", encoding, field, TypeUtil.toHexString(buffer.array(), buffer.arrayOffset() + p, e - p)); } } private void encodeName(ByteBuffer buffer, byte mask, int bits, String name, Entry entry) { buffer.put(mask); - if (entry==null) + if (entry == null) { // leave name index bits as 0 // Encode the name always with lowercase huffman buffer.put((byte)0x80); - NBitInteger.encode(buffer,7,Huffman.octetsNeededLC(name)); - Huffman.encodeLC(buffer,name); + NBitInteger.encode(buffer, 7, Huffman.octetsNeededLC(name)); + Huffman.encodeLC(buffer, name); } else { - NBitInteger.encode(buffer,bits,_context.index(entry)); + NBitInteger.encode(buffer, bits, _context.index(entry)); } } @@ -391,18 +392,18 @@ public class HpackEncoder { // huffman literal value buffer.put((byte)0x80); - NBitInteger.encode(buffer,7,Huffman.octetsNeeded(value)); - Huffman.encode(buffer,value); + NBitInteger.encode(buffer, 7, Huffman.octetsNeeded(value)); + Huffman.encode(buffer, value); } else { // add literal assuming iso_8859_1 buffer.put((byte)0x00); - NBitInteger.encode(buffer,7,value.length()); - for (int i=0;i127) + char c = value.charAt(i); + if (c < ' ' || c > 127) throw new IllegalArgumentException(); buffer.put((byte)c); } diff --git a/jetty-http2/http2-hpack/src/main/java/org/eclipse/jetty/http2/hpack/HpackException.java b/jetty-http2/http2-hpack/src/main/java/org/eclipse/jetty/http2/hpack/HpackException.java index d1fc70fce3a..0a3e254b514 100644 --- a/jetty-http2/http2-hpack/src/main/java/org/eclipse/jetty/http2/hpack/HpackException.java +++ b/jetty-http2/http2-hpack/src/main/java/org/eclipse/jetty/http2/hpack/HpackException.java @@ -18,7 +18,6 @@ package org.eclipse.jetty.http2.hpack; - @SuppressWarnings("serial") public abstract class HpackException extends Exception { @@ -26,19 +25,19 @@ public abstract class HpackException extends Exception { super(String.format(messageFormat, args)); } - + /** * A Stream HPACK exception. - *

      Stream exceptions are not fatal to the connection and the + *

      Stream exceptions are not fatal to the connection and the * hpack state is complete and able to continue handling other - * decoding/encoding for the session. + * decoding/encoding for the session. *

      */ public static class StreamException extends HpackException { StreamException(String messageFormat, Object... args) { - super(messageFormat,args); + super(messageFormat, args); } } @@ -51,7 +50,7 @@ public abstract class HpackException extends Exception { SessionException(String messageFormat, Object... args) { - super(messageFormat,args); + super(messageFormat, args); } } @@ -59,7 +58,7 @@ public abstract class HpackException extends Exception { public CompressionException(String messageFormat, Object... args) { - super(messageFormat,args); + super(messageFormat, args); } } } diff --git a/jetty-http2/http2-hpack/src/main/java/org/eclipse/jetty/http2/hpack/HpackFieldPreEncoder.java b/jetty-http2/http2-hpack/src/main/java/org/eclipse/jetty/http2/hpack/HpackFieldPreEncoder.java index a369897d906..2b3d30dc345 100644 --- a/jetty-http2/http2-hpack/src/main/java/org/eclipse/jetty/http2/hpack/HpackFieldPreEncoder.java +++ b/jetty-http2/http2-hpack/src/main/java/org/eclipse/jetty/http2/hpack/HpackFieldPreEncoder.java @@ -16,7 +16,6 @@ // ======================================================================== // - package org.eclipse.jetty.http2.hpack; import java.nio.ByteBuffer; @@ -26,13 +25,12 @@ import org.eclipse.jetty.http.HttpHeader; import org.eclipse.jetty.http.HttpVersion; import org.eclipse.jetty.util.BufferUtil; - -/* ------------------------------------------------------------ */ /** + * */ public class HpackFieldPreEncoder implements HttpFieldPreEncoder { - /* ------------------------------------------------------------ */ + /** * @see org.eclipse.jetty.http.HttpFieldPreEncoder#getHttpVersion() */ @@ -42,56 +40,55 @@ public class HpackFieldPreEncoder implements HttpFieldPreEncoder return HttpVersion.HTTP_2; } - /* ------------------------------------------------------------ */ /** * @see org.eclipse.jetty.http.HttpFieldPreEncoder#getEncodedField(org.eclipse.jetty.http.HttpHeader, java.lang.String, java.lang.String) */ @Override public byte[] getEncodedField(HttpHeader header, String name, String value) { - boolean not_indexed=HpackEncoder.__DO_NOT_INDEX.contains(header); - - ByteBuffer buffer = BufferUtil.allocate(name.length()+value.length()+10); + boolean notIndexed = HpackEncoder.__DO_NOT_INDEX.contains(header); + + ByteBuffer buffer = BufferUtil.allocate(name.length() + value.length() + 10); BufferUtil.clearToFill(buffer); boolean huffman; int bits; - - if (not_indexed) + + if (notIndexed) { // Non indexed field - boolean never_index=HpackEncoder.__NEVER_INDEX.contains(header); - huffman=!HpackEncoder.__DO_NOT_HUFFMAN.contains(header); - buffer.put(never_index?(byte)0x10:(byte)0x00); - bits=4; + boolean neverIndex = HpackEncoder.__NEVER_INDEX.contains(header); + huffman = !HpackEncoder.__DO_NOT_HUFFMAN.contains(header); + buffer.put(neverIndex ? (byte)0x10 : (byte)0x00); + bits = 4; } - else if (header==HttpHeader.CONTENT_LENGTH && value.length()>1) + else if (header == HttpHeader.CONTENT_LENGTH && value.length() > 1) { // Non indexed content length for 2 digits or more buffer.put((byte)0x00); - huffman=true; - bits=4; + huffman = true; + bits = 4; } else { // indexed buffer.put((byte)0x40); - huffman=!HpackEncoder.__DO_NOT_HUFFMAN.contains(header); - bits=6; + huffman = !HpackEncoder.__DO_NOT_HUFFMAN.contains(header); + bits = 6; } - - int name_idx=HpackContext.staticIndex(header); - if (name_idx>0) - NBitInteger.encode(buffer,bits,name_idx); + + int nameIdx = HpackContext.staticIndex(header); + if (nameIdx > 0) + NBitInteger.encode(buffer, bits, nameIdx); else { buffer.put((byte)0x80); - NBitInteger.encode(buffer,7,Huffman.octetsNeededLC(name)); - Huffman.encodeLC(buffer,name); + NBitInteger.encode(buffer, 7, Huffman.octetsNeededLC(name)); + Huffman.encodeLC(buffer, name); } - HpackEncoder.encodeValue(buffer,huffman,value); - - BufferUtil.flipToFlush(buffer,0); + HpackEncoder.encodeValue(buffer, huffman, value); + + BufferUtil.flipToFlush(buffer, 0); return BufferUtil.toArray(buffer); } } diff --git a/jetty-http2/http2-hpack/src/main/java/org/eclipse/jetty/http2/hpack/Huffman.java b/jetty-http2/http2-hpack/src/main/java/org/eclipse/jetty/http2/hpack/Huffman.java index c45f40ec5e6..38aff6f8d68 100644 --- a/jetty-http2/http2-hpack/src/main/java/org/eclipse/jetty/http2/hpack/Huffman.java +++ b/jetty-http2/http2-hpack/src/main/java/org/eclipse/jetty/http2/hpack/Huffman.java @@ -26,269 +26,269 @@ public class Huffman // Appendix C: Huffman Codes // http://tools.ietf.org/html/draft-ietf-httpbis-header-compression-12#appendix-C static final int[][] CODES = - { - /* ( 0) |11111111|11000 */ {0x1ff8,13}, - /* ( 1) |11111111|11111111|1011000 */ {0x7fffd8,23}, - /* ( 2) |11111111|11111111|11111110|0010 */ {0xfffffe2,28}, - /* ( 3) |11111111|11111111|11111110|0011 */ {0xfffffe3,28}, - /* ( 4) |11111111|11111111|11111110|0100 */ {0xfffffe4,28}, - /* ( 5) |11111111|11111111|11111110|0101 */ {0xfffffe5,28}, - /* ( 6) |11111111|11111111|11111110|0110 */ {0xfffffe6,28}, - /* ( 7) |11111111|11111111|11111110|0111 */ {0xfffffe7,28}, - /* ( 8) |11111111|11111111|11111110|1000 */ {0xfffffe8,28}, - /* ( 9) |11111111|11111111|11101010 */ {0xffffea,24}, - /* ( 10) |11111111|11111111|11111111|111100 */ {0x3ffffffc,30}, - /* ( 11) |11111111|11111111|11111110|1001 */ {0xfffffe9,28}, - /* ( 12) |11111111|11111111|11111110|1010 */ {0xfffffea,28}, - /* ( 13) |11111111|11111111|11111111|111101 */ {0x3ffffffd,30}, - /* ( 14) |11111111|11111111|11111110|1011 */ {0xfffffeb,28}, - /* ( 15) |11111111|11111111|11111110|1100 */ {0xfffffec,28}, - /* ( 16) |11111111|11111111|11111110|1101 */ {0xfffffed,28}, - /* ( 17) |11111111|11111111|11111110|1110 */ {0xfffffee,28}, - /* ( 18) |11111111|11111111|11111110|1111 */ {0xfffffef,28}, - /* ( 19) |11111111|11111111|11111111|0000 */ {0xffffff0,28}, - /* ( 20) |11111111|11111111|11111111|0001 */ {0xffffff1,28}, - /* ( 21) |11111111|11111111|11111111|0010 */ {0xffffff2,28}, - /* ( 22) |11111111|11111111|11111111|111110 */ {0x3ffffffe,30}, - /* ( 23) |11111111|11111111|11111111|0011 */ {0xffffff3,28}, - /* ( 24) |11111111|11111111|11111111|0100 */ {0xffffff4,28}, - /* ( 25) |11111111|11111111|11111111|0101 */ {0xffffff5,28}, - /* ( 26) |11111111|11111111|11111111|0110 */ {0xffffff6,28}, - /* ( 27) |11111111|11111111|11111111|0111 */ {0xffffff7,28}, - /* ( 28) |11111111|11111111|11111111|1000 */ {0xffffff8,28}, - /* ( 29) |11111111|11111111|11111111|1001 */ {0xffffff9,28}, - /* ( 30) |11111111|11111111|11111111|1010 */ {0xffffffa,28}, - /* ( 31) |11111111|11111111|11111111|1011 */ {0xffffffb,28}, - /*' ' ( 32) |010100 */ {0x14, 6}, - /*'!' ( 33) |11111110|00 */ {0x3f8,10}, - /*'"' ( 34) |11111110|01 */ {0x3f9,10}, - /*'#' ( 35) |11111111|1010 */ {0xffa,12}, - /*'$' ( 36) |11111111|11001 */ {0x1ff9,13}, - /*'%' ( 37) |010101 */ {0x15, 6}, - /*'&' ( 38) |11111000 */ {0xf8, 8}, - /*''' ( 39) |11111111|010 */ {0x7fa,11}, - /*'(' ( 40) |11111110|10 */ {0x3fa,10}, - /*')' ( 41) |11111110|11 */ {0x3fb,10}, - /*'*' ( 42) |11111001 */ {0xf9, 8}, - /*'+' ( 43) |11111111|011 */ {0x7fb,11}, - /*',' ( 44) |11111010 */ {0xfa, 8}, - /*'-' ( 45) |010110 */ {0x16, 6}, - /*'.' ( 46) |010111 */ {0x17, 6}, - /*'/' ( 47) |011000 */ {0x18, 6}, - /*'0' ( 48) |00000 */ {0x0, 5}, - /*'1' ( 49) |00001 */ {0x1, 5}, - /*'2' ( 50) |00010 */ {0x2, 5}, - /*'3' ( 51) |011001 */ {0x19, 6}, - /*'4' ( 52) |011010 */ {0x1a, 6}, - /*'5' ( 53) |011011 */ {0x1b, 6}, - /*'6' ( 54) |011100 */ {0x1c, 6}, - /*'7' ( 55) |011101 */ {0x1d, 6}, - /*'8' ( 56) |011110 */ {0x1e, 6}, - /*'9' ( 57) |011111 */ {0x1f, 6}, - /*':' ( 58) |1011100 */ {0x5c, 7}, - /*';' ( 59) |11111011 */ {0xfb, 8}, - /*'<' ( 60) |11111111|1111100 */ {0x7ffc,15}, - /*'=' ( 61) |100000 */ {0x20, 6}, - /*'>' ( 62) |11111111|1011 */ {0xffb,12}, - /*'?' ( 63) |11111111|00 */ {0x3fc,10}, - /*'@' ( 64) |11111111|11010 */ {0x1ffa,13}, - /*'A' ( 65) |100001 */ {0x21, 6}, - /*'B' ( 66) |1011101 */ {0x5d, 7}, - /*'C' ( 67) |1011110 */ {0x5e, 7}, - /*'D' ( 68) |1011111 */ {0x5f, 7}, - /*'E' ( 69) |1100000 */ {0x60, 7}, - /*'F' ( 70) |1100001 */ {0x61, 7}, - /*'G' ( 71) |1100010 */ {0x62, 7}, - /*'H' ( 72) |1100011 */ {0x63, 7}, - /*'I' ( 73) |1100100 */ {0x64, 7}, - /*'J' ( 74) |1100101 */ {0x65, 7}, - /*'K' ( 75) |1100110 */ {0x66, 7}, - /*'L' ( 76) |1100111 */ {0x67, 7}, - /*'M' ( 77) |1101000 */ {0x68, 7}, - /*'N' ( 78) |1101001 */ {0x69, 7}, - /*'O' ( 79) |1101010 */ {0x6a, 7}, - /*'P' ( 80) |1101011 */ {0x6b, 7}, - /*'Q' ( 81) |1101100 */ {0x6c, 7}, - /*'R' ( 82) |1101101 */ {0x6d, 7}, - /*'S' ( 83) |1101110 */ {0x6e, 7}, - /*'T' ( 84) |1101111 */ {0x6f, 7}, - /*'U' ( 85) |1110000 */ {0x70, 7}, - /*'V' ( 86) |1110001 */ {0x71, 7}, - /*'W' ( 87) |1110010 */ {0x72, 7}, - /*'X' ( 88) |11111100 */ {0xfc, 8}, - /*'Y' ( 89) |1110011 */ {0x73, 7}, - /*'Z' ( 90) |11111101 */ {0xfd, 8}, - /*'[' ( 91) |11111111|11011 */ {0x1ffb,13}, - /*'\' ( 92) |11111111|11111110|000 */ {0x7fff0,19}, - /*']' ( 93) |11111111|11100 */ {0x1ffc,13}, - /*'^' ( 94) |11111111|111100 */ {0x3ffc,14}, - /*'_' ( 95) |100010 */ {0x22, 6}, - /*'`' ( 96) |11111111|1111101 */ {0x7ffd,15}, - /*'a' ( 97) |00011 */ {0x3, 5}, - /*'b' ( 98) |100011 */ {0x23, 6}, - /*'c' ( 99) |00100 */ {0x4, 5}, - /*'d' (100) |100100 */ {0x24, 6}, - /*'e' (101) |00101 */ {0x5, 5}, - /*'f' (102) |100101 */ {0x25, 6}, - /*'g' (103) |100110 */ {0x26, 6}, - /*'h' (104) |100111 */ {0x27, 6}, - /*'i' (105) |00110 */ {0x6, 5}, - /*'j' (106) |1110100 */ {0x74, 7}, - /*'k' (107) |1110101 */ {0x75, 7}, - /*'l' (108) |101000 */ {0x28, 6}, - /*'m' (109) |101001 */ {0x29, 6}, - /*'n' (110) |101010 */ {0x2a, 6}, - /*'o' (111) |00111 */ {0x7, 5}, - /*'p' (112) |101011 */ {0x2b, 6}, - /*'q' (113) |1110110 */ {0x76, 7}, - /*'r' (114) |101100 */ {0x2c, 6}, - /*'s' (115) |01000 */ {0x8, 5}, - /*'t' (116) |01001 */ {0x9, 5}, - /*'u' (117) |101101 */ {0x2d, 6}, - /*'v' (118) |1110111 */ {0x77, 7}, - /*'w' (119) |1111000 */ {0x78, 7}, - /*'x' (120) |1111001 */ {0x79, 7}, - /*'y' (121) |1111010 */ {0x7a, 7}, - /*'z' (122) |1111011 */ {0x7b, 7}, - /*'{' (123) |11111111|1111110 */ {0x7ffe,15}, - /*'|' (124) |11111111|100 */ {0x7fc,11}, - /*'}' (125) |11111111|111101 */ {0x3ffd,14}, - /*'~' (126) |11111111|11101 */ {0x1ffd,13}, - /* (127) |11111111|11111111|11111111|1100 */ {0xffffffc,28}, - /* (128) |11111111|11111110|0110 */ {0xfffe6,20}, - /* (129) |11111111|11111111|010010 */ {0x3fffd2,22}, - /* (130) |11111111|11111110|0111 */ {0xfffe7,20}, - /* (131) |11111111|11111110|1000 */ {0xfffe8,20}, - /* (132) |11111111|11111111|010011 */ {0x3fffd3,22}, - /* (133) |11111111|11111111|010100 */ {0x3fffd4,22}, - /* (134) |11111111|11111111|010101 */ {0x3fffd5,22}, - /* (135) |11111111|11111111|1011001 */ {0x7fffd9,23}, - /* (136) |11111111|11111111|010110 */ {0x3fffd6,22}, - /* (137) |11111111|11111111|1011010 */ {0x7fffda,23}, - /* (138) |11111111|11111111|1011011 */ {0x7fffdb,23}, - /* (139) |11111111|11111111|1011100 */ {0x7fffdc,23}, - /* (140) |11111111|11111111|1011101 */ {0x7fffdd,23}, - /* (141) |11111111|11111111|1011110 */ {0x7fffde,23}, - /* (142) |11111111|11111111|11101011 */ {0xffffeb,24}, - /* (143) |11111111|11111111|1011111 */ {0x7fffdf,23}, - /* (144) |11111111|11111111|11101100 */ {0xffffec,24}, - /* (145) |11111111|11111111|11101101 */ {0xffffed,24}, - /* (146) |11111111|11111111|010111 */ {0x3fffd7,22}, - /* (147) |11111111|11111111|1100000 */ {0x7fffe0,23}, - /* (148) |11111111|11111111|11101110 */ {0xffffee,24}, - /* (149) |11111111|11111111|1100001 */ {0x7fffe1,23}, - /* (150) |11111111|11111111|1100010 */ {0x7fffe2,23}, - /* (151) |11111111|11111111|1100011 */ {0x7fffe3,23}, - /* (152) |11111111|11111111|1100100 */ {0x7fffe4,23}, - /* (153) |11111111|11111110|11100 */ {0x1fffdc,21}, - /* (154) |11111111|11111111|011000 */ {0x3fffd8,22}, - /* (155) |11111111|11111111|1100101 */ {0x7fffe5,23}, - /* (156) |11111111|11111111|011001 */ {0x3fffd9,22}, - /* (157) |11111111|11111111|1100110 */ {0x7fffe6,23}, - /* (158) |11111111|11111111|1100111 */ {0x7fffe7,23}, - /* (159) |11111111|11111111|11101111 */ {0xffffef,24}, - /* (160) |11111111|11111111|011010 */ {0x3fffda,22}, - /* (161) |11111111|11111110|11101 */ {0x1fffdd,21}, - /* (162) |11111111|11111110|1001 */ {0xfffe9,20}, - /* (163) |11111111|11111111|011011 */ {0x3fffdb,22}, - /* (164) |11111111|11111111|011100 */ {0x3fffdc,22}, - /* (165) |11111111|11111111|1101000 */ {0x7fffe8,23}, - /* (166) |11111111|11111111|1101001 */ {0x7fffe9,23}, - /* (167) |11111111|11111110|11110 */ {0x1fffde,21}, - /* (168) |11111111|11111111|1101010 */ {0x7fffea,23}, - /* (169) |11111111|11111111|011101 */ {0x3fffdd,22}, - /* (170) |11111111|11111111|011110 */ {0x3fffde,22}, - /* (171) |11111111|11111111|11110000 */ {0xfffff0,24}, - /* (172) |11111111|11111110|11111 */ {0x1fffdf,21}, - /* (173) |11111111|11111111|011111 */ {0x3fffdf,22}, - /* (174) |11111111|11111111|1101011 */ {0x7fffeb,23}, - /* (175) |11111111|11111111|1101100 */ {0x7fffec,23}, - /* (176) |11111111|11111111|00000 */ {0x1fffe0,21}, - /* (177) |11111111|11111111|00001 */ {0x1fffe1,21}, - /* (178) |11111111|11111111|100000 */ {0x3fffe0,22}, - /* (179) |11111111|11111111|00010 */ {0x1fffe2,21}, - /* (180) |11111111|11111111|1101101 */ {0x7fffed,23}, - /* (181) |11111111|11111111|100001 */ {0x3fffe1,22}, - /* (182) |11111111|11111111|1101110 */ {0x7fffee,23}, - /* (183) |11111111|11111111|1101111 */ {0x7fffef,23}, - /* (184) |11111111|11111110|1010 */ {0xfffea,20}, - /* (185) |11111111|11111111|100010 */ {0x3fffe2,22}, - /* (186) |11111111|11111111|100011 */ {0x3fffe3,22}, - /* (187) |11111111|11111111|100100 */ {0x3fffe4,22}, - /* (188) |11111111|11111111|1110000 */ {0x7ffff0,23}, - /* (189) |11111111|11111111|100101 */ {0x3fffe5,22}, - /* (190) |11111111|11111111|100110 */ {0x3fffe6,22}, - /* (191) |11111111|11111111|1110001 */ {0x7ffff1,23}, - /* (192) |11111111|11111111|11111000|00 */ {0x3ffffe0,26}, - /* (193) |11111111|11111111|11111000|01 */ {0x3ffffe1,26}, - /* (194) |11111111|11111110|1011 */ {0xfffeb,20}, - /* (195) |11111111|11111110|001 */ {0x7fff1,19}, - /* (196) |11111111|11111111|100111 */ {0x3fffe7,22}, - /* (197) |11111111|11111111|1110010 */ {0x7ffff2,23}, - /* (198) |11111111|11111111|101000 */ {0x3fffe8,22}, - /* (199) |11111111|11111111|11110110|0 */ {0x1ffffec,25}, - /* (200) |11111111|11111111|11111000|10 */ {0x3ffffe2,26}, - /* (201) |11111111|11111111|11111000|11 */ {0x3ffffe3,26}, - /* (202) |11111111|11111111|11111001|00 */ {0x3ffffe4,26}, - /* (203) |11111111|11111111|11111011|110 */ {0x7ffffde,27}, - /* (204) |11111111|11111111|11111011|111 */ {0x7ffffdf,27}, - /* (205) |11111111|11111111|11111001|01 */ {0x3ffffe5,26}, - /* (206) |11111111|11111111|11110001 */ {0xfffff1,24}, - /* (207) |11111111|11111111|11110110|1 */ {0x1ffffed,25}, - /* (208) |11111111|11111110|010 */ {0x7fff2,19}, - /* (209) |11111111|11111111|00011 */ {0x1fffe3,21}, - /* (210) |11111111|11111111|11111001|10 */ {0x3ffffe6,26}, - /* (211) |11111111|11111111|11111100|000 */ {0x7ffffe0,27}, - /* (212) |11111111|11111111|11111100|001 */ {0x7ffffe1,27}, - /* (213) |11111111|11111111|11111001|11 */ {0x3ffffe7,26}, - /* (214) |11111111|11111111|11111100|010 */ {0x7ffffe2,27}, - /* (215) |11111111|11111111|11110010 */ {0xfffff2,24}, - /* (216) |11111111|11111111|00100 */ {0x1fffe4,21}, - /* (217) |11111111|11111111|00101 */ {0x1fffe5,21}, - /* (218) |11111111|11111111|11111010|00 */ {0x3ffffe8,26}, - /* (219) |11111111|11111111|11111010|01 */ {0x3ffffe9,26}, - /* (220) |11111111|11111111|11111111|1101 */ {0xffffffd,28}, - /* (221) |11111111|11111111|11111100|011 */ {0x7ffffe3,27}, - /* (222) |11111111|11111111|11111100|100 */ {0x7ffffe4,27}, - /* (223) |11111111|11111111|11111100|101 */ {0x7ffffe5,27}, - /* (224) |11111111|11111110|1100 */ {0xfffec,20}, - /* (225) |11111111|11111111|11110011 */ {0xfffff3,24}, - /* (226) |11111111|11111110|1101 */ {0xfffed,20}, - /* (227) |11111111|11111111|00110 */ {0x1fffe6,21}, - /* (228) |11111111|11111111|101001 */ {0x3fffe9,22}, - /* (229) |11111111|11111111|00111 */ {0x1fffe7,21}, - /* (230) |11111111|11111111|01000 */ {0x1fffe8,21}, - /* (231) |11111111|11111111|1110011 */ {0x7ffff3,23}, - /* (232) |11111111|11111111|101010 */ {0x3fffea,22}, - /* (233) |11111111|11111111|101011 */ {0x3fffeb,22}, - /* (234) |11111111|11111111|11110111|0 */ {0x1ffffee,25}, - /* (235) |11111111|11111111|11110111|1 */ {0x1ffffef,25}, - /* (236) |11111111|11111111|11110100 */ {0xfffff4,24}, - /* (237) |11111111|11111111|11110101 */ {0xfffff5,24}, - /* (238) |11111111|11111111|11111010|10 */ {0x3ffffea,26}, - /* (239) |11111111|11111111|1110100 */ {0x7ffff4,23}, - /* (240) |11111111|11111111|11111010|11 */ {0x3ffffeb,26}, - /* (241) |11111111|11111111|11111100|110 */ {0x7ffffe6,27}, - /* (242) |11111111|11111111|11111011|00 */ {0x3ffffec,26}, - /* (243) |11111111|11111111|11111011|01 */ {0x3ffffed,26}, - /* (244) |11111111|11111111|11111100|111 */ {0x7ffffe7,27}, - /* (245) |11111111|11111111|11111101|000 */ {0x7ffffe8,27}, - /* (246) |11111111|11111111|11111101|001 */ {0x7ffffe9,27}, - /* (247) |11111111|11111111|11111101|010 */ {0x7ffffea,27}, - /* (248) |11111111|11111111|11111101|011 */ {0x7ffffeb,27}, - /* (249) |11111111|11111111|11111111|1110 */ {0xffffffe,28}, - /* (250) |11111111|11111111|11111101|100 */ {0x7ffffec,27}, - /* (251) |11111111|11111111|11111101|101 */ {0x7ffffed,27}, - /* (252) |11111111|11111111|11111101|110 */ {0x7ffffee,27}, - /* (253) |11111111|11111111|11111101|111 */ {0x7ffffef,27}, - /* (254) |11111111|11111111|11111110|000 */ {0x7fffff0,27}, - /* (255) |11111111|11111111|11111011|10 */ {0x3ffffee,26}, - /*EOS (256) |11111111|11111111|11111111|111111 */ {0x3fffffff,30}, - }; + { + /* ( 0) |11111111|11000 */ {0x1ff8, 13}, + /* ( 1) |11111111|11111111|1011000 */ {0x7fffd8, 23}, + /* ( 2) |11111111|11111111|11111110|0010 */ {0xfffffe2, 28}, + /* ( 3) |11111111|11111111|11111110|0011 */ {0xfffffe3, 28}, + /* ( 4) |11111111|11111111|11111110|0100 */ {0xfffffe4, 28}, + /* ( 5) |11111111|11111111|11111110|0101 */ {0xfffffe5, 28}, + /* ( 6) |11111111|11111111|11111110|0110 */ {0xfffffe6, 28}, + /* ( 7) |11111111|11111111|11111110|0111 */ {0xfffffe7, 28}, + /* ( 8) |11111111|11111111|11111110|1000 */ {0xfffffe8, 28}, + /* ( 9) |11111111|11111111|11101010 */ {0xffffea, 24}, + /* ( 10) |11111111|11111111|11111111|111100 */ {0x3ffffffc, 30}, + /* ( 11) |11111111|11111111|11111110|1001 */ {0xfffffe9, 28}, + /* ( 12) |11111111|11111111|11111110|1010 */ {0xfffffea, 28}, + /* ( 13) |11111111|11111111|11111111|111101 */ {0x3ffffffd, 30}, + /* ( 14) |11111111|11111111|11111110|1011 */ {0xfffffeb, 28}, + /* ( 15) |11111111|11111111|11111110|1100 */ {0xfffffec, 28}, + /* ( 16) |11111111|11111111|11111110|1101 */ {0xfffffed, 28}, + /* ( 17) |11111111|11111111|11111110|1110 */ {0xfffffee, 28}, + /* ( 18) |11111111|11111111|11111110|1111 */ {0xfffffef, 28}, + /* ( 19) |11111111|11111111|11111111|0000 */ {0xffffff0, 28}, + /* ( 20) |11111111|11111111|11111111|0001 */ {0xffffff1, 28}, + /* ( 21) |11111111|11111111|11111111|0010 */ {0xffffff2, 28}, + /* ( 22) |11111111|11111111|11111111|111110 */ {0x3ffffffe, 30}, + /* ( 23) |11111111|11111111|11111111|0011 */ {0xffffff3, 28}, + /* ( 24) |11111111|11111111|11111111|0100 */ {0xffffff4, 28}, + /* ( 25) |11111111|11111111|11111111|0101 */ {0xffffff5, 28}, + /* ( 26) |11111111|11111111|11111111|0110 */ {0xffffff6, 28}, + /* ( 27) |11111111|11111111|11111111|0111 */ {0xffffff7, 28}, + /* ( 28) |11111111|11111111|11111111|1000 */ {0xffffff8, 28}, + /* ( 29) |11111111|11111111|11111111|1001 */ {0xffffff9, 28}, + /* ( 30) |11111111|11111111|11111111|1010 */ {0xffffffa, 28}, + /* ( 31) |11111111|11111111|11111111|1011 */ {0xffffffb, 28}, + /*' ' ( 32) |010100 */ {0x14, 6}, + /*'!' ( 33) |11111110|00 */ {0x3f8, 10}, + /*'"' ( 34) |11111110|01 */ {0x3f9, 10}, + /*'#' ( 35) |11111111|1010 */ {0xffa, 12}, + /*'$' ( 36) |11111111|11001 */ {0x1ff9, 13}, + /*'%' ( 37) |010101 */ {0x15, 6}, + /*'&' ( 38) |11111000 */ {0xf8, 8}, + /*''' ( 39) |11111111|010 */ {0x7fa, 11}, + /*'(' ( 40) |11111110|10 */ {0x3fa, 10}, + /*')' ( 41) |11111110|11 */ {0x3fb, 10}, + /*'*' ( 42) |11111001 */ {0xf9, 8}, + /*'+' ( 43) |11111111|011 */ {0x7fb, 11}, + /*',' ( 44) |11111010 */ {0xfa, 8}, + /*'-' ( 45) |010110 */ {0x16, 6}, + /*'.' ( 46) |010111 */ {0x17, 6}, + /*'/' ( 47) |011000 */ {0x18, 6}, + /*'0' ( 48) |00000 */ {0x0, 5}, + /*'1' ( 49) |00001 */ {0x1, 5}, + /*'2' ( 50) |00010 */ {0x2, 5}, + /*'3' ( 51) |011001 */ {0x19, 6}, + /*'4' ( 52) |011010 */ {0x1a, 6}, + /*'5' ( 53) |011011 */ {0x1b, 6}, + /*'6' ( 54) |011100 */ {0x1c, 6}, + /*'7' ( 55) |011101 */ {0x1d, 6}, + /*'8' ( 56) |011110 */ {0x1e, 6}, + /*'9' ( 57) |011111 */ {0x1f, 6}, + /*':' ( 58) |1011100 */ {0x5c, 7}, + /*';' ( 59) |11111011 */ {0xfb, 8}, + /*'<' ( 60) |11111111|1111100 */ {0x7ffc, 15}, + /*'=' ( 61) |100000 */ {0x20, 6}, + /*'>' ( 62) |11111111|1011 */ {0xffb, 12}, + /*'?' ( 63) |11111111|00 */ {0x3fc, 10}, + /*'@' ( 64) |11111111|11010 */ {0x1ffa, 13}, + /*'A' ( 65) |100001 */ {0x21, 6}, + /*'B' ( 66) |1011101 */ {0x5d, 7}, + /*'C' ( 67) |1011110 */ {0x5e, 7}, + /*'D' ( 68) |1011111 */ {0x5f, 7}, + /*'E' ( 69) |1100000 */ {0x60, 7}, + /*'F' ( 70) |1100001 */ {0x61, 7}, + /*'G' ( 71) |1100010 */ {0x62, 7}, + /*'H' ( 72) |1100011 */ {0x63, 7}, + /*'I' ( 73) |1100100 */ {0x64, 7}, + /*'J' ( 74) |1100101 */ {0x65, 7}, + /*'K' ( 75) |1100110 */ {0x66, 7}, + /*'L' ( 76) |1100111 */ {0x67, 7}, + /*'M' ( 77) |1101000 */ {0x68, 7}, + /*'N' ( 78) |1101001 */ {0x69, 7}, + /*'O' ( 79) |1101010 */ {0x6a, 7}, + /*'P' ( 80) |1101011 */ {0x6b, 7}, + /*'Q' ( 81) |1101100 */ {0x6c, 7}, + /*'R' ( 82) |1101101 */ {0x6d, 7}, + /*'S' ( 83) |1101110 */ {0x6e, 7}, + /*'T' ( 84) |1101111 */ {0x6f, 7}, + /*'U' ( 85) |1110000 */ {0x70, 7}, + /*'V' ( 86) |1110001 */ {0x71, 7}, + /*'W' ( 87) |1110010 */ {0x72, 7}, + /*'X' ( 88) |11111100 */ {0xfc, 8}, + /*'Y' ( 89) |1110011 */ {0x73, 7}, + /*'Z' ( 90) |11111101 */ {0xfd, 8}, + /*'[' ( 91) |11111111|11011 */ {0x1ffb, 13}, + /*'\' ( 92) |11111111|11111110|000 */ {0x7fff0, 19}, + /*']' ( 93) |11111111|11100 */ {0x1ffc, 13}, + /*'^' ( 94) |11111111|111100 */ {0x3ffc, 14}, + /*'_' ( 95) |100010 */ {0x22, 6}, + /*'`' ( 96) |11111111|1111101 */ {0x7ffd, 15}, + /*'a' ( 97) |00011 */ {0x3, 5}, + /*'b' ( 98) |100011 */ {0x23, 6}, + /*'c' ( 99) |00100 */ {0x4, 5}, + /*'d' (100) |100100 */ {0x24, 6}, + /*'e' (101) |00101 */ {0x5, 5}, + /*'f' (102) |100101 */ {0x25, 6}, + /*'g' (103) |100110 */ {0x26, 6}, + /*'h' (104) |100111 */ {0x27, 6}, + /*'i' (105) |00110 */ {0x6, 5}, + /*'j' (106) |1110100 */ {0x74, 7}, + /*'k' (107) |1110101 */ {0x75, 7}, + /*'l' (108) |101000 */ {0x28, 6}, + /*'m' (109) |101001 */ {0x29, 6}, + /*'n' (110) |101010 */ {0x2a, 6}, + /*'o' (111) |00111 */ {0x7, 5}, + /*'p' (112) |101011 */ {0x2b, 6}, + /*'q' (113) |1110110 */ {0x76, 7}, + /*'r' (114) |101100 */ {0x2c, 6}, + /*'s' (115) |01000 */ {0x8, 5}, + /*'t' (116) |01001 */ {0x9, 5}, + /*'u' (117) |101101 */ {0x2d, 6}, + /*'v' (118) |1110111 */ {0x77, 7}, + /*'w' (119) |1111000 */ {0x78, 7}, + /*'x' (120) |1111001 */ {0x79, 7}, + /*'y' (121) |1111010 */ {0x7a, 7}, + /*'z' (122) |1111011 */ {0x7b, 7}, + /*'{' (123) |11111111|1111110 */ {0x7ffe, 15}, + /*'|' (124) |11111111|100 */ {0x7fc, 11}, + /*'}' (125) |11111111|111101 */ {0x3ffd, 14}, + /*'~' (126) |11111111|11101 */ {0x1ffd, 13}, + /* (127) |11111111|11111111|11111111|1100 */ {0xffffffc, 28}, + /* (128) |11111111|11111110|0110 */ {0xfffe6, 20}, + /* (129) |11111111|11111111|010010 */ {0x3fffd2, 22}, + /* (130) |11111111|11111110|0111 */ {0xfffe7, 20}, + /* (131) |11111111|11111110|1000 */ {0xfffe8, 20}, + /* (132) |11111111|11111111|010011 */ {0x3fffd3, 22}, + /* (133) |11111111|11111111|010100 */ {0x3fffd4, 22}, + /* (134) |11111111|11111111|010101 */ {0x3fffd5, 22}, + /* (135) |11111111|11111111|1011001 */ {0x7fffd9, 23}, + /* (136) |11111111|11111111|010110 */ {0x3fffd6, 22}, + /* (137) |11111111|11111111|1011010 */ {0x7fffda, 23}, + /* (138) |11111111|11111111|1011011 */ {0x7fffdb, 23}, + /* (139) |11111111|11111111|1011100 */ {0x7fffdc, 23}, + /* (140) |11111111|11111111|1011101 */ {0x7fffdd, 23}, + /* (141) |11111111|11111111|1011110 */ {0x7fffde, 23}, + /* (142) |11111111|11111111|11101011 */ {0xffffeb, 24}, + /* (143) |11111111|11111111|1011111 */ {0x7fffdf, 23}, + /* (144) |11111111|11111111|11101100 */ {0xffffec, 24}, + /* (145) |11111111|11111111|11101101 */ {0xffffed, 24}, + /* (146) |11111111|11111111|010111 */ {0x3fffd7, 22}, + /* (147) |11111111|11111111|1100000 */ {0x7fffe0, 23}, + /* (148) |11111111|11111111|11101110 */ {0xffffee, 24}, + /* (149) |11111111|11111111|1100001 */ {0x7fffe1, 23}, + /* (150) |11111111|11111111|1100010 */ {0x7fffe2, 23}, + /* (151) |11111111|11111111|1100011 */ {0x7fffe3, 23}, + /* (152) |11111111|11111111|1100100 */ {0x7fffe4, 23}, + /* (153) |11111111|11111110|11100 */ {0x1fffdc, 21}, + /* (154) |11111111|11111111|011000 */ {0x3fffd8, 22}, + /* (155) |11111111|11111111|1100101 */ {0x7fffe5, 23}, + /* (156) |11111111|11111111|011001 */ {0x3fffd9, 22}, + /* (157) |11111111|11111111|1100110 */ {0x7fffe6, 23}, + /* (158) |11111111|11111111|1100111 */ {0x7fffe7, 23}, + /* (159) |11111111|11111111|11101111 */ {0xffffef, 24}, + /* (160) |11111111|11111111|011010 */ {0x3fffda, 22}, + /* (161) |11111111|11111110|11101 */ {0x1fffdd, 21}, + /* (162) |11111111|11111110|1001 */ {0xfffe9, 20}, + /* (163) |11111111|11111111|011011 */ {0x3fffdb, 22}, + /* (164) |11111111|11111111|011100 */ {0x3fffdc, 22}, + /* (165) |11111111|11111111|1101000 */ {0x7fffe8, 23}, + /* (166) |11111111|11111111|1101001 */ {0x7fffe9, 23}, + /* (167) |11111111|11111110|11110 */ {0x1fffde, 21}, + /* (168) |11111111|11111111|1101010 */ {0x7fffea, 23}, + /* (169) |11111111|11111111|011101 */ {0x3fffdd, 22}, + /* (170) |11111111|11111111|011110 */ {0x3fffde, 22}, + /* (171) |11111111|11111111|11110000 */ {0xfffff0, 24}, + /* (172) |11111111|11111110|11111 */ {0x1fffdf, 21}, + /* (173) |11111111|11111111|011111 */ {0x3fffdf, 22}, + /* (174) |11111111|11111111|1101011 */ {0x7fffeb, 23}, + /* (175) |11111111|11111111|1101100 */ {0x7fffec, 23}, + /* (176) |11111111|11111111|00000 */ {0x1fffe0, 21}, + /* (177) |11111111|11111111|00001 */ {0x1fffe1, 21}, + /* (178) |11111111|11111111|100000 */ {0x3fffe0, 22}, + /* (179) |11111111|11111111|00010 */ {0x1fffe2, 21}, + /* (180) |11111111|11111111|1101101 */ {0x7fffed, 23}, + /* (181) |11111111|11111111|100001 */ {0x3fffe1, 22}, + /* (182) |11111111|11111111|1101110 */ {0x7fffee, 23}, + /* (183) |11111111|11111111|1101111 */ {0x7fffef, 23}, + /* (184) |11111111|11111110|1010 */ {0xfffea, 20}, + /* (185) |11111111|11111111|100010 */ {0x3fffe2, 22}, + /* (186) |11111111|11111111|100011 */ {0x3fffe3, 22}, + /* (187) |11111111|11111111|100100 */ {0x3fffe4, 22}, + /* (188) |11111111|11111111|1110000 */ {0x7ffff0, 23}, + /* (189) |11111111|11111111|100101 */ {0x3fffe5, 22}, + /* (190) |11111111|11111111|100110 */ {0x3fffe6, 22}, + /* (191) |11111111|11111111|1110001 */ {0x7ffff1, 23}, + /* (192) |11111111|11111111|11111000|00 */ {0x3ffffe0, 26}, + /* (193) |11111111|11111111|11111000|01 */ {0x3ffffe1, 26}, + /* (194) |11111111|11111110|1011 */ {0xfffeb, 20}, + /* (195) |11111111|11111110|001 */ {0x7fff1, 19}, + /* (196) |11111111|11111111|100111 */ {0x3fffe7, 22}, + /* (197) |11111111|11111111|1110010 */ {0x7ffff2, 23}, + /* (198) |11111111|11111111|101000 */ {0x3fffe8, 22}, + /* (199) |11111111|11111111|11110110|0 */ {0x1ffffec, 25}, + /* (200) |11111111|11111111|11111000|10 */ {0x3ffffe2, 26}, + /* (201) |11111111|11111111|11111000|11 */ {0x3ffffe3, 26}, + /* (202) |11111111|11111111|11111001|00 */ {0x3ffffe4, 26}, + /* (203) |11111111|11111111|11111011|110 */ {0x7ffffde, 27}, + /* (204) |11111111|11111111|11111011|111 */ {0x7ffffdf, 27}, + /* (205) |11111111|11111111|11111001|01 */ {0x3ffffe5, 26}, + /* (206) |11111111|11111111|11110001 */ {0xfffff1, 24}, + /* (207) |11111111|11111111|11110110|1 */ {0x1ffffed, 25}, + /* (208) |11111111|11111110|010 */ {0x7fff2, 19}, + /* (209) |11111111|11111111|00011 */ {0x1fffe3, 21}, + /* (210) |11111111|11111111|11111001|10 */ {0x3ffffe6, 26}, + /* (211) |11111111|11111111|11111100|000 */ {0x7ffffe0, 27}, + /* (212) |11111111|11111111|11111100|001 */ {0x7ffffe1, 27}, + /* (213) |11111111|11111111|11111001|11 */ {0x3ffffe7, 26}, + /* (214) |11111111|11111111|11111100|010 */ {0x7ffffe2, 27}, + /* (215) |11111111|11111111|11110010 */ {0xfffff2, 24}, + /* (216) |11111111|11111111|00100 */ {0x1fffe4, 21}, + /* (217) |11111111|11111111|00101 */ {0x1fffe5, 21}, + /* (218) |11111111|11111111|11111010|00 */ {0x3ffffe8, 26}, + /* (219) |11111111|11111111|11111010|01 */ {0x3ffffe9, 26}, + /* (220) |11111111|11111111|11111111|1101 */ {0xffffffd, 28}, + /* (221) |11111111|11111111|11111100|011 */ {0x7ffffe3, 27}, + /* (222) |11111111|11111111|11111100|100 */ {0x7ffffe4, 27}, + /* (223) |11111111|11111111|11111100|101 */ {0x7ffffe5, 27}, + /* (224) |11111111|11111110|1100 */ {0xfffec, 20}, + /* (225) |11111111|11111111|11110011 */ {0xfffff3, 24}, + /* (226) |11111111|11111110|1101 */ {0xfffed, 20}, + /* (227) |11111111|11111111|00110 */ {0x1fffe6, 21}, + /* (228) |11111111|11111111|101001 */ {0x3fffe9, 22}, + /* (229) |11111111|11111111|00111 */ {0x1fffe7, 21}, + /* (230) |11111111|11111111|01000 */ {0x1fffe8, 21}, + /* (231) |11111111|11111111|1110011 */ {0x7ffff3, 23}, + /* (232) |11111111|11111111|101010 */ {0x3fffea, 22}, + /* (233) |11111111|11111111|101011 */ {0x3fffeb, 22}, + /* (234) |11111111|11111111|11110111|0 */ {0x1ffffee, 25}, + /* (235) |11111111|11111111|11110111|1 */ {0x1ffffef, 25}, + /* (236) |11111111|11111111|11110100 */ {0xfffff4, 24}, + /* (237) |11111111|11111111|11110101 */ {0xfffff5, 24}, + /* (238) |11111111|11111111|11111010|10 */ {0x3ffffea, 26}, + /* (239) |11111111|11111111|1110100 */ {0x7ffff4, 23}, + /* (240) |11111111|11111111|11111010|11 */ {0x3ffffeb, 26}, + /* (241) |11111111|11111111|11111100|110 */ {0x7ffffe6, 27}, + /* (242) |11111111|11111111|11111011|00 */ {0x3ffffec, 26}, + /* (243) |11111111|11111111|11111011|01 */ {0x3ffffed, 26}, + /* (244) |11111111|11111111|11111100|111 */ {0x7ffffe7, 27}, + /* (245) |11111111|11111111|11111101|000 */ {0x7ffffe8, 27}, + /* (246) |11111111|11111111|11111101|001 */ {0x7ffffe9, 27}, + /* (247) |11111111|11111111|11111101|010 */ {0x7ffffea, 27}, + /* (248) |11111111|11111111|11111101|011 */ {0x7ffffeb, 27}, + /* (249) |11111111|11111111|11111111|1110 */ {0xffffffe, 28}, + /* (250) |11111111|11111111|11111101|100 */ {0x7ffffec, 27}, + /* (251) |11111111|11111111|11111101|101 */ {0x7ffffed, 27}, + /* (252) |11111111|11111111|11111101|110 */ {0x7ffffee, 27}, + /* (253) |11111111|11111111|11111101|111 */ {0x7ffffef, 27}, + /* (254) |11111111|11111111|11111110|000 */ {0x7fffff0, 27}, + /* (255) |11111111|11111111|11111011|10 */ {0x3ffffee, 26}, + /*EOS (256) |11111111|11111111|11111111|111111 */ {0x3fffffff, 30} + }; static final int[][] LCCODES = new int[CODES.length][]; static final char EOS = 256; - + // Huffman decode tree stored in a flattened char array for good // locality of reference. static final char[] tree; @@ -296,87 +296,93 @@ public class Huffman static final byte[] rowbits; // Build the Huffman lookup tree and LC TABLE - static + static { - System.arraycopy(CODES,0,LCCODES,0,CODES.length); - for (int i='A';i<='Z';i++) - LCCODES[i]=LCCODES['a'+i-'A']; - - int r=0; - for (int i=0;i 8) + while (len > 8) { len -= 8; int i = ((code >>> len) & 0xFF); - int t=current*256+i; + int t = current * 256 + i; current = tree[t]; if (current == 0) { tree[t] = (char)++r; - current=r; + current = r; } } int terminal = ++r; - rowsym[r]=(char)sym; + rowsym[r] = (char)sym; int b = len & 0x07; - int terminalBits = b == 0?8:b; + int terminalBits = b == 0 ? 8 : b; - rowbits[r]=(byte)terminalBits; + rowbits[r] = (byte)terminalBits; int shift = 8 - len; - int start = current*256 + ((code << shift) & 0xFF); - int end = start + (1<= 8) + while (bits >= 8) { int c = (current >>> (bits - 8)) & 0xFF; - node = tree[node*256+c]; - if (rowbits[node]!=0) + node = tree[node * 256 + c]; + if (rowbits[node] != 0) { - if(rowsym[node] == EOS) + if (rowsym[node] == EOS) throw new HpackException.CompressionException("EOS in content"); // terminal node out.append(rowsym[node]); bits -= rowbits[node]; node = 0; - } - else + } + else { // non-terminal node bits -= 8; @@ -384,19 +390,21 @@ public class Huffman } } - while (bits > 0) + while (bits > 0) { int c = (current << (8 - bits)) & 0xFF; int lastNode = node; - node = tree[node*256+c]; + node = tree[node * 256 + c]; - if (rowbits[node]==0 || rowbits[node] > bits) + if (rowbits[node] == 0 || rowbits[node] > bits) { int requiredPadding = 0; - for(int i=0; i>(8-bits)) != requiredPadding) + if ((c >> (8 - bits)) != requiredPadding) throw new HpackException.CompressionException("Incorrect padding"); node = lastNode; @@ -408,56 +416,56 @@ public class Huffman node = 0; } - if(node != 0) + if (node != 0) throw new HpackException.CompressionException("Bad termination"); return out.toString(); } public static int octetsNeeded(String s) - { - return octetsNeeded(CODES,s); - } - - public static void encode(ByteBuffer buffer,String s) { - encode(CODES,buffer,s); + return octetsNeeded(CODES, s); } - + + public static void encode(ByteBuffer buffer, String s) + { + encode(CODES, buffer, s); + } + public static int octetsNeededLC(String s) { - return octetsNeeded(LCCODES,s); + return octetsNeeded(LCCODES, s); } public static void encodeLC(ByteBuffer buffer, String s) { - encode(LCCODES,buffer,s); + encode(LCCODES, buffer, s); } - - private static int octetsNeeded(final int[][] table,String s) - { - int needed=0; + + private static int octetsNeeded(final int[][] table, String s) + { + int needed = 0; int len = s.length(); - for (int i=0;i=128 || c<' ') + char c = s.charAt(i); + if (c >= 128 || c < ' ') throw new IllegalArgumentException(); needed += table[c][1]; } - return (needed+7) / 8; + return (needed + 7) / 8; } - private static void encode(final int[][] table,ByteBuffer buffer,String s) + private static void encode(final int[][] table, ByteBuffer buffer, String s) { long current = 0; int n = 0; int len = s.length(); - for (int i=0;i=128 || c<' ') + char c = s.charAt(i); + if (c >= 128 || c < ' ') throw new IllegalArgumentException(); int code = table[c][0]; int bits = table[c][1]; @@ -466,7 +474,7 @@ public class Huffman current |= code; n += bits; - while (n >= 8) + while (n >= 8) { n -= 8; buffer.put((byte)(current >> n)); @@ -479,7 +487,5 @@ public class Huffman current |= (0xFF >>> n); buffer.put((byte)(current)); } - } - } diff --git a/jetty-http2/http2-hpack/src/main/java/org/eclipse/jetty/http2/hpack/MetaDataBuilder.java b/jetty-http2/http2-hpack/src/main/java/org/eclipse/jetty/http2/hpack/MetaDataBuilder.java index 490614e8394..8afb5d5344a 100644 --- a/jetty-http2/http2-hpack/src/main/java/org/eclipse/jetty/http2/hpack/MetaDataBuilder.java +++ b/jetty-http2/http2-hpack/src/main/java/org/eclipse/jetty/http2/hpack/MetaDataBuilder.java @@ -16,10 +16,8 @@ // ======================================================================== // - package org.eclipse.jetty.http2.hpack; - import org.eclipse.jetty.http.HostPortHttpField; import org.eclipse.jetty.http.HttpField; import org.eclipse.jetty.http.HttpFields; @@ -38,7 +36,7 @@ public class MetaDataBuilder private HttpScheme _scheme; private HostPortHttpField _authority; private String _path; - private long _contentLength=Long.MIN_VALUE; + private long _contentLength = Long.MIN_VALUE; private HttpFields _fields = new HttpFields(); private HpackException.StreamException _streamException; private boolean _request; @@ -49,10 +47,12 @@ public class MetaDataBuilder */ protected MetaDataBuilder(int maxHeadersSize) { - _maxSize=maxHeadersSize; + _maxSize = maxHeadersSize; } - /** Get the maxSize. + /** + * Get the maxSize. + * * @return the maxSize */ public int getMaxSize() @@ -60,7 +60,9 @@ public class MetaDataBuilder return _maxSize; } - /** Get the size. + /** + * Get the size. + * * @return the current size in bytes */ public int getSize() @@ -73,30 +75,30 @@ public class MetaDataBuilder HttpHeader header = field.getHeader(); String name = field.getName(); String value = field.getValue(); - int field_size = name.length() + (value == null ? 0 : value.length()); - _size+=field_size+32; - if (_size>_maxSize) - throw new HpackException.SessionException("Header Size %d > %d",_size,_maxSize); + int fieldSize = name.length() + (value == null ? 0 : value.length()); + _size += fieldSize + 32; + if (_size > _maxSize) + throw new HpackException.SessionException("Header Size %d > %d", _size, _maxSize); if (field instanceof StaticTableHttpField) { StaticTableHttpField staticField = (StaticTableHttpField)field; - switch(header) + switch (header) { case C_STATUS: - if(checkPseudoHeader(header, _status)) + if (checkPseudoHeader(header, _status)) _status = staticField.getIntValue(); _response = true; break; case C_METHOD: - if(checkPseudoHeader(header, _method)) + if (checkPseudoHeader(header, _method)) _method = value; _request = true; break; case C_SCHEME: - if(checkPseudoHeader(header, _scheme)) + if (checkPseudoHeader(header, _scheme)) _scheme = (HttpScheme)staticField.getStaticValue(); _request = true; break; @@ -105,30 +107,30 @@ public class MetaDataBuilder throw new IllegalArgumentException(name); } } - else if (header!=null) + else if (header != null) { - switch(header) + switch (header) { case C_STATUS: - if(checkPseudoHeader(header, _status)) + if (checkPseudoHeader(header, _status)) _status = field.getIntValue(); _response = true; break; case C_METHOD: - if(checkPseudoHeader(header, _method)) - _method = value; + if (checkPseudoHeader(header, _method)) + _method = value; _request = true; break; case C_SCHEME: - if(checkPseudoHeader(header, _scheme) && value != null) + if (checkPseudoHeader(header, _scheme) && value != null) _scheme = HttpScheme.CACHE.get(value); _request = true; break; case C_AUTHORITY: - if(checkPseudoHeader(header, _authority)) + if (checkPseudoHeader(header, _authority)) { if (field instanceof HostPortHttpField) _authority = (HostPortHttpField)field; @@ -140,7 +142,7 @@ public class MetaDataBuilder case HOST: // :authority fields must come first. If we have one, ignore the host header as far as authority goes. - if (_authority==null) + if (_authority == null) { if (field instanceof HostPortHttpField) _authority = (HostPortHttpField)field; @@ -151,9 +153,9 @@ public class MetaDataBuilder break; case C_PATH: - if(checkPseudoHeader(header, _path)) + if (checkPseudoHeader(header, _path)) { - if (value!=null && value.length()>0) + if (value != null && value.length() > 0) _path = value; else streamException("No Path"); @@ -165,23 +167,23 @@ public class MetaDataBuilder _contentLength = field.getLongValue(); _fields.add(field); break; - + case TE: if ("trailers".equalsIgnoreCase(value)) _fields.add(field); else streamException("Unsupported TE value '%s'", value); break; - + case CONNECTION: if ("TE".equalsIgnoreCase(value)) _fields.add(field); else streamException("Connection specific field '%s'", header); - break; + break; - default: - if (name.charAt(0)==':') + default: + if (name.charAt(0) == ':') streamException("Unknown pseudo header '%s'", name); else _fields.add(field); @@ -190,8 +192,8 @@ public class MetaDataBuilder } else { - if (name.charAt(0)==':') - streamException("Unknown pseudo header '%s'",name); + if (name.charAt(0) == ':') + streamException("Unknown pseudo header '%s'", name); else _fields.add(field); } @@ -200,7 +202,7 @@ public class MetaDataBuilder protected void streamException(String messageFormat, Object... args) { HpackException.StreamException stream = new HpackException.StreamException(messageFormat, args); - if (_streamException==null) + if (_streamException == null) _streamException = stream; else _streamException.addSuppressed(stream); @@ -208,12 +210,12 @@ public class MetaDataBuilder protected boolean checkPseudoHeader(HttpHeader header, Object value) { - if (_fields.size()>0) + if (_fields.size() > 0) { streamException("Pseudo header %s after fields", header.asString()); return false; } - if (value==null) + if (value == null) return true; streamException("Duplicate pseudo header %s", header.asString()); return false; @@ -221,37 +223,36 @@ public class MetaDataBuilder public MetaData build() throws HpackException.StreamException { - if (_streamException!=null) + if (_streamException != null) { _streamException.addSuppressed(new Throwable()); throw _streamException; } - + if (_request && _response) throw new HpackException.StreamException("Request and Response headers"); - HttpFields fields = _fields; try { if (_request) { - if (_method==null) + if (_method == null) throw new HpackException.StreamException("No Method"); - if (_scheme==null) + if (_scheme == null) throw new HpackException.StreamException("No Scheme"); - if (_path==null) + if (_path == null) throw new HpackException.StreamException("No Path"); - return new MetaData.Request(_method,_scheme,_authority,_path,HttpVersion.HTTP_2,fields,_contentLength); + return new MetaData.Request(_method, _scheme, _authority, _path, HttpVersion.HTTP_2, fields, _contentLength); } if (_response) { - if (_status==null) + if (_status == null) throw new HpackException.StreamException("No Status"); return new MetaData.Response(HttpVersion.HTTP_2, _status, fields, _contentLength); } - - return new MetaData(HttpVersion.HTTP_2,fields,_contentLength); + + return new MetaData(HttpVersion.HTTP_2, fields, _contentLength); } finally { @@ -270,6 +271,7 @@ public class MetaDataBuilder /** * Check that the max size will not be exceeded. + * * @param length the length * @param huffman the huffman name * @throws SessionException in case of size errors @@ -278,8 +280,8 @@ public class MetaDataBuilder { // Apply a huffman fudge factor if (huffman) - length=(length*4)/3; - if ((_size+length)>_maxSize) - throw new HpackException.SessionException("Header too large %d > %d", _size+length, _maxSize); + length = (length * 4) / 3; + if ((_size + length) > _maxSize) + throw new HpackException.SessionException("Header too large %d > %d", _size + length, _maxSize); } } diff --git a/jetty-http2/http2-hpack/src/main/java/org/eclipse/jetty/http2/hpack/NBitInteger.java b/jetty-http2/http2-hpack/src/main/java/org/eclipse/jetty/http2/hpack/NBitInteger.java index b21823f4cda..7d700cd4338 100644 --- a/jetty-http2/http2-hpack/src/main/java/org/eclipse/jetty/http2/hpack/NBitInteger.java +++ b/jetty-http2/http2-hpack/src/main/java/org/eclipse/jetty/http2/hpack/NBitInteger.java @@ -22,35 +22,35 @@ import java.nio.ByteBuffer; public class NBitInteger { - public static int octectsNeeded(int n,int i) + public static int octectsNeeded(int n, int i) { - if (n==8) + if (n == 8) { int nbits = 0xFF; - i=i-nbits; - if (i<0) + i = i - nbits; + if (i < 0) return 1; - if (i==0) + if (i == 0) return 2; - int lz=Integer.numberOfLeadingZeros(i); - int log=32-lz; - return 1+(log+6)/7; + int lz = Integer.numberOfLeadingZeros(i); + int log = 32 - lz; + return 1 + (log + 6) / 7; } - + int nbits = 0xFF >>> (8 - n); - i=i-nbits; - if (i<0) + i = i - nbits; + if (i < 0) return 0; - if (i==0) + if (i == 0) return 1; - int lz=Integer.numberOfLeadingZeros(i); - int log=32-lz; - return (log+6)/7; + int lz = Integer.numberOfLeadingZeros(i); + int log = 32 - lz; + return (log + 6) / 7; } - + public static void encode(ByteBuffer buf, int n, int i) { - if (n==8) + if (n == 8) { if (i < 0xFF) { @@ -78,16 +78,16 @@ public class NBitInteger } else { - int p=buf.position()-1; + int p = buf.position() - 1; int bits = 0xFF >>> (8 - n); if (i < bits) { - buf.put(p,(byte)((buf.get(p)&~bits)|i)); + buf.put(p, (byte)((buf.get(p) & ~bits) | i)); } else { - buf.put(p,(byte)(buf.get(p)|bits)); + buf.put(p, (byte)(buf.get(p) | bits)); int length = i - bits; while (true) @@ -109,42 +109,42 @@ public class NBitInteger public static int decode(ByteBuffer buffer, int n) { - if (n==8) + if (n == 8) { int nbits = 0xFF; - int i=buffer.get()&0xff; - + int i = buffer.get() & 0xff; + if (i == nbits) - { - int m=1; + { + int m = 1; int b; do { - b = 0xff&buffer.get(); - i = i + (b&127) * m; - m = m*128; + b = 0xff & buffer.get(); + i = i + (b & 127) * m; + m = m * 128; } - while ((b&128) == 128); + while ((b & 128) == 128); } return i; } - + int nbits = 0xFF >>> (8 - n); - int i=buffer.get(buffer.position()-1)&nbits; - + int i = buffer.get(buffer.position() - 1) & nbits; + if (i == nbits) - { - int m=1; + { + int m = 1; int b; do { - b = 0xff&buffer.get(); - i = i + (b&127) * m; - m = m*128; + b = 0xff & buffer.get(); + i = i + (b & 127) * m; + m = m * 128; } - while ((b&128) == 128); + while ((b & 128) == 128); } return i; } diff --git a/jetty-http2/http2-hpack/src/main/java/org/eclipse/jetty/http2/hpack/StaticTableHttpField.java b/jetty-http2/http2-hpack/src/main/java/org/eclipse/jetty/http2/hpack/StaticTableHttpField.java index 6f9e6d9c32a..56bd4bc4be6 100644 --- a/jetty-http2/http2-hpack/src/main/java/org/eclipse/jetty/http2/hpack/StaticTableHttpField.java +++ b/jetty-http2/http2-hpack/src/main/java/org/eclipse/jetty/http2/hpack/StaticTableHttpField.java @@ -16,46 +16,44 @@ // ======================================================================== // - package org.eclipse.jetty.http2.hpack; import org.eclipse.jetty.http.HttpField; import org.eclipse.jetty.http.HttpHeader; -/* ------------------------------------------------------------ */ public class StaticTableHttpField extends HttpField { private final Object _value; public StaticTableHttpField(HttpHeader header, String name, String valueString, Object value) { - super(header,name,valueString); - if (value==null) + super(header, name, valueString); + if (value == null) throw new IllegalArgumentException(); - _value=value; + _value = value; } - - public StaticTableHttpField(HttpHeader header,String valueString, Object value) + + public StaticTableHttpField(HttpHeader header, String valueString, Object value) { - this (header,header.asString(),valueString, value); + this(header, header.asString(), valueString, value); } - + public StaticTableHttpField(String name, String valueString, Object value) { - super(name,valueString); - if (value==null) + super(name, valueString); + if (value == null) throw new IllegalArgumentException(); - _value=value; + _value = value; } public Object getStaticValue() { return _value; } - + @Override public String toString() { - return super.toString()+"(evaluated)"; + return super.toString() + "(evaluated)"; } } diff --git a/jetty-http2/http2-hpack/src/test/java/org/eclipse/jetty/http2/hpack/HpackContextTest.java b/jetty-http2/http2-hpack/src/test/java/org/eclipse/jetty/http2/hpack/HpackContextTest.java index 4f868208e12..ed4ac09d86a 100644 --- a/jetty-http2/http2-hpack/src/test/java/org/eclipse/jetty/http2/hpack/HpackContextTest.java +++ b/jetty-http2/http2-hpack/src/test/java/org/eclipse/jetty/http2/hpack/HpackContextTest.java @@ -16,9 +16,14 @@ // ======================================================================== // - package org.eclipse.jetty.http2.hpack; +import java.nio.ByteBuffer; + +import org.eclipse.jetty.http.HttpField; +import org.eclipse.jetty.http2.hpack.HpackContext.Entry; +import org.hamcrest.Matchers; +import org.junit.jupiter.api.Test; import static org.hamcrest.MatcherAssert.assertThat; import static org.junit.jupiter.api.Assertions.assertEquals; @@ -27,17 +32,8 @@ import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertNull; import static org.junit.jupiter.api.Assertions.assertTrue; -import java.nio.ByteBuffer; - -import org.eclipse.jetty.http.HttpField; -import org.eclipse.jetty.http2.hpack.HpackContext.Entry; -import org.hamcrest.Matchers; - -import org.junit.jupiter.api.Test; - - -/* ------------------------------------------------------------ */ /** + * */ public class HpackContextTest { @@ -46,92 +42,94 @@ public class HpackContextTest public void testStaticName() { HpackContext ctx = new HpackContext(4096); - Entry entry=ctx.get(":method"); - assertEquals(":method",entry.getHttpField().getName()); + Entry entry = ctx.get(":method"); + assertEquals(":method", entry.getHttpField().getName()); assertTrue(entry.isStatic()); - assertThat(entry.toString(),Matchers.startsWith("{S,2,:method: ")); + assertThat(entry.toString(), Matchers.startsWith("{S,2,:method: ")); } - + @Test public void testEmptyAdd() { HpackContext ctx = new HpackContext(0); - HttpField field = new HttpField("foo","bar"); + HttpField field = new HttpField("foo", "bar"); assertNull(ctx.add(field)); } - + @Test public void testTooBigAdd() { HpackContext ctx = new HpackContext(37); - HttpField field = new HttpField("foo","bar"); + HttpField field = new HttpField("foo", "bar"); assertNull(ctx.add(field)); } - + @Test public void testJustRight() { HpackContext ctx = new HpackContext(38); - HttpField field = new HttpField("foo","bar"); - Entry entry=ctx.add(field); + HttpField field = new HttpField("foo", "bar"); + Entry entry = ctx.add(field); assertNotNull(entry); - assertThat(entry.toString(),Matchers.startsWith("{D,0,foo: bar,")); + assertThat(entry.toString(), Matchers.startsWith("{D,0,foo: bar,")); } - + @Test public void testEvictOne() { HpackContext ctx = new HpackContext(38); - HttpField field0 = new HttpField("foo","bar"); - - assertEquals(field0,ctx.add(field0).getHttpField()); - assertEquals(field0,ctx.get("foo").getHttpField()); - - HttpField field1 = new HttpField("xxx","yyy"); - assertEquals(field1,ctx.add(field1).getHttpField()); + HttpField field0 = new HttpField("foo", "bar"); + + assertEquals(field0, ctx.add(field0).getHttpField()); + assertEquals(field0, ctx.get("foo").getHttpField()); + + HttpField field1 = new HttpField("xxx", "yyy"); + assertEquals(field1, ctx.add(field1).getHttpField()); assertNull(ctx.get(field0)); assertNull(ctx.get("foo")); - assertEquals(field1,ctx.get(field1).getHttpField()); - assertEquals(field1,ctx.get("xxx").getHttpField()); - + assertEquals(field1, ctx.get(field1).getHttpField()); + assertEquals(field1, ctx.get("xxx").getHttpField()); } @Test public void testEvictNames() { - HpackContext ctx = new HpackContext(38*2); - HttpField[] field = - { - new HttpField("name","v0"), - new HttpField("name","v1"), - new HttpField("name","v2"), - new HttpField("name","v3"), - new HttpField("name","v4"), - new HttpField("name","v5"), - }; - + HpackContext ctx = new HpackContext(38 * 2); + HttpField[] field = + { + new HttpField("name", "v0"), + new HttpField("name", "v1"), + new HttpField("name", "v2"), + new HttpField("name", "v3"), + new HttpField("name", "v4"), + new HttpField("name", "v5"), + }; + Entry[] entry = new Entry[field.length]; - + // Add 2 name entries to fill table - for (int i=0;i<=1;i++) - entry[i]=ctx.add(field[i]); - + for (int i = 0; i <= 1; i++) + { + entry[i] = ctx.add(field[i]); + } + // check there is a name reference and it is the most recent added - assertEquals(entry[1],ctx.get("name")); + assertEquals(entry[1], ctx.get("name")); // Add 1 other entry to table and evict 1 - ctx.add(new HttpField("xxx","yyy")); - + ctx.add(new HttpField("xxx", "yyy")); + // check the name reference has been not been evicted - assertEquals(entry[1],ctx.get("name")); - + assertEquals(entry[1], ctx.get("name")); + // Add 1 other entry to table and evict 1 - ctx.add(new HttpField("foo","bar")); - + ctx.add(new HttpField("foo", "bar")); + // name is evicted assertNull(ctx.get("name")); } + @Test @SuppressWarnings("ReferenceEquality") public void testGetAddStatic() @@ -139,316 +137,317 @@ public class HpackContextTest HpackContext ctx = new HpackContext(4096); // Look for the field. Should find static version. - HttpField methodGet = new HttpField(":method","GET"); - assertEquals(methodGet,ctx.get(methodGet).getHttpField()); + HttpField methodGet = new HttpField(":method", "GET"); + assertEquals(methodGet, ctx.get(methodGet).getHttpField()); assertTrue(ctx.get(methodGet).isStatic()); - + // Add static version to dynamic table - Entry e0=ctx.add(ctx.get(methodGet).getHttpField()); - + Entry e0 = ctx.add(ctx.get(methodGet).getHttpField()); + // Look again and should see dynamic version - assertEquals(methodGet,ctx.get(methodGet).getHttpField()); - assertFalse(methodGet==ctx.get(methodGet).getHttpField()); + assertEquals(methodGet, ctx.get(methodGet).getHttpField()); + assertFalse(methodGet == ctx.get(methodGet).getHttpField()); assertFalse(ctx.get(methodGet).isStatic()); - + // Duplicates allows - Entry e1=ctx.add(ctx.get(methodGet).getHttpField()); - + Entry e1 = ctx.add(ctx.get(methodGet).getHttpField()); + // Look again and should see dynamic version - assertEquals(methodGet,ctx.get(methodGet).getHttpField()); - assertFalse(methodGet==ctx.get(methodGet).getHttpField()); + assertEquals(methodGet, ctx.get(methodGet).getHttpField()); + assertFalse(methodGet == ctx.get(methodGet).getHttpField()); assertFalse(ctx.get(methodGet).isStatic()); - assertFalse(e0==e1); + assertFalse(e0 == e1); } - + @Test public void testGetAddStaticName() { HpackContext ctx = new HpackContext(4096); - HttpField methodOther = new HttpField(":method","OTHER"); + HttpField methodOther = new HttpField(":method", "OTHER"); // Look for the field by name. Should find static version. - assertEquals(":method",ctx.get(":method").getHttpField().getName()); + assertEquals(":method", ctx.get(":method").getHttpField().getName()); assertTrue(ctx.get(":method").isStatic()); - + // Add dynamic entry with method ctx.add(methodOther); - + // Look for the field by name. Should find static version. - assertEquals(":method",ctx.get(":method").getHttpField().getName()); - assertTrue(ctx.get(":method").isStatic()); + assertEquals(":method", ctx.get(":method").getHttpField().getName()); + assertTrue(ctx.get(":method").isStatic()); } @Test public void testIndexes() { // Only enough space for 5 entries - HpackContext ctx = new HpackContext(38*5); - - HttpField methodPost = new HttpField(":method","POST"); - HttpField[] field = - { - new HttpField("fo0","b0r"), - new HttpField("fo1","b1r"), - new HttpField("fo2","b2r"), - new HttpField("fo3","b3r"), - new HttpField("fo4","b4r"), - new HttpField("fo5","b5r"), - new HttpField("fo6","b6r"), - new HttpField("fo7","b7r"), - new HttpField("fo8","b8r"), - new HttpField("fo9","b9r"), - new HttpField("foA","bAr"), - }; - + HpackContext ctx = new HpackContext(38 * 5); + + HttpField methodPost = new HttpField(":method", "POST"); + HttpField[] field = + { + new HttpField("fo0", "b0r"), + new HttpField("fo1", "b1r"), + new HttpField("fo2", "b2r"), + new HttpField("fo3", "b3r"), + new HttpField("fo4", "b4r"), + new HttpField("fo5", "b5r"), + new HttpField("fo6", "b6r"), + new HttpField("fo7", "b7r"), + new HttpField("fo8", "b8r"), + new HttpField("fo9", "b9r"), + new HttpField("foA", "bAr"), + }; + Entry[] entry = new Entry[100]; - + // Lookup the index of a static field - assertEquals(0,ctx.size()); - assertEquals(":authority",ctx.get(1).getHttpField().getName()); - assertEquals(3,ctx.index(ctx.get(methodPost))); - assertEquals(methodPost,ctx.get(3).getHttpField()); - assertEquals("www-authenticate",ctx.get(61).getHttpField().getName()); - assertEquals(null,ctx.get(62)); - + assertEquals(0, ctx.size()); + assertEquals(":authority", ctx.get(1).getHttpField().getName()); + assertEquals(3, ctx.index(ctx.get(methodPost))); + assertEquals(methodPost, ctx.get(3).getHttpField()); + assertEquals("www-authenticate", ctx.get(61).getHttpField().getName()); + assertEquals(null, ctx.get(62)); + // Add a single entry - entry[0]=ctx.add(field[0]); - + entry[0] = ctx.add(field[0]); + // Check new entry is 62 - assertEquals(1,ctx.size()); - assertEquals(62,ctx.index(entry[0])); - assertEquals(entry[0],ctx.get(62)); - + assertEquals(1, ctx.size()); + assertEquals(62, ctx.index(entry[0])); + assertEquals(entry[0], ctx.get(62)); + // and statics still OK - assertEquals(":authority",ctx.get(1).getHttpField().getName()); - assertEquals(3,ctx.index(ctx.get(methodPost))); - assertEquals(methodPost,ctx.get(3).getHttpField()); - assertEquals("www-authenticate",ctx.get(61).getHttpField().getName()); - assertEquals(null,ctx.get(62+ctx.size())); - + assertEquals(":authority", ctx.get(1).getHttpField().getName()); + assertEquals(3, ctx.index(ctx.get(methodPost))); + assertEquals(methodPost, ctx.get(3).getHttpField()); + assertEquals("www-authenticate", ctx.get(61).getHttpField().getName()); + assertEquals(null, ctx.get(62 + ctx.size())); // Add 4 more entries - for (int i=1;i<=4;i++) - entry[i]=ctx.add(field[i]); + for (int i = 1; i <= 4; i++) + { + entry[i] = ctx.add(field[i]); + } // Check newest entry is at 62 oldest at 66 - assertEquals(5,ctx.size()); - int index=66; - for (int i=0;i<=4;i++) + assertEquals(5, ctx.size()); + int index = 66; + for (int i = 0; i <= 4; i++) { - assertEquals(index,ctx.index(entry[i])); - assertEquals(entry[i],ctx.get(index)); + assertEquals(index, ctx.index(entry[i])); + assertEquals(entry[i], ctx.get(index)); index--; } // and statics still OK - assertEquals(":authority",ctx.get(1).getHttpField().getName()); - assertEquals(3,ctx.index(ctx.get(methodPost))); - assertEquals(methodPost,ctx.get(3).getHttpField()); - assertEquals("www-authenticate",ctx.get(61).getHttpField().getName()); - assertEquals(null,ctx.get(62+ctx.size())); - + assertEquals(":authority", ctx.get(1).getHttpField().getName()); + assertEquals(3, ctx.index(ctx.get(methodPost))); + assertEquals(methodPost, ctx.get(3).getHttpField()); + assertEquals("www-authenticate", ctx.get(61).getHttpField().getName()); + assertEquals(null, ctx.get(62 + ctx.size())); + // add 1 more entry and this should cause an eviction! - entry[5]=ctx.add(field[5]); + entry[5] = ctx.add(field[5]); // Check newest entry is at 1 oldest at 5 - index=66; - for (int i=1;i<=5;i++) + index = 66; + for (int i = 1; i <= 5; i++) { - assertEquals(index,ctx.index(entry[i])); - assertEquals(entry[i],ctx.get(index)); + assertEquals(index, ctx.index(entry[i])); + assertEquals(entry[i], ctx.get(index)); index--; } // check entry 0 evicted assertNull(ctx.get(field[0])); - assertEquals(0,ctx.index(entry[0])); + assertEquals(0, ctx.index(entry[0])); // and statics still OK - assertEquals(":authority",ctx.get(1).getHttpField().getName()); - assertEquals(3,ctx.index(ctx.get(methodPost))); - assertEquals(methodPost,ctx.get(3).getHttpField()); - assertEquals("www-authenticate",ctx.get(61).getHttpField().getName()); - assertEquals(null,ctx.get(62+ctx.size())); - + assertEquals(":authority", ctx.get(1).getHttpField().getName()); + assertEquals(3, ctx.index(ctx.get(methodPost))); + assertEquals(methodPost, ctx.get(3).getHttpField()); + assertEquals("www-authenticate", ctx.get(61).getHttpField().getName()); + assertEquals(null, ctx.get(62 + ctx.size())); + // Add 4 more entries - for (int i=6;i<=9;i++) - entry[i]=ctx.add(field[i]); - - // Check newest entry is at 1 oldest at 5 - index=66; - for (int i=5;i<=9;i++) + for (int i = 6; i <= 9; i++) { - assertEquals(index,ctx.index(entry[i])); - assertEquals(entry[i],ctx.get(index)); + entry[i] = ctx.add(field[i]); + } + + // Check newest entry is at 1 oldest at 5 + index = 66; + for (int i = 5; i <= 9; i++) + { + assertEquals(index, ctx.index(entry[i])); + assertEquals(entry[i], ctx.get(index)); index--; } // check entry 0-4 evicted - for (int i=0;i<=4;i++) + for (int i = 0; i <= 4; i++) { assertNull(ctx.get(field[i])); - assertEquals(0,ctx.index(entry[i])); + assertEquals(0, ctx.index(entry[i])); } - // Add new entries enough so that array queue will wrap - for (int i=10;i<=52;i++) - entry[i]=ctx.add(new HttpField("n"+i,"v"+i)); - - index=66; - for (int i=48;i<=52;i++) + for (int i = 10; i <= 52; i++) { - assertEquals(index,ctx.index(entry[i])); - assertEquals(entry[i],ctx.get(index)); + entry[i] = ctx.add(new HttpField("n" + i, "v" + i)); + } + + index = 66; + for (int i = 48; i <= 52; i++) + { + assertEquals(index, ctx.index(entry[i])); + assertEquals(entry[i], ctx.get(index)); index--; } } - @Test public void testResize() { // Only enough space for 5 entries - HpackContext ctx = new HpackContext(38*5); - - HttpField[] field = - { - new HttpField("fo0","b0r"), - new HttpField("fo1","b1r"), - new HttpField("fo2","b2r"), - new HttpField("fo3","b3r"), - new HttpField("fo4","b4r"), - new HttpField("fo5","b5r"), - new HttpField("fo6","b6r"), - new HttpField("fo7","b7r"), - new HttpField("fo8","b8r"), - new HttpField("fo9","b9r"), - new HttpField("foA","bAr"), - }; + HpackContext ctx = new HpackContext(38 * 5); + + HttpField[] field = + { + new HttpField("fo0", "b0r"), + new HttpField("fo1", "b1r"), + new HttpField("fo2", "b2r"), + new HttpField("fo3", "b3r"), + new HttpField("fo4", "b4r"), + new HttpField("fo5", "b5r"), + new HttpField("fo6", "b6r"), + new HttpField("fo7", "b7r"), + new HttpField("fo8", "b8r"), + new HttpField("fo9", "b9r"), + new HttpField("foA", "bAr"), + }; Entry[] entry = new Entry[field.length]; - + // Add 5 entries - for (int i=0;i<=4;i++) - entry[i]=ctx.add(field[i]); - - assertEquals(5,ctx.size()); - - // check indexes - int index=66; - for (int i=0;i<=4;i++) + for (int i = 0; i <= 4; i++) { - assertEquals(index,ctx.index(entry[i])); - assertEquals(entry[i],ctx.get(index)); + entry[i] = ctx.add(field[i]); + } + + assertEquals(5, ctx.size()); + + // check indexes + int index = 66; + for (int i = 0; i <= 4; i++) + { + assertEquals(index, ctx.index(entry[i])); + assertEquals(entry[i], ctx.get(index)); index--; } // resize so that only 2 entries may be held - ctx.resize(38*2); - assertEquals(2,ctx.size()); - - // check indexes - index=63; - for (int i=3;i<=4;i++) - { - assertEquals(index,ctx.index(entry[i])); - assertEquals(entry[i],ctx.get(index)); - index--; - } - - // resize so that 6.5 entries may be held - ctx.resize(38*6+19); - assertEquals(2,ctx.size()); + ctx.resize(38 * 2); + assertEquals(2, ctx.size()); // check indexes - index=63; - for (int i=3;i<=4;i++) + index = 63; + for (int i = 3; i <= 4; i++) { - assertEquals(index,ctx.index(entry[i])); - assertEquals(entry[i],ctx.get(index)); + assertEquals(index, ctx.index(entry[i])); + assertEquals(entry[i], ctx.get(index)); + index--; + } + + // resize so that 6.5 entries may be held + ctx.resize(38 * 6 + 19); + assertEquals(2, ctx.size()); + + // check indexes + index = 63; + for (int i = 3; i <= 4; i++) + { + assertEquals(index, ctx.index(entry[i])); + assertEquals(entry[i], ctx.get(index)); index--; } - // Add 5 entries - for (int i=5;i<=9;i++) - entry[i]=ctx.add(field[i]); - - assertEquals(6,ctx.size()); + for (int i = 5; i <= 9; i++) + { + entry[i] = ctx.add(field[i]); + } + + assertEquals(6, ctx.size()); // check indexes - index=67; - for (int i=4;i<=9;i++) + index = 67; + for (int i = 4; i <= 9; i++) { - assertEquals(index,ctx.index(entry[i])); - assertEquals(entry[i],ctx.get(index)); + assertEquals(index, ctx.index(entry[i])); + assertEquals(entry[i], ctx.get(index)); index--; } - // resize so that only 100 entries may be held - ctx.resize(38*100); - assertEquals(6,ctx.size()); + ctx.resize(38 * 100); + assertEquals(6, ctx.size()); // check indexes - index=67; - for (int i=4;i<=9;i++) + index = 67; + for (int i = 4; i <= 9; i++) { - assertEquals(index,ctx.index(entry[i])); - assertEquals(entry[i],ctx.get(index)); + assertEquals(index, ctx.index(entry[i])); + assertEquals(entry[i], ctx.get(index)); index--; } - + // add 50 fields - for (int i=0;i<50;i++) - ctx.add(new HttpField("n"+i,"v"+i)); + for (int i = 0; i < 50; i++) + { + ctx.add(new HttpField("n" + i, "v" + i)); + } // check indexes - index=67+50; - for (int i=4;i<=9;i++) + index = 67 + 50; + for (int i = 4; i <= 9; i++) { - assertEquals(index,ctx.index(entry[i])); - assertEquals(entry[i],ctx.get(index)); + assertEquals(index, ctx.index(entry[i])); + assertEquals(entry[i], ctx.get(index)); index--; } - - } - + @Test public void testStaticHuffmanValues() throws Exception { HpackContext ctx = new HpackContext(4096); - for (int i=2;i<=14;i++) + for (int i = 2; i <= 14; i++) { - Entry entry=ctx.get(i); + Entry entry = ctx.get(i); assertTrue(entry.isStatic()); - + ByteBuffer buffer = ByteBuffer.wrap(entry.getStaticHuffmanValue()); - int huff = 0xff&buffer.get(); - assertTrue((0x80&huff)==0x80); - - int len = NBitInteger.decode(buffer,7); - - assertEquals(len,buffer.remaining()); + int huff = 0xff & buffer.get(); + assertTrue((0x80 & huff) == 0x80); + + int len = NBitInteger.decode(buffer, 7); + + assertEquals(len, buffer.remaining()); String value = Huffman.decode(buffer); - - assertEquals(entry.getHttpField().getValue(),value); - + + assertEquals(entry.getHttpField().getValue(), value); } } - - @Test public void testNameInsensitivity() { HpackContext ctx = new HpackContext(4096); - assertEquals("content-length",ctx.get("content-length").getHttpField().getName()); - assertEquals("content-length",ctx.get("Content-Length").getHttpField().getName()); + assertEquals("content-length", ctx.get("content-length").getHttpField().getName()); + assertEquals("content-length", ctx.get("Content-Length").getHttpField().getName()); assertTrue(ctx.get("Content-Length").isStatic()); assertTrue(ctx.get("Content-Type").isStatic()); - - ctx.add(new HttpField("Wibble","Wobble")); - assertEquals("Wibble",ctx.get("wibble").getHttpField().getName()); - assertEquals("Wibble",ctx.get("Wibble").getHttpField().getName()); - + + ctx.add(new HttpField("Wibble", "Wobble")); + assertEquals("Wibble", ctx.get("wibble").getHttpField().getName()); + assertEquals("Wibble", ctx.get("Wibble").getHttpField().getName()); } } diff --git a/jetty-http2/http2-hpack/src/test/java/org/eclipse/jetty/http2/hpack/HpackDecoderTest.java b/jetty-http2/http2-hpack/src/test/java/org/eclipse/jetty/http2/hpack/HpackDecoderTest.java index f75764f91a1..12526186674 100644 --- a/jetty-http2/http2-hpack/src/test/java/org/eclipse/jetty/http2/hpack/HpackDecoderTest.java +++ b/jetty-http2/http2-hpack/src/test/java/org/eclipse/jetty/http2/hpack/HpackDecoderTest.java @@ -16,7 +16,6 @@ // ======================================================================== // - package org.eclipse.jetty.http2.hpack; import java.nio.ByteBuffer; @@ -42,87 +41,86 @@ import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.junit.jupiter.api.Assertions.fail; - public class HpackDecoderTest { @Test public void testDecodeD_3() throws Exception { - HpackDecoder decoder = new HpackDecoder(4096,8192); + HpackDecoder decoder = new HpackDecoder(4096, 8192); // First request - String encoded="828684410f7777772e6578616d706c652e636f6d"; + String encoded = "828684410f7777772e6578616d706c652e636f6d"; ByteBuffer buffer = ByteBuffer.wrap(TypeUtil.fromHexString(encoded)); MetaData.Request request = (MetaData.Request)decoder.decode(buffer); assertEquals("GET", request.getMethod()); - assertEquals(HttpScheme.HTTP.asString(),request.getURI().getScheme()); - assertEquals("/",request.getURI().getPath()); - assertEquals("www.example.com",request.getURI().getHost()); + assertEquals(HttpScheme.HTTP.asString(), request.getURI().getScheme()); + assertEquals("/", request.getURI().getPath()); + assertEquals("www.example.com", request.getURI().getHost()); assertFalse(request.iterator().hasNext()); // Second request - encoded="828684be58086e6f2d6361636865"; + encoded = "828684be58086e6f2d6361636865"; buffer = ByteBuffer.wrap(TypeUtil.fromHexString(encoded)); request = (MetaData.Request)decoder.decode(buffer); assertEquals("GET", request.getMethod()); - assertEquals(HttpScheme.HTTP.asString(),request.getURI().getScheme()); - assertEquals("/",request.getURI().getPath()); - assertEquals("www.example.com",request.getURI().getHost()); - Iterator iterator=request.iterator(); + assertEquals(HttpScheme.HTTP.asString(), request.getURI().getScheme()); + assertEquals("/", request.getURI().getPath()); + assertEquals("www.example.com", request.getURI().getHost()); + Iterator iterator = request.iterator(); assertTrue(iterator.hasNext()); - assertEquals(new HttpField("cache-control","no-cache"),iterator.next()); + assertEquals(new HttpField("cache-control", "no-cache"), iterator.next()); assertFalse(iterator.hasNext()); // Third request - encoded="828785bf400a637573746f6d2d6b65790c637573746f6d2d76616c7565"; + encoded = "828785bf400a637573746f6d2d6b65790c637573746f6d2d76616c7565"; buffer = ByteBuffer.wrap(TypeUtil.fromHexString(encoded)); request = (MetaData.Request)decoder.decode(buffer); - assertEquals("GET",request.getMethod()); - assertEquals(HttpScheme.HTTPS.asString(),request.getURI().getScheme()); - assertEquals("/index.html",request.getURI().getPath()); - assertEquals("www.example.com",request.getURI().getHost()); - iterator=request.iterator(); + assertEquals("GET", request.getMethod()); + assertEquals(HttpScheme.HTTPS.asString(), request.getURI().getScheme()); + assertEquals("/index.html", request.getURI().getPath()); + assertEquals("www.example.com", request.getURI().getHost()); + iterator = request.iterator(); assertTrue(iterator.hasNext()); - assertEquals(new HttpField("custom-key","custom-value"),iterator.next()); + assertEquals(new HttpField("custom-key", "custom-value"), iterator.next()); assertFalse(iterator.hasNext()); } @Test public void testDecodeD_4() throws Exception { - HpackDecoder decoder = new HpackDecoder(4096,8192); + HpackDecoder decoder = new HpackDecoder(4096, 8192); // First request - String encoded="828684418cf1e3c2e5f23a6ba0ab90f4ff"; + String encoded = "828684418cf1e3c2e5f23a6ba0ab90f4ff"; ByteBuffer buffer = ByteBuffer.wrap(TypeUtil.fromHexString(encoded)); MetaData.Request request = (MetaData.Request)decoder.decode(buffer); assertEquals("GET", request.getMethod()); - assertEquals(HttpScheme.HTTP.asString(),request.getURI().getScheme()); - assertEquals("/",request.getURI().getPath()); - assertEquals("www.example.com",request.getURI().getHost()); + assertEquals(HttpScheme.HTTP.asString(), request.getURI().getScheme()); + assertEquals("/", request.getURI().getPath()); + assertEquals("www.example.com", request.getURI().getHost()); assertFalse(request.iterator().hasNext()); // Second request - encoded="828684be5886a8eb10649cbf"; + encoded = "828684be5886a8eb10649cbf"; buffer = ByteBuffer.wrap(TypeUtil.fromHexString(encoded)); request = (MetaData.Request)decoder.decode(buffer); assertEquals("GET", request.getMethod()); - assertEquals(HttpScheme.HTTP.asString(),request.getURI().getScheme()); - assertEquals("/",request.getURI().getPath()); - assertEquals("www.example.com",request.getURI().getHost()); - Iterator iterator=request.iterator(); + assertEquals(HttpScheme.HTTP.asString(), request.getURI().getScheme()); + assertEquals("/", request.getURI().getPath()); + assertEquals("www.example.com", request.getURI().getHost()); + Iterator iterator = request.iterator(); assertTrue(iterator.hasNext()); - assertEquals(new HttpField("cache-control","no-cache"),iterator.next()); + assertEquals(new HttpField("cache-control", "no-cache"), iterator.next()); assertFalse(iterator.hasNext()); } @@ -131,7 +129,7 @@ public class HpackDecoderTest { String value = "Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ=="; - HpackDecoder decoder = new HpackDecoder(4096,8192); + HpackDecoder decoder = new HpackDecoder(4096, 8192); String encoded = "8682418cF1E3C2E5F23a6bA0Ab90F4Ff841f0822426173696320515778685a475270626a70766347567549484e6c633246745a513d3d"; byte[] bytes = TypeUtil.fromHexString(encoded); byte[] array = new byte[bytes.length + 1]; @@ -141,10 +139,10 @@ public class HpackDecoderTest MetaData.Request request = (MetaData.Request)decoder.decode(buffer); assertEquals("GET", request.getMethod()); - assertEquals(HttpScheme.HTTP.asString(),request.getURI().getScheme()); - assertEquals("/",request.getURI().getPath()); - assertEquals("www.example.com",request.getURI().getHost()); - assertEquals(1,request.getFields().size()); + assertEquals(HttpScheme.HTTP.asString(), request.getURI().getScheme()); + assertEquals("/", request.getURI().getPath()); + assertEquals("www.example.com", request.getURI().getHost()); + assertEquals(1, request.getFields().size()); HttpField field = request.iterator().next(); assertEquals(HttpHeader.AUTHORIZATION, field.getHeader()); assertEquals(value, field.getValue()); @@ -153,9 +151,9 @@ public class HpackDecoderTest @Test public void testDecodeHuffmanWithArrayOffset() throws Exception { - HpackDecoder decoder = new HpackDecoder(4096,8192); + HpackDecoder decoder = new HpackDecoder(4096, 8192); - String encoded="8286418cf1e3c2e5f23a6ba0ab90f4ff84"; + String encoded = "8286418cf1e3c2e5f23a6ba0ab90f4ff84"; byte[] bytes = TypeUtil.fromHexString(encoded); byte[] array = new byte[bytes.length + 1]; System.arraycopy(bytes, 0, array, 1, bytes.length); @@ -164,30 +162,30 @@ public class HpackDecoderTest MetaData.Request request = (MetaData.Request)decoder.decode(buffer); assertEquals("GET", request.getMethod()); - assertEquals(HttpScheme.HTTP.asString(),request.getURI().getScheme()); - assertEquals("/",request.getURI().getPath()); - assertEquals("www.example.com",request.getURI().getHost()); + assertEquals(HttpScheme.HTTP.asString(), request.getURI().getScheme()); + assertEquals("/", request.getURI().getPath()); + assertEquals("www.example.com", request.getURI().getHost()); assertFalse(request.iterator().hasNext()); } - + @Test public void testNghttpx() throws Exception - { + { // Response encoded by nghttpx - String encoded="886196C361Be940b6a65B6850400B8A00571972e080a62D1Bf5f87497cA589D34d1f9a0f0d0234327690Aa69D29aFcA954D3A5358980Ae112e0f7c880aE152A9A74a6bF3"; + String encoded = "886196C361Be940b6a65B6850400B8A00571972e080a62D1Bf5f87497cA589D34d1f9a0f0d0234327690Aa69D29aFcA954D3A5358980Ae112e0f7c880aE152A9A74a6bF3"; ByteBuffer buffer = ByteBuffer.wrap(TypeUtil.fromHexString(encoded)); - HpackDecoder decoder = new HpackDecoder(4096,8192); + HpackDecoder decoder = new HpackDecoder(4096, 8192); MetaData.Response response = (MetaData.Response)decoder.decode(buffer); - assertThat(response.getStatus(),is(200)); - assertThat(response.getFields().size(),is(6)); - assertThat(response.getFields(), containsHeaderValue(HttpHeader.DATE,"Fri, 15 Jul 2016 02:36:20 GMT")); - assertThat(response.getFields(), containsHeaderValue(HttpHeader.CONTENT_TYPE,"text/html")); - assertThat(response.getFields(), containsHeaderValue(HttpHeader.CONTENT_ENCODING,"")); - assertThat(response.getFields(), containsHeaderValue(HttpHeader.CONTENT_LENGTH,"42")); - assertThat(response.getFields(), containsHeaderValue(HttpHeader.SERVER,"nghttpx nghttp2/1.12.0")); - assertThat(response.getFields(), containsHeaderValue(HttpHeader.VIA,"1.1 nghttpx")); + assertThat(response.getStatus(), is(200)); + assertThat(response.getFields().size(), is(6)); + assertThat(response.getFields(), containsHeaderValue(HttpHeader.DATE, "Fri, 15 Jul 2016 02:36:20 GMT")); + assertThat(response.getFields(), containsHeaderValue(HttpHeader.CONTENT_TYPE, "text/html")); + assertThat(response.getFields(), containsHeaderValue(HttpHeader.CONTENT_ENCODING, "")); + assertThat(response.getFields(), containsHeaderValue(HttpHeader.CONTENT_LENGTH, "42")); + assertThat(response.getFields(), containsHeaderValue(HttpHeader.SERVER, "nghttpx nghttp2/1.12.0")); + assertThat(response.getFields(), containsHeaderValue(HttpHeader.VIA, "1.1 nghttpx")); } @Test @@ -197,12 +195,10 @@ public class HpackDecoderTest ByteBuffer buffer = ByteBuffer.wrap(TypeUtil.fromHexString(encoded)); HpackDecoder decoder = new HpackDecoder(4096, 8192); MetaData metaData = decoder.decode(buffer); - assertThat(metaData.getFields().get(HttpHeader.HOST),is( "localhost0")); - assertThat(metaData.getFields().get(HttpHeader.COOKIE),is("abcdefghij")); - assertThat(decoder.getHpackContext().getMaxDynamicTableSize(),is(50)); - assertThat(decoder.getHpackContext().size(),is(1)); - - + assertThat(metaData.getFields().get(HttpHeader.HOST), is("localhost0")); + assertThat(metaData.getFields().get(HttpHeader.COOKIE), is("abcdefghij")); + assertThat(decoder.getHpackContext().getMaxDynamicTableSize(), is(50)); + assertThat(decoder.getHpackContext().size(), is(1)); } @Test @@ -216,7 +212,7 @@ public class HpackDecoderTest Expected: GOAWAY Frame (Error Code: COMPRESSION_ERROR) Connection closed */ - + String encoded = "203f136687A0E41d139d090760881c6490B2Cd39Ba7f20"; ByteBuffer buffer = ByteBuffer.wrap(TypeUtil.fromHexString(encoded)); HpackDecoder decoder = new HpackDecoder(4096, 8192); @@ -225,9 +221,9 @@ public class HpackDecoderTest decoder.decode(buffer); fail(); } - catch(CompressionException e) + catch (CompressionException e) { - assertThat(e.getMessage(),Matchers.containsString("Dynamic table resize after fields")); + assertThat(e.getMessage(), Matchers.containsString("Dynamic table resize after fields")); } } @@ -237,11 +233,11 @@ public class HpackDecoderTest String encoded = "3f610f17FfEc02Df3990A190A0D4Ee5b3d2940Ec98Aa4a62D127D29e273a0aA20dEcAa190a503b262d8a2671D4A2672a927aA874988a2471D05510750c951139EdA2452a3a548cAa1aA90bE4B228342864A9E0D450A5474a92992a1aA513395448E3A0Aa17B96cFe3f3f3f3f3f3f3f3f3f3f3f3f3f3f3f3f3f3f3f3f3f3f3f3f3f3f3f3f3f3f3f3f3f3f3f3f3f3f3f3f3f3f3f3f3f3f3f3f3f3f3f3f3f3f3f3f3f3f3f3f3f3f3f3f3f3f3f3f3f3f3f3f3f3f3f3f3f3f3f3f3f3f3f3f3f3f3f3f3f3f3f3f3f3f3f3f3f3f3f3f3f3f3f3f3f3f3f3f3f3f3f3f3f3f3f3f3f3f3f3f3f3f3f3f3f3f3f3f3f3f3f3f3f3f3f3f14E7Cf9f3e7cF9F3E7Cf9f3e7cF9F3E7Cf9f3e7cF9F3E7Cf9f3e7cF9F3E7Cf9f3e7cF9F3E7Cf9f3e7cF9F3E7Cf9f3e7cF9F3E7Cf9f3e7cF9F3E7Cf9f3e7cF9F3E7Cf9f3e7cF9F3E7Cf9f3e7cF9F3E7Cf9f3e7cF9F3E7Cf9f3e7cF9F3E7Cf9f3e7cF9F3E7Cf9f3e7cF9F3E7Cf9f3e7cF9F3E7Cf9f3e7cF9F353F7F7F7F7F7F7F7F7F7F7F7F7F7F7F7F7F7F7F7F7F7F7F7F7F7F7F7F7F7F7F7F7F7F7F7F7F7F7F7F7F7F7F7F7F7F7F7F7F7F7F7F7F7F7F7F7F7F7F7F7F7F7F7F7F7F7F7F7F7F7F7F7F7F7F7F7F7F7F7F7F7F7F7F7F7F7F7F7F7F7F7F7F7F7F7F7F7F7F7F7F7F7F7F7F7F7F7F7F7F7F7F7F7F7F7F7F7F7F7F7F7F7F7F7F7F7F7F7F7F7F7F7F7F7F7F54f"; ByteBuffer buffer = ByteBuffer.wrap(TypeUtil.fromHexString(encoded)); - HpackDecoder decoder = new HpackDecoder(128,8192); + HpackDecoder decoder = new HpackDecoder(128, 8192); MetaData metaData = decoder.decode(buffer); - assertThat(decoder.getHpackContext().getDynamicTableSize(),is(0)); - assertThat(metaData.getFields().get("host"),Matchers.startsWith("This is a very large field")); + assertThat(decoder.getHpackContext().getDynamicTableSize(), is(0)); + assertThat(metaData.getFields().get("host"), Matchers.startsWith("This is a very large field")); } @Test @@ -250,7 +246,7 @@ public class HpackDecoderTest String encoded = "BE"; ByteBuffer buffer = ByteBuffer.wrap(TypeUtil.fromHexString(encoded)); - HpackDecoder decoder = new HpackDecoder(128,8192); + HpackDecoder decoder = new HpackDecoder(128, 8192); try { @@ -259,64 +255,63 @@ public class HpackDecoderTest } catch (HpackException.SessionException e) { - assertThat(e.getMessage(),Matchers.startsWith("Unknown index")); + assertThat(e.getMessage(), Matchers.startsWith("Unknown index")); } - } - + /* 8.1.2.1. Pseudo-Header Fields */ @Test() public void test8_1_2_1_PsuedoHeaderFields() throws Exception { // 1:Sends a HEADERS frame that contains a unknown pseudo-header field MetaDataBuilder mdb = new MetaDataBuilder(4096); - mdb.emit(new HttpField(":unknown","value")); + mdb.emit(new HttpField(":unknown", "value")); try { mdb.build(); fail(); } - catch(StreamException ex) + catch (StreamException ex) { - assertThat(ex.getMessage(),Matchers.containsString("Unknown pseudo header")); + assertThat(ex.getMessage(), Matchers.containsString("Unknown pseudo header")); } - + // 2: Sends a HEADERS frame that contains the pseudo-header field defined for response mdb = new MetaDataBuilder(4096); - mdb.emit(new HttpField(HttpHeader.C_SCHEME,"http")); - mdb.emit(new HttpField(HttpHeader.C_METHOD,"GET")); - mdb.emit(new HttpField(HttpHeader.C_PATH,"/path")); - mdb.emit(new HttpField(HttpHeader.C_STATUS,"100")); + mdb.emit(new HttpField(HttpHeader.C_SCHEME, "http")); + mdb.emit(new HttpField(HttpHeader.C_METHOD, "GET")); + mdb.emit(new HttpField(HttpHeader.C_PATH, "/path")); + mdb.emit(new HttpField(HttpHeader.C_STATUS, "100")); try { mdb.build(); fail(); } - catch(StreamException ex) + catch (StreamException ex) { - assertThat(ex.getMessage(),Matchers.containsString("Request and Response headers")); + assertThat(ex.getMessage(), Matchers.containsString("Request and Response headers")); } // 3: Sends a HEADERS frame that contains a pseudo-header field as trailers - + // 4: Sends a HEADERS frame that contains a pseudo-header field that appears in a header block after a regular header field mdb = new MetaDataBuilder(4096); - mdb.emit(new HttpField(HttpHeader.C_SCHEME,"http")); - mdb.emit(new HttpField(HttpHeader.C_METHOD,"GET")); - mdb.emit(new HttpField(HttpHeader.C_PATH,"/path")); - mdb.emit(new HttpField("Accept","No Compromise")); - mdb.emit(new HttpField(HttpHeader.C_AUTHORITY,"localhost")); + mdb.emit(new HttpField(HttpHeader.C_SCHEME, "http")); + mdb.emit(new HttpField(HttpHeader.C_METHOD, "GET")); + mdb.emit(new HttpField(HttpHeader.C_PATH, "/path")); + mdb.emit(new HttpField("Accept", "No Compromise")); + mdb.emit(new HttpField(HttpHeader.C_AUTHORITY, "localhost")); try { mdb.build(); fail(); } - catch(StreamException ex) + catch (StreamException ex) { - assertThat(ex.getMessage(),Matchers.containsString("Pseudo header :authority after fields")); + assertThat(ex.getMessage(), Matchers.containsString("Pseudo header :authority after fields")); } } - + @Test() public void test8_1_2_2_ConnectionSpecificHeaderFields() throws Exception { @@ -324,122 +319,115 @@ public class HpackDecoderTest // 1: Sends a HEADERS frame that contains the connection-specific header field mdb = new MetaDataBuilder(4096); - mdb.emit(new HttpField(HttpHeader.CONNECTION,"value")); + mdb.emit(new HttpField(HttpHeader.CONNECTION, "value")); try { mdb.build(); fail(); } - catch(StreamException ex) + catch (StreamException ex) { - assertThat(ex.getMessage(),Matchers.containsString("Connection specific field 'Connection'")); + assertThat(ex.getMessage(), Matchers.containsString("Connection specific field 'Connection'")); } // 2: Sends a HEADERS frame that contains the TE header field with any value other than "trailers" mdb = new MetaDataBuilder(4096); - mdb.emit(new HttpField(HttpHeader.TE,"not_trailers")); + mdb.emit(new HttpField(HttpHeader.TE, "not_trailers")); try { mdb.build(); fail(); } - catch(StreamException ex) + catch (StreamException ex) { - assertThat(ex.getMessage(),Matchers.containsString("Unsupported TE value 'not_trailers'")); + assertThat(ex.getMessage(), Matchers.containsString("Unsupported TE value 'not_trailers'")); } - mdb = new MetaDataBuilder(4096); - mdb.emit(new HttpField(HttpHeader.CONNECTION,"TE")); - mdb.emit(new HttpField(HttpHeader.TE,"trailers")); + mdb.emit(new HttpField(HttpHeader.CONNECTION, "TE")); + mdb.emit(new HttpField(HttpHeader.TE, "trailers")); assertNotNull(mdb.build()); } - @Test() public void test8_1_2_3_RequestPseudoHeaderFields() throws Exception { { - MetaDataBuilder mdb = new MetaDataBuilder( 4096 ); - mdb.emit( new HttpField( HttpHeader.C_METHOD, "GET" ) ); - mdb.emit( new HttpField( HttpHeader.C_SCHEME, "http" ) ); - mdb.emit( new HttpField( HttpHeader.C_AUTHORITY, "localhost:8080" ) ); - mdb.emit( new HttpField( HttpHeader.C_PATH, "/" ) ); - assertThat( mdb.build(), Matchers.instanceOf( MetaData.Request.class ) ); + MetaDataBuilder mdb = new MetaDataBuilder(4096); + mdb.emit(new HttpField(HttpHeader.C_METHOD, "GET")); + mdb.emit(new HttpField(HttpHeader.C_SCHEME, "http")); + mdb.emit(new HttpField(HttpHeader.C_AUTHORITY, "localhost:8080")); + mdb.emit(new HttpField(HttpHeader.C_PATH, "/")); + assertThat(mdb.build(), Matchers.instanceOf(MetaData.Request.class)); } { // 1: Sends a HEADERS frame with empty ":path" pseudo-header field - final MetaDataBuilder mdb = new MetaDataBuilder( 4096 ); - mdb.emit( new HttpField( HttpHeader.C_METHOD, "GET" ) ); - mdb.emit( new HttpField( HttpHeader.C_SCHEME, "http" ) ); - mdb.emit( new HttpField( HttpHeader.C_AUTHORITY, "localhost:8080" ) ); - mdb.emit( new HttpField( HttpHeader.C_PATH, "" ) ); - StreamException ex = assertThrows( StreamException.class, () -> mdb.build() ); - assertThat( ex.getMessage(), Matchers.containsString( "No Path" ) ); - + final MetaDataBuilder mdb = new MetaDataBuilder(4096); + mdb.emit(new HttpField(HttpHeader.C_METHOD, "GET")); + mdb.emit(new HttpField(HttpHeader.C_SCHEME, "http")); + mdb.emit(new HttpField(HttpHeader.C_AUTHORITY, "localhost:8080")); + mdb.emit(new HttpField(HttpHeader.C_PATH, "")); + StreamException ex = assertThrows(StreamException.class, () -> mdb.build()); + assertThat(ex.getMessage(), Matchers.containsString("No Path")); } { // 2: Sends a HEADERS frame that omits ":method" pseudo-header field - final MetaDataBuilder mdb = new MetaDataBuilder( 4096 ); - mdb.emit( new HttpField( HttpHeader.C_SCHEME, "http" ) ); - mdb.emit( new HttpField( HttpHeader.C_AUTHORITY, "localhost:8080" ) ); - mdb.emit( new HttpField( HttpHeader.C_PATH, "/" ) ); - StreamException ex = assertThrows( StreamException.class, () -> mdb.build() ); - assertThat( ex.getMessage(), Matchers.containsString( "No Method" ) ); - + final MetaDataBuilder mdb = new MetaDataBuilder(4096); + mdb.emit(new HttpField(HttpHeader.C_SCHEME, "http")); + mdb.emit(new HttpField(HttpHeader.C_AUTHORITY, "localhost:8080")); + mdb.emit(new HttpField(HttpHeader.C_PATH, "/")); + StreamException ex = assertThrows(StreamException.class, () -> mdb.build()); + assertThat(ex.getMessage(), Matchers.containsString("No Method")); } { // 3: Sends a HEADERS frame that omits ":scheme" pseudo-header field - final MetaDataBuilder mdb = new MetaDataBuilder( 4096 ); - mdb.emit( new HttpField( HttpHeader.C_METHOD, "GET" ) ); - mdb.emit( new HttpField( HttpHeader.C_AUTHORITY, "localhost:8080" ) ); - mdb.emit( new HttpField( HttpHeader.C_PATH, "/" ) ); - StreamException ex = assertThrows( StreamException.class, () -> mdb.build() ); - assertThat( ex.getMessage(), Matchers.containsString( "No Scheme" ) ); - + final MetaDataBuilder mdb = new MetaDataBuilder(4096); + mdb.emit(new HttpField(HttpHeader.C_METHOD, "GET")); + mdb.emit(new HttpField(HttpHeader.C_AUTHORITY, "localhost:8080")); + mdb.emit(new HttpField(HttpHeader.C_PATH, "/")); + StreamException ex = assertThrows(StreamException.class, () -> mdb.build()); + assertThat(ex.getMessage(), Matchers.containsString("No Scheme")); } { // 4: Sends a HEADERS frame that omits ":path" pseudo-header field - final MetaDataBuilder mdb = new MetaDataBuilder( 4096 ); - mdb.emit( new HttpField( HttpHeader.C_METHOD, "GET" ) ); - mdb.emit( new HttpField( HttpHeader.C_SCHEME, "http" ) ); - mdb.emit( new HttpField( HttpHeader.C_AUTHORITY, "localhost:8080" ) ); - StreamException ex = assertThrows( StreamException.class, () -> mdb.build() ); - assertThat( ex.getMessage(), Matchers.containsString( "No Path" ) ); - + final MetaDataBuilder mdb = new MetaDataBuilder(4096); + mdb.emit(new HttpField(HttpHeader.C_METHOD, "GET")); + mdb.emit(new HttpField(HttpHeader.C_SCHEME, "http")); + mdb.emit(new HttpField(HttpHeader.C_AUTHORITY, "localhost:8080")); + StreamException ex = assertThrows(StreamException.class, () -> mdb.build()); + assertThat(ex.getMessage(), Matchers.containsString("No Path")); } { // 5: Sends a HEADERS frame with duplicated ":method" pseudo-header field - final MetaDataBuilder mdb = new MetaDataBuilder( 4096 ); - mdb.emit( new HttpField( HttpHeader.C_METHOD, "GET" ) ); - mdb.emit( new HttpField( HttpHeader.C_METHOD, "GET" ) ); - mdb.emit( new HttpField( HttpHeader.C_SCHEME, "http" ) ); - mdb.emit( new HttpField( HttpHeader.C_AUTHORITY, "localhost:8080" ) ); - mdb.emit( new HttpField( HttpHeader.C_PATH, "/" ) ); - StreamException ex = assertThrows( StreamException.class, () -> mdb.build() ); - assertThat( ex.getMessage(), Matchers.containsString( "Duplicate" ) ); + final MetaDataBuilder mdb = new MetaDataBuilder(4096); + mdb.emit(new HttpField(HttpHeader.C_METHOD, "GET")); + mdb.emit(new HttpField(HttpHeader.C_METHOD, "GET")); + mdb.emit(new HttpField(HttpHeader.C_SCHEME, "http")); + mdb.emit(new HttpField(HttpHeader.C_AUTHORITY, "localhost:8080")); + mdb.emit(new HttpField(HttpHeader.C_PATH, "/")); + StreamException ex = assertThrows(StreamException.class, () -> mdb.build()); + assertThat(ex.getMessage(), Matchers.containsString("Duplicate")); } { // 6: Sends a HEADERS frame with duplicated ":scheme" pseudo-header field - final MetaDataBuilder mdb = new MetaDataBuilder( 4096 ); - mdb.emit( new HttpField( HttpHeader.C_METHOD, "GET" ) ); - mdb.emit( new HttpField( HttpHeader.C_SCHEME, "http" ) ); - mdb.emit( new HttpField( HttpHeader.C_SCHEME, "http" ) ); - mdb.emit( new HttpField( HttpHeader.C_AUTHORITY, "localhost:8080" ) ); - mdb.emit( new HttpField( HttpHeader.C_PATH, "/" ) ); + final MetaDataBuilder mdb = new MetaDataBuilder(4096); + mdb.emit(new HttpField(HttpHeader.C_METHOD, "GET")); + mdb.emit(new HttpField(HttpHeader.C_SCHEME, "http")); + mdb.emit(new HttpField(HttpHeader.C_SCHEME, "http")); + mdb.emit(new HttpField(HttpHeader.C_AUTHORITY, "localhost:8080")); + mdb.emit(new HttpField(HttpHeader.C_PATH, "/")); - StreamException ex = assertThrows( StreamException.class, () -> mdb.build() ); - assertThat( ex.getMessage(), Matchers.containsString( "Duplicate" ) ); + StreamException ex = assertThrows(StreamException.class, () -> mdb.build()); + assertThat(ex.getMessage(), Matchers.containsString("Duplicate")); } } - @Test() public void testHuffmanEncodedStandard() throws Exception { @@ -457,7 +445,6 @@ public class HpackDecoderTest assertFalse(request.iterator().hasNext()); } - /* 5.2.1: Sends a Huffman-encoded string literal representation with padding longer than 7 bits */ @Test() public void testHuffmanEncodedExtraPadding() throws Exception @@ -466,11 +453,10 @@ public class HpackDecoderTest String encoded = "82868441" + "84" + "49509FFF"; ByteBuffer buffer = ByteBuffer.wrap(TypeUtil.fromHexString(encoded)); - CompressionException ex = assertThrows( CompressionException.class, () -> decoder.decode(buffer)); + CompressionException ex = assertThrows(CompressionException.class, () -> decoder.decode(buffer)); assertThat(ex.getMessage(), Matchers.containsString("Bad termination")); } - /* 5.2.2: Sends a Huffman-encoded string literal representation padded by zero */ @Test() public void testHuffmanEncodedZeroPadding() throws Exception @@ -480,12 +466,10 @@ public class HpackDecoderTest String encoded = "82868441" + "83" + "495090"; ByteBuffer buffer = ByteBuffer.wrap(TypeUtil.fromHexString(encoded)); - CompressionException ex = assertThrows( CompressionException.class, () -> decoder.decode(buffer)); + CompressionException ex = assertThrows(CompressionException.class, () -> decoder.decode(buffer)); assertThat(ex.getMessage(), Matchers.containsString("Incorrect padding")); - } - /* 5.2.3: Sends a Huffman-encoded string literal representation containing the EOS symbol */ @Test() public void testHuffmanEncodedWithEOS() throws Exception @@ -495,12 +479,10 @@ public class HpackDecoderTest String encoded = "82868441" + "87" + "497FFFFFFF427F"; ByteBuffer buffer = ByteBuffer.wrap(TypeUtil.fromHexString(encoded)); - CompressionException ex = assertThrows( CompressionException.class, () -> decoder.decode(buffer)); + CompressionException ex = assertThrows(CompressionException.class, () -> decoder.decode(buffer)); assertThat(ex.getMessage(), Matchers.containsString("EOS in content")); - } - @Test() public void testHuffmanEncodedOneIncompleteOctet() throws Exception { @@ -509,12 +491,10 @@ public class HpackDecoderTest String encoded = "82868441" + "81" + "FE"; ByteBuffer buffer = ByteBuffer.wrap(TypeUtil.fromHexString(encoded)); - CompressionException ex = assertThrows( CompressionException.class, () -> decoder.decode(buffer)); + CompressionException ex = assertThrows(CompressionException.class, () -> decoder.decode(buffer)); assertThat(ex.getMessage(), Matchers.containsString("Bad termination")); - } - @Test() public void testHuffmanEncodedTwoIncompleteOctet() throws Exception { @@ -523,9 +503,7 @@ public class HpackDecoderTest String encoded = "82868441" + "82" + "FFFE"; ByteBuffer buffer = ByteBuffer.wrap(TypeUtil.fromHexString(encoded)); - - CompressionException ex = assertThrows( CompressionException.class, () -> decoder.decode(buffer)); + CompressionException ex = assertThrows(CompressionException.class, () -> decoder.decode(buffer)); assertThat(ex.getMessage(), Matchers.containsString("Bad termination")); - } } diff --git a/jetty-http2/http2-hpack/src/test/java/org/eclipse/jetty/http2/hpack/HpackEncoderTest.java b/jetty-http2/http2-hpack/src/test/java/org/eclipse/jetty/http2/hpack/HpackEncoderTest.java index 26e5a464a64..d9a59639950 100644 --- a/jetty-http2/http2-hpack/src/test/java/org/eclipse/jetty/http2/hpack/HpackEncoderTest.java +++ b/jetty-http2/http2-hpack/src/test/java/org/eclipse/jetty/http2/hpack/HpackEncoderTest.java @@ -16,176 +16,169 @@ // ======================================================================== // - package org.eclipse.jetty.http2.hpack; - -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.equalTo; -import static org.junit.jupiter.api.Assertions.assertEquals; - import java.nio.ByteBuffer; import org.eclipse.jetty.http.HttpField; import org.eclipse.jetty.http.HttpFields; -import org.eclipse.jetty.http.HttpHeader; import org.eclipse.jetty.http.HttpVersion; import org.eclipse.jetty.http.MetaData; import org.eclipse.jetty.util.BufferUtil; import org.hamcrest.Matchers; import org.junit.jupiter.api.Test; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.equalTo; +import static org.junit.jupiter.api.Assertions.assertEquals; -/* ------------------------------------------------------------ */ /** + * */ public class HpackEncoderTest { @Test public void testUnknownFieldsContextManagement() { - HpackEncoder encoder = new HpackEncoder(38*5); + HpackEncoder encoder = new HpackEncoder(38 * 5); HttpFields fields = new HttpFields(); - - HttpField[] field = - { - new HttpField("fo0","b0r"), - new HttpField("fo1","b1r"), - new HttpField("fo2","b2r"), - new HttpField("fo3","b3r"), - new HttpField("fo4","b4r"), - new HttpField("fo5","b5r"), - new HttpField("fo6","b6r"), - new HttpField("fo7","b7r"), - new HttpField("fo8","b8r"), - new HttpField("fo9","b9r"), - new HttpField("foA","bAr"), - }; - + HttpField[] field = + { + new HttpField("fo0", "b0r"), + new HttpField("fo1", "b1r"), + new HttpField("fo2", "b2r"), + new HttpField("fo3", "b3r"), + new HttpField("fo4", "b4r"), + new HttpField("fo5", "b5r"), + new HttpField("fo6", "b6r"), + new HttpField("fo7", "b7r"), + new HttpField("fo8", "b8r"), + new HttpField("fo9", "b9r"), + new HttpField("foA", "bAr"), + }; + // Add 4 entries - for (int i=0;i<=3;i++) + for (int i = 0; i <= 3; i++) + { fields.add(field[i]); - + } + // encode them ByteBuffer buffer = BufferUtil.allocate(4096); int pos = BufferUtil.flipToFill(buffer); - encoder.encode(buffer,new MetaData(HttpVersion.HTTP_2,fields)); - BufferUtil.flipToFlush(buffer,pos); - + encoder.encode(buffer, new MetaData(HttpVersion.HTTP_2, fields)); + BufferUtil.flipToFlush(buffer, pos); + // something was encoded! - assertThat(buffer.remaining(),Matchers.greaterThan(0)); - + assertThat(buffer.remaining(), Matchers.greaterThan(0)); + // All are in the dynamic table - assertEquals(4,encoder.getHpackContext().size()); - + assertEquals(4, encoder.getHpackContext().size()); + // encode exact same fields again! BufferUtil.clearToFill(buffer); - encoder.encode(buffer,new MetaData(HttpVersion.HTTP_2,fields)); - BufferUtil.flipToFlush(buffer,0); + encoder.encode(buffer, new MetaData(HttpVersion.HTTP_2, fields)); + BufferUtil.flipToFlush(buffer, 0); // All are in the dynamic table - assertEquals(4,encoder.getHpackContext().size()); - + assertEquals(4, encoder.getHpackContext().size()); + // Add 4 more fields - for (int i=4;i<=7;i++) + for (int i = 4; i <= 7; i++) + { fields.add(field[i]); - + } + // encode BufferUtil.clearToFill(buffer); - encoder.encode(buffer,new MetaData(HttpVersion.HTTP_2,fields)); - BufferUtil.flipToFlush(buffer,0); + encoder.encode(buffer, new MetaData(HttpVersion.HTTP_2, fields)); + BufferUtil.flipToFlush(buffer, 0); // something was encoded! - assertThat(buffer.remaining(),Matchers.greaterThan(0)); + assertThat(buffer.remaining(), Matchers.greaterThan(0)); // max dynamic table size reached - assertEquals(5,encoder.getHpackContext().size()); - - + assertEquals(5, encoder.getHpackContext().size()); + // remove some fields - for (int i=0;i<=7;i+=2) + for (int i = 0; i <= 7; i += 2) + { fields.remove(field[i].getName()); + } // encode BufferUtil.clearToFill(buffer); - encoder.encode(buffer,new MetaData(HttpVersion.HTTP_2,fields)); - BufferUtil.flipToFlush(buffer,0); - + encoder.encode(buffer, new MetaData(HttpVersion.HTTP_2, fields)); + BufferUtil.flipToFlush(buffer, 0); + // something was encoded! - assertThat(buffer.remaining(),Matchers.greaterThan(0)); + assertThat(buffer.remaining(), Matchers.greaterThan(0)); // max dynamic table size reached - assertEquals(5,encoder.getHpackContext().size()); - + assertEquals(5, encoder.getHpackContext().size()); // remove another fields fields.remove(field[1].getName()); // encode BufferUtil.clearToFill(buffer); - encoder.encode(buffer,new MetaData(HttpVersion.HTTP_2,fields)); - BufferUtil.flipToFlush(buffer,0); - + encoder.encode(buffer, new MetaData(HttpVersion.HTTP_2, fields)); + BufferUtil.flipToFlush(buffer, 0); + // something was encoded! - assertThat(buffer.remaining(),Matchers.greaterThan(0)); + assertThat(buffer.remaining(), Matchers.greaterThan(0)); // max dynamic table size reached - assertEquals(5,encoder.getHpackContext().size()); + assertEquals(5, encoder.getHpackContext().size()); - // re add the field fields.add(field[1]); // encode BufferUtil.clearToFill(buffer); - encoder.encode(buffer,new MetaData(HttpVersion.HTTP_2,fields)); - BufferUtil.flipToFlush(buffer,0); - + encoder.encode(buffer, new MetaData(HttpVersion.HTTP_2, fields)); + BufferUtil.flipToFlush(buffer, 0); + // something was encoded! - assertThat(buffer.remaining(),Matchers.greaterThan(0)); + assertThat(buffer.remaining(), Matchers.greaterThan(0)); // max dynamic table size reached - assertEquals(5,encoder.getHpackContext().size()); - + assertEquals(5, encoder.getHpackContext().size()); } - @Test public void testNeverIndexSetCookie() { - HpackEncoder encoder = new HpackEncoder(38*5); + HpackEncoder encoder = new HpackEncoder(38 * 5); ByteBuffer buffer = BufferUtil.allocate(4096); - + HttpFields fields = new HttpFields(); - fields.put("set-cookie","some cookie value"); + fields.put("set-cookie", "some cookie value"); // encode BufferUtil.clearToFill(buffer); - encoder.encode(buffer,new MetaData(HttpVersion.HTTP_2,fields)); - BufferUtil.flipToFlush(buffer,0); - + encoder.encode(buffer, new MetaData(HttpVersion.HTTP_2, fields)); + BufferUtil.flipToFlush(buffer, 0); + // something was encoded! - assertThat(buffer.remaining(),Matchers.greaterThan(0)); - + assertThat(buffer.remaining(), Matchers.greaterThan(0)); + // empty dynamic table - assertEquals(0,encoder.getHpackContext().size()); - + assertEquals(0, encoder.getHpackContext().size()); // encode again BufferUtil.clearToFill(buffer); - encoder.encode(buffer,new MetaData(HttpVersion.HTTP_2,fields)); - BufferUtil.flipToFlush(buffer,0); - + encoder.encode(buffer, new MetaData(HttpVersion.HTTP_2, fields)); + BufferUtil.flipToFlush(buffer, 0); + // something was encoded! - assertThat(buffer.remaining(),Matchers.greaterThan(0)); - + assertThat(buffer.remaining(), Matchers.greaterThan(0)); + // empty dynamic table - assertEquals(0,encoder.getHpackContext().size()); - + assertEquals(0, encoder.getHpackContext().size()); } - @Test public void testFieldLargerThanTable() @@ -195,82 +188,79 @@ public class HpackEncoderTest HpackEncoder encoder = new HpackEncoder(128); ByteBuffer buffer0 = BufferUtil.allocate(4096); int pos = BufferUtil.flipToFill(buffer0); - encoder.encode(buffer0,new MetaData(HttpVersion.HTTP_2,fields)); - BufferUtil.flipToFlush(buffer0,pos); - + encoder.encode(buffer0, new MetaData(HttpVersion.HTTP_2, fields)); + BufferUtil.flipToFlush(buffer0, pos); + encoder = new HpackEncoder(128); - fields.add(new HttpField("user-agent","jetty/test")); + fields.add(new HttpField("user-agent", "jetty/test")); ByteBuffer buffer1 = BufferUtil.allocate(4096); pos = BufferUtil.flipToFill(buffer1); - encoder.encode(buffer1,new MetaData(HttpVersion.HTTP_2,fields)); - BufferUtil.flipToFlush(buffer1,pos); - + encoder.encode(buffer1, new MetaData(HttpVersion.HTTP_2, fields)); + BufferUtil.flipToFlush(buffer1, pos); + encoder = new HpackEncoder(128); fields.add(new HttpField(":path", - "This is a very large field, whose size is larger than the dynamic table so it should not be indexed as it will not fit in the table ever!"+ - "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX "+ - "YYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYY "+ - "ZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZ ")); + "This is a very large field, whose size is larger than the dynamic table so it should not be indexed as it will not fit in the table ever!" + + "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX " + + "YYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYY " + + "ZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZ ")); ByteBuffer buffer2 = BufferUtil.allocate(4096); pos = BufferUtil.flipToFill(buffer2); - encoder.encode(buffer2,new MetaData(HttpVersion.HTTP_2,fields)); - BufferUtil.flipToFlush(buffer2,pos); - + encoder.encode(buffer2, new MetaData(HttpVersion.HTTP_2, fields)); + BufferUtil.flipToFlush(buffer2, pos); + encoder = new HpackEncoder(128); - fields.add(new HttpField("host","somehost")); + fields.add(new HttpField("host", "somehost")); ByteBuffer buffer = BufferUtil.allocate(4096); pos = BufferUtil.flipToFill(buffer); - encoder.encode(buffer,new MetaData(HttpVersion.HTTP_2,fields)); - BufferUtil.flipToFlush(buffer,pos); + encoder.encode(buffer, new MetaData(HttpVersion.HTTP_2, fields)); + BufferUtil.flipToFlush(buffer, pos); //System.err.println(BufferUtil.toHexString(buffer0)); //System.err.println(BufferUtil.toHexString(buffer1)); //System.err.println(BufferUtil.toHexString(buffer2)); //System.err.println(BufferUtil.toHexString(buffer)); - + // something was encoded! - assertThat(buffer.remaining(),Matchers.greaterThan(0)); - + assertThat(buffer.remaining(), Matchers.greaterThan(0)); + // check first field is static index name and dynamic index body - assertThat((buffer.get(buffer0.remaining())&0xFF)>>6,equalTo(1)); - + assertThat((buffer.get(buffer0.remaining()) & 0xFF) >> 6, equalTo(1)); + // check first field is static index name and literal body - assertThat((buffer.get(buffer1.remaining())&0xFF)>>4,equalTo(0)); - + assertThat((buffer.get(buffer1.remaining()) & 0xFF) >> 4, equalTo(0)); + // check first field is static index name and dynamic index body - assertThat((buffer.get(buffer2.remaining())&0xFF)>>6,equalTo(1)); - + assertThat((buffer.get(buffer2.remaining()) & 0xFF) >> 6, equalTo(1)); + // Only first and third fields are put in the table HpackContext context = encoder.getHpackContext(); - assertThat(context.size(),equalTo(2)); - assertThat(context.get(HpackContext.STATIC_SIZE+1).getHttpField().getName(),equalTo("host")); - assertThat(context.get(HpackContext.STATIC_SIZE+2).getHttpField().getName(),equalTo("user-agent")); - assertThat(context.getDynamicTableSize(),equalTo( - context.get(HpackContext.STATIC_SIZE+1).getSize()+context.get(HpackContext.STATIC_SIZE+2).getSize())); - + assertThat(context.size(), equalTo(2)); + assertThat(context.get(HpackContext.STATIC_SIZE + 1).getHttpField().getName(), equalTo("host")); + assertThat(context.get(HpackContext.STATIC_SIZE + 2).getHttpField().getName(), equalTo("user-agent")); + assertThat(context.getDynamicTableSize(), equalTo( + context.get(HpackContext.STATIC_SIZE + 1).getSize() + context.get(HpackContext.STATIC_SIZE + 2).getSize())); } - + @Test public void testResize() { HttpFields fields = new HttpFields(); - fields.add("host", "localhost0"); - fields.add("cookie","abcdefghij"); + fields.add("host", "localhost0"); + fields.add("cookie", "abcdefghij"); HpackEncoder encoder = new HpackEncoder(4096); - + ByteBuffer buffer = BufferUtil.allocate(4096); int pos = BufferUtil.flipToFill(buffer); - encoder.encodeMaxDynamicTableSize(buffer,0); + encoder.encodeMaxDynamicTableSize(buffer, 0); encoder.setRemoteMaxDynamicTableSize(50); - encoder.encode(buffer,new MetaData(HttpVersion.HTTP_2,fields)); - BufferUtil.flipToFlush(buffer,pos); - - HpackContext context = encoder.getHpackContext(); - - assertThat(context.getMaxDynamicTableSize(),Matchers.is(50)); - assertThat(context.size(),Matchers.is(1)); - + encoder.encode(buffer, new MetaData(HttpVersion.HTTP_2, fields)); + BufferUtil.flipToFlush(buffer, pos); + HpackContext context = encoder.getHpackContext(); + + assertThat(context.getMaxDynamicTableSize(), Matchers.is(50)); + assertThat(context.size(), Matchers.is(1)); } } diff --git a/jetty-http2/http2-hpack/src/test/java/org/eclipse/jetty/http2/hpack/HpackPerfTest.java b/jetty-http2/http2-hpack/src/test/java/org/eclipse/jetty/http2/hpack/HpackPerfTest.java index 6b27809a2bd..959a064eafb 100644 --- a/jetty-http2/http2-hpack/src/test/java/org/eclipse/jetty/http2/hpack/HpackPerfTest.java +++ b/jetty-http2/http2-hpack/src/test/java/org/eclipse/jetty/http2/hpack/HpackPerfTest.java @@ -16,7 +16,6 @@ // ======================================================================== // - package org.eclipse.jetty.http2.hpack; import java.io.File; @@ -35,33 +34,31 @@ import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; - public class HpackPerfTest { - int _maxDynamicTableSize=4*1024; + int _maxDynamicTableSize = 4 * 1024; int _unencodedSize; int _encodedSize; - + @BeforeEach public void before() { - _unencodedSize=0; - _encodedSize=0; + _unencodedSize = 0; + _encodedSize = 0; } @AfterEach public void after() - { - System.err.printf("dynamictable=%d unencoded=%d encoded=%d p=%3.1f%%%n",_maxDynamicTableSize,_unencodedSize,_encodedSize,100.0*_encodedSize/_unencodedSize); - + { + System.err.printf("dynamictable=%d unencoded=%d encoded=%d p=%3.1f%%%n", _maxDynamicTableSize, _unencodedSize, _encodedSize, 100.0 * _encodedSize / _unencodedSize); } - + @Test public void simpleTest() throws Exception { runStories(_maxDynamicTableSize); } - + private void runStories(int maxDynamicTableSize) throws Exception { // Find files @@ -74,62 +71,58 @@ public class HpackPerfTest return name.startsWith("story_"); } }); - + // Parse JSON - Map[] stories = new Map[files.length]; - int i=0; + Map[] stories = new Map[files.length]; + int i = 0; for (String story : files) - stories[i++]=(Map)JSON.parse(new FileReader(new File(data,story))); - - ByteBuffer buffer = BufferUtil.allocate(256*1024); - + { + stories[i++] = (Map)JSON.parse(new FileReader(new File(data, story))); + } + + ByteBuffer buffer = BufferUtil.allocate(256 * 1024); + // Encode all the requests - encodeStories(buffer,stories,"request"); + encodeStories(buffer, stories, "request"); // clear table BufferUtil.clearToFill(buffer); - BufferUtil.flipToFlush(buffer,0); - + BufferUtil.flipToFlush(buffer, 0); + // Encode all the responses - encodeStories(buffer,stories,"response"); - + encodeStories(buffer, stories, "response"); } - - private void encodeStories(ByteBuffer buffer,Map[] stories, String type) throws Exception + + private void encodeStories(ByteBuffer buffer, Map[] stories, String type) throws Exception { - for (Map story : stories) + for (Map story : stories) { if (type.equals(story.get("context"))) { - HpackEncoder encoder = new HpackEncoder(_maxDynamicTableSize,_maxDynamicTableSize); - + HpackEncoder encoder = new HpackEncoder(_maxDynamicTableSize, _maxDynamicTableSize); + // System.err.println(story); Object[] cases = (Object[])story.get("cases"); for (Object c : cases) { // System.err.println(" "+c); - Object[] headers = (Object[])((Map)c).get("headers"); + Object[] headers = (Object[])((Map)c).get("headers"); // System.err.println(" "+headers); HttpFields fields = new HttpFields(); - for (Object header:headers) + for (Object header : headers) { - Map h = (Map)header; + Map h = (Map)header; Map.Entry e = h.entrySet().iterator().next(); - fields.add(e.getKey(),e.getValue()); - _unencodedSize+=e.getKey().length()+e.getValue().length(); - + fields.add(e.getKey(), e.getValue()); + _unencodedSize += e.getKey().length() + e.getValue().length(); } BufferUtil.clearToFill(buffer); - encoder.encode(buffer,new MetaData(HttpVersion.HTTP_2,fields)); - BufferUtil.flipToFlush(buffer,0); - _encodedSize+=buffer.remaining(); - + encoder.encode(buffer, new MetaData(HttpVersion.HTTP_2, fields)); + BufferUtil.flipToFlush(buffer, 0); + _encodedSize += buffer.remaining(); } } } - } - - } diff --git a/jetty-http2/http2-hpack/src/test/java/org/eclipse/jetty/http2/hpack/HpackTest.java b/jetty-http2/http2-hpack/src/test/java/org/eclipse/jetty/http2/hpack/HpackTest.java index 6654b285835..7b9218d3585 100644 --- a/jetty-http2/http2-hpack/src/test/java/org/eclipse/jetty/http2/hpack/HpackTest.java +++ b/jetty-http2/http2-hpack/src/test/java/org/eclipse/jetty/http2/hpack/HpackTest.java @@ -38,165 +38,163 @@ import static org.hamcrest.Matchers.is; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.fail; - public class HpackTest { - final static HttpField ServerJetty = new PreEncodedHttpField(HttpHeader.SERVER,"jetty"); - final static HttpField XPowerJetty = new PreEncodedHttpField(HttpHeader.X_POWERED_BY,"jetty"); - final static HttpField Date = new PreEncodedHttpField(HttpHeader.DATE,DateGenerator.formatDate(TimeUnit.NANOSECONDS.toMillis(System.nanoTime()))); - + static final HttpField ServerJetty = new PreEncodedHttpField(HttpHeader.SERVER, "jetty"); + static final HttpField XPowerJetty = new PreEncodedHttpField(HttpHeader.X_POWERED_BY, "jetty"); + static final HttpField Date = new PreEncodedHttpField(HttpHeader.DATE, DateGenerator.formatDate(TimeUnit.NANOSECONDS.toMillis(System.nanoTime()))); + @Test public void encodeDecodeResponseTest() throws Exception { HpackEncoder encoder = new HpackEncoder(); - HpackDecoder decoder = new HpackDecoder(4096,8192); - ByteBuffer buffer = BufferUtil.allocateDirect(16*1024); - + HpackDecoder decoder = new HpackDecoder(4096, 8192); + ByteBuffer buffer = BufferUtil.allocateDirect(16 * 1024); + HttpFields fields0 = new HttpFields(); - fields0.add(HttpHeader.CONTENT_TYPE,"text/html"); - fields0.add(HttpHeader.CONTENT_LENGTH,"1024"); - fields0.add(new HttpField(HttpHeader.CONTENT_ENCODING,(String)null)); + fields0.add(HttpHeader.CONTENT_TYPE, "text/html"); + fields0.add(HttpHeader.CONTENT_LENGTH, "1024"); + fields0.add(new HttpField(HttpHeader.CONTENT_ENCODING, (String)null)); fields0.add(ServerJetty); fields0.add(XPowerJetty); fields0.add(Date); - fields0.add(HttpHeader.SET_COOKIE,"abcdefghijklmnopqrstuvwxyz"); - fields0.add("custom-key","custom-value"); - Response original0 = new MetaData.Response(HttpVersion.HTTP_2,200,fields0); - + fields0.add(HttpHeader.SET_COOKIE, "abcdefghijklmnopqrstuvwxyz"); + fields0.add("custom-key", "custom-value"); + Response original0 = new MetaData.Response(HttpVersion.HTTP_2, 200, fields0); + BufferUtil.clearToFill(buffer); - encoder.encode(buffer,original0); - BufferUtil.flipToFlush(buffer,0); + encoder.encode(buffer, original0); + BufferUtil.flipToFlush(buffer, 0); Response decoded0 = (Response)decoder.decode(buffer); - original0.getFields().put(new HttpField(HttpHeader.CONTENT_ENCODING,"")); - assertMetadataSame(original0,decoded0); - + original0.getFields().put(new HttpField(HttpHeader.CONTENT_ENCODING, "")); + assertMetadataSame(original0, decoded0); + // Same again? BufferUtil.clearToFill(buffer); - encoder.encode(buffer,original0); - BufferUtil.flipToFlush(buffer,0); + encoder.encode(buffer, original0); + BufferUtil.flipToFlush(buffer, 0); Response decoded0b = (Response)decoder.decode(buffer); - assertMetadataSame(original0,decoded0b); + assertMetadataSame(original0, decoded0b); HttpFields fields1 = new HttpFields(); - fields1.add(HttpHeader.CONTENT_TYPE,"text/plain"); - fields1.add(HttpHeader.CONTENT_LENGTH,"1234"); - fields1.add(HttpHeader.CONTENT_ENCODING," "); + fields1.add(HttpHeader.CONTENT_TYPE, "text/plain"); + fields1.add(HttpHeader.CONTENT_LENGTH, "1234"); + fields1.add(HttpHeader.CONTENT_ENCODING, " "); fields1.add(ServerJetty); fields1.add(XPowerJetty); fields1.add(Date); - fields1.add("Custom-Key","Other-Value"); - Response original1 = new MetaData.Response(HttpVersion.HTTP_2,200,fields1); + fields1.add("Custom-Key", "Other-Value"); + Response original1 = new MetaData.Response(HttpVersion.HTTP_2, 200, fields1); // Same again? BufferUtil.clearToFill(buffer); - encoder.encode(buffer,original1); - BufferUtil.flipToFlush(buffer,0); + encoder.encode(buffer, original1); + BufferUtil.flipToFlush(buffer, 0); Response decoded1 = (Response)decoder.decode(buffer); - assertMetadataSame(original1,decoded1); - assertEquals("custom-key",decoded1.getFields().getField("Custom-Key").getName()); + assertMetadataSame(original1, decoded1); + assertEquals("custom-key", decoded1.getFields().getField("Custom-Key").getName()); } - + @Test public void encodeDecodeTooLargeTest() throws Exception { HpackEncoder encoder = new HpackEncoder(); - HpackDecoder decoder = new HpackDecoder(4096,164); - ByteBuffer buffer = BufferUtil.allocateDirect(16*1024); - + HpackDecoder decoder = new HpackDecoder(4096, 164); + ByteBuffer buffer = BufferUtil.allocateDirect(16 * 1024); + HttpFields fields0 = new HttpFields(); - fields0.add("1234567890","1234567890123456789012345678901234567890"); - fields0.add("Cookie","abcdeffhijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQR"); - MetaData original0= new MetaData(HttpVersion.HTTP_2,fields0); - + fields0.add("1234567890", "1234567890123456789012345678901234567890"); + fields0.add("Cookie", "abcdeffhijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQR"); + MetaData original0 = new MetaData(HttpVersion.HTTP_2, fields0); + BufferUtil.clearToFill(buffer); - encoder.encode(buffer,original0); - BufferUtil.flipToFlush(buffer,0); + encoder.encode(buffer, original0); + BufferUtil.flipToFlush(buffer, 0); MetaData decoded0 = (MetaData)decoder.decode(buffer); - assertMetadataSame(original0,decoded0); - + assertMetadataSame(original0, decoded0); + HttpFields fields1 = new HttpFields(); - fields1.add("1234567890","1234567890123456789012345678901234567890"); - fields1.add("Cookie","abcdeffhijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQR"); - fields1.add("x","y"); - MetaData original1 = new MetaData(HttpVersion.HTTP_2,fields1); + fields1.add("1234567890", "1234567890123456789012345678901234567890"); + fields1.add("Cookie", "abcdeffhijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQR"); + fields1.add("x", "y"); + MetaData original1 = new MetaData(HttpVersion.HTTP_2, fields1); BufferUtil.clearToFill(buffer); - encoder.encode(buffer,original1); - BufferUtil.flipToFlush(buffer,0); + encoder.encode(buffer, original1); + BufferUtil.flipToFlush(buffer, 0); try { decoder.decode(buffer); fail(); } - catch(HpackException.SessionException e) + catch (HpackException.SessionException e) { - assertThat(e.getMessage(),containsString("Header too large")); + assertThat(e.getMessage(), containsString("Header too large")); } - } @Test public void evictReferencedFieldTest() throws Exception { - HpackEncoder encoder = new HpackEncoder(200,200); - HpackDecoder decoder = new HpackDecoder(200,1024); - ByteBuffer buffer = BufferUtil.allocateDirect(16*1024); - + HpackEncoder encoder = new HpackEncoder(200, 200); + HpackDecoder decoder = new HpackDecoder(200, 1024); + ByteBuffer buffer = BufferUtil.allocateDirect(16 * 1024); + HttpFields fields0 = new HttpFields(); - fields0.add("123456789012345678901234567890123456788901234567890","value"); - fields0.add("foo","abcdeffhijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQR"); - MetaData original0= new MetaData(HttpVersion.HTTP_2,fields0); + fields0.add("123456789012345678901234567890123456788901234567890", "value"); + fields0.add("foo", "abcdeffhijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQR"); + MetaData original0 = new MetaData(HttpVersion.HTTP_2, fields0); BufferUtil.clearToFill(buffer); - encoder.encode(buffer,original0); - BufferUtil.flipToFlush(buffer,0); + encoder.encode(buffer, original0); + BufferUtil.flipToFlush(buffer, 0); MetaData decoded0 = (MetaData)decoder.decode(buffer); - assertEquals(2,encoder.getHpackContext().size()); - assertEquals(2,decoder.getHpackContext().size()); - assertEquals("123456789012345678901234567890123456788901234567890",encoder.getHpackContext().get(HpackContext.STATIC_TABLE.length+1).getHttpField().getName()); - assertEquals("foo",encoder.getHpackContext().get(HpackContext.STATIC_TABLE.length+0).getHttpField().getName()); - - assertMetadataSame(original0,decoded0); - + assertEquals(2, encoder.getHpackContext().size()); + assertEquals(2, decoder.getHpackContext().size()); + assertEquals("123456789012345678901234567890123456788901234567890", encoder.getHpackContext().get(HpackContext.STATIC_TABLE.length + 1).getHttpField().getName()); + assertEquals("foo", encoder.getHpackContext().get(HpackContext.STATIC_TABLE.length + 0).getHttpField().getName()); + + assertMetadataSame(original0, decoded0); + HttpFields fields1 = new HttpFields(); - fields1.add("123456789012345678901234567890123456788901234567890","other_value"); - fields1.add("x","y"); - MetaData original1 = new MetaData(HttpVersion.HTTP_2,fields1); + fields1.add("123456789012345678901234567890123456788901234567890", "other_value"); + fields1.add("x", "y"); + MetaData original1 = new MetaData(HttpVersion.HTTP_2, fields1); BufferUtil.clearToFill(buffer); - encoder.encode(buffer,original1); - BufferUtil.flipToFlush(buffer,0); + encoder.encode(buffer, original1); + BufferUtil.flipToFlush(buffer, 0); MetaData decoded1 = (MetaData)decoder.decode(buffer); - assertMetadataSame(original1,decoded1); - - assertEquals(2,encoder.getHpackContext().size()); - assertEquals(2,decoder.getHpackContext().size()); - assertEquals("x",encoder.getHpackContext().get(HpackContext.STATIC_TABLE.length+0).getHttpField().getName()); - assertEquals("foo",encoder.getHpackContext().get(HpackContext.STATIC_TABLE.length+1).getHttpField().getName()); + assertMetadataSame(original1, decoded1); + + assertEquals(2, encoder.getHpackContext().size()); + assertEquals(2, decoder.getHpackContext().size()); + assertEquals("x", encoder.getHpackContext().get(HpackContext.STATIC_TABLE.length + 0).getHttpField().getName()); + assertEquals("foo", encoder.getHpackContext().get(HpackContext.STATIC_TABLE.length + 1).getHttpField().getName()); } - + private void assertMetadataSame(MetaData.Response expected, MetaData.Response actual) { assertThat("Response.status", actual.getStatus(), is(expected.getStatus())); assertThat("Response.reason", actual.getReason(), is(expected.getReason())); - assertMetadataSame((MetaData)expected,(MetaData)actual); + assertMetadataSame((MetaData)expected, (MetaData)actual); } private void assertMetadataSame(MetaData expected, MetaData actual) { - assertThat("Metadata.contentLength",actual.getContentLength(),is(expected.getContentLength())); - assertThat("Metadata.version" + ".version", actual.getHttpVersion(),is(expected.getHttpVersion())); - assertHttpFieldsSame("Metadata.fields",expected.getFields(),actual.getFields()); + assertThat("Metadata.contentLength", actual.getContentLength(), is(expected.getContentLength())); + assertThat("Metadata.version" + ".version", actual.getHttpVersion(), is(expected.getHttpVersion())); + assertHttpFieldsSame("Metadata.fields", expected.getFields(), actual.getFields()); } private void assertHttpFieldsSame(String msg, HttpFields expected, HttpFields actual) { assertThat(msg + ".size", actual.size(), is(expected.size())); - + for (HttpField actualField : actual) { if ("DATE".equalsIgnoreCase(actualField.getName())) @@ -205,7 +203,7 @@ public class HpackTest // during testing. continue; } - assertThat(msg + ".contains(" + actualField + ")",expected.contains(actualField),is(true)); + assertThat(msg + ".contains(" + actualField + ")", expected.contains(actualField), is(true)); } } } diff --git a/jetty-http2/http2-hpack/src/test/java/org/eclipse/jetty/http2/hpack/HuffmanTest.java b/jetty-http2/http2-hpack/src/test/java/org/eclipse/jetty/http2/hpack/HuffmanTest.java index 0d6acc0b4c0..802427f1866 100644 --- a/jetty-http2/http2-hpack/src/test/java/org/eclipse/jetty/http2/hpack/HuffmanTest.java +++ b/jetty-http2/http2-hpack/src/test/java/org/eclipse/jetty/http2/hpack/HuffmanTest.java @@ -18,9 +18,6 @@ package org.eclipse.jetty.http2.hpack; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertThrows; - import java.nio.BufferOverflowException; import java.nio.ByteBuffer; import java.util.Locale; @@ -33,54 +30,57 @@ import org.junit.jupiter.params.provider.Arguments; import org.junit.jupiter.params.provider.MethodSource; import org.junit.jupiter.params.provider.ValueSource; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; + public class HuffmanTest { public static Stream data() { return Stream.of( new String[][]{ - {"D.4.1", "f1e3c2e5f23a6ba0ab90f4ff", "www.example.com"}, - {"D.4.2", "a8eb10649cbf", "no-cache"}, - {"D.6.1k", "6402", "302"}, - {"D.6.1v", "aec3771a4b", "private"}, - {"D.6.1d", "d07abe941054d444a8200595040b8166e082a62d1bff", "Mon, 21 Oct 2013 20:13:21 GMT"}, - {"D.6.1l", "9d29ad171863c78f0b97c8e9ae82ae43d3", "https://www.example.com"}, - {"D.6.2te", "640cff", "303"}, - }).map(Arguments::of); + {"D.4.1", "f1e3c2e5f23a6ba0ab90f4ff", "www.example.com"}, + {"D.4.2", "a8eb10649cbf", "no-cache"}, + {"D.6.1k", "6402", "302"}, + {"D.6.1v", "aec3771a4b", "private"}, + {"D.6.1d", "d07abe941054d444a8200595040b8166e082a62d1bff", "Mon, 21 Oct 2013 20:13:21 GMT"}, + {"D.6.1l", "9d29ad171863c78f0b97c8e9ae82ae43d3", "https://www.example.com"}, + {"D.6.2te", "640cff", "303"}, + }).map(Arguments::of); } - @ParameterizedTest(name="[{index}] spec={0}") + @ParameterizedTest(name = "[{index}] spec={0}") @MethodSource("data") public void testDecode(String specSection, String hex, String expected) throws Exception { - byte[] encoded=TypeUtil.fromHexString(hex); - String decoded=Huffman.decode(ByteBuffer.wrap(encoded)); - assertEquals(expected,decoded,specSection); + byte[] encoded = TypeUtil.fromHexString(hex); + String decoded = Huffman.decode(ByteBuffer.wrap(encoded)); + assertEquals(expected, decoded, specSection); } - @ParameterizedTest(name="[{index}] spec={0}") + @ParameterizedTest(name = "[{index}] spec={0}") @MethodSource("data") public void testEncode(String specSection, String hex, String expected) { ByteBuffer buf = BufferUtil.allocate(1024); - int pos=BufferUtil.flipToFill(buf); - Huffman.encode(buf,expected); - BufferUtil.flipToFlush(buf,pos); - String encoded=TypeUtil.toHexString(BufferUtil.toArray(buf)).toLowerCase(Locale.ENGLISH); - assertEquals(hex,encoded,specSection); - assertEquals(hex.length()/2,Huffman.octetsNeeded(expected)); + int pos = BufferUtil.flipToFill(buf); + Huffman.encode(buf, expected); + BufferUtil.flipToFlush(buf, pos); + String encoded = TypeUtil.toHexString(BufferUtil.toArray(buf)).toLowerCase(Locale.ENGLISH); + assertEquals(hex, encoded, specSection); + assertEquals(hex.length() / 2, Huffman.octetsNeeded(expected)); } - @ParameterizedTest(name="[{index}]") // don't include unprintable character in test display-name - @ValueSource(chars = {(char) 128, (char) 0, (char) -1, ' ' - 1}) + @ParameterizedTest(name = "[{index}]") // don't include unprintable character in test display-name + @ValueSource(chars = {(char)128, (char)0, (char)-1, ' ' - 1}) public void testEncode8859Only(char bad) { - String s="bad '"+bad+"'"; + String s = "bad '" + bad + "'"; assertThrows(IllegalArgumentException.class, - () -> Huffman.octetsNeeded(s)); + () -> Huffman.octetsNeeded(s)); assertThrows(BufferOverflowException.class, - () -> Huffman.encode(BufferUtil.allocate(32), s)); + () -> Huffman.encode(BufferUtil.allocate(32), s)); } } diff --git a/jetty-http2/http2-hpack/src/test/java/org/eclipse/jetty/http2/hpack/NBitIntegerTest.java b/jetty-http2/http2-hpack/src/test/java/org/eclipse/jetty/http2/hpack/NBitIntegerTest.java index 1f9c3e63082..1fe8fd60f2f 100644 --- a/jetty-http2/http2-hpack/src/test/java/org/eclipse/jetty/http2/hpack/NBitIntegerTest.java +++ b/jetty-http2/http2-hpack/src/test/java/org/eclipse/jetty/http2/hpack/NBitIntegerTest.java @@ -18,197 +18,187 @@ package org.eclipse.jetty.http2.hpack; -import static org.junit.jupiter.api.Assertions.assertEquals; - import java.nio.ByteBuffer; import org.eclipse.jetty.util.BufferUtil; import org.eclipse.jetty.util.TypeUtil; - import org.junit.jupiter.api.Test; +import static org.junit.jupiter.api.Assertions.assertEquals; + public class NBitIntegerTest { - @Test + @Test public void testOctetsNeeded() { - assertEquals(0,NBitInteger.octectsNeeded(5,10)); - assertEquals(2,NBitInteger.octectsNeeded(5,1337)); - assertEquals(1,NBitInteger.octectsNeeded(8,42)); - assertEquals(3,NBitInteger.octectsNeeded(8,1337)); + assertEquals(0, NBitInteger.octectsNeeded(5, 10)); + assertEquals(2, NBitInteger.octectsNeeded(5, 1337)); + assertEquals(1, NBitInteger.octectsNeeded(8, 42)); + assertEquals(3, NBitInteger.octectsNeeded(8, 1337)); - assertEquals(0,NBitInteger.octectsNeeded(6,62)); - assertEquals(1,NBitInteger.octectsNeeded(6,63)); - assertEquals(1,NBitInteger.octectsNeeded(6,64)); - assertEquals(2,NBitInteger.octectsNeeded(6,63+0x00+0x80*0x01)); - assertEquals(3,NBitInteger.octectsNeeded(6,63+0x00+0x80*0x80)); - assertEquals(4,NBitInteger.octectsNeeded(6,63+0x00+0x80*0x80*0x80)); + assertEquals(0, NBitInteger.octectsNeeded(6, 62)); + assertEquals(1, NBitInteger.octectsNeeded(6, 63)); + assertEquals(1, NBitInteger.octectsNeeded(6, 64)); + assertEquals(2, NBitInteger.octectsNeeded(6, 63 + 0x00 + 0x80 * 0x01)); + assertEquals(3, NBitInteger.octectsNeeded(6, 63 + 0x00 + 0x80 * 0x80)); + assertEquals(4, NBitInteger.octectsNeeded(6, 63 + 0x00 + 0x80 * 0x80 * 0x80)); } @Test public void testEncode() { - testEncode(6,0,"00"); - testEncode(6,1,"01"); - testEncode(6,62,"3e"); - testEncode(6,63,"3f00"); - testEncode(6,63+1,"3f01"); - testEncode(6,63+0x7e,"3f7e"); - testEncode(6,63+0x7f,"3f7f"); - testEncode(6,63+0x00+0x80*0x01,"3f8001"); - testEncode(6,63+0x01+0x80*0x01,"3f8101"); - testEncode(6,63+0x7f+0x80*0x01,"3fFf01"); - testEncode(6,63+0x00+0x80*0x02,"3f8002"); - testEncode(6,63+0x01+0x80*0x02,"3f8102"); - testEncode(6,63+0x7f+0x80*0x7f,"3fFf7f"); - testEncode(6,63+0x00+0x80*0x80, "3f808001"); - testEncode(6,63+0x7f+0x80*0x80*0x7f,"3fFf807f"); - testEncode(6,63+0x00+0x80*0x80*0x80,"3f80808001"); + testEncode(6, 0, "00"); + testEncode(6, 1, "01"); + testEncode(6, 62, "3e"); + testEncode(6, 63, "3f00"); + testEncode(6, 63 + 1, "3f01"); + testEncode(6, 63 + 0x7e, "3f7e"); + testEncode(6, 63 + 0x7f, "3f7f"); + testEncode(6, 63 + 0x00 + 0x80 * 0x01, "3f8001"); + testEncode(6, 63 + 0x01 + 0x80 * 0x01, "3f8101"); + testEncode(6, 63 + 0x7f + 0x80 * 0x01, "3fFf01"); + testEncode(6, 63 + 0x00 + 0x80 * 0x02, "3f8002"); + testEncode(6, 63 + 0x01 + 0x80 * 0x02, "3f8102"); + testEncode(6, 63 + 0x7f + 0x80 * 0x7f, "3fFf7f"); + testEncode(6, 63 + 0x00 + 0x80 * 0x80, "3f808001"); + testEncode(6, 63 + 0x7f + 0x80 * 0x80 * 0x7f, "3fFf807f"); + testEncode(6, 63 + 0x00 + 0x80 * 0x80 * 0x80, "3f80808001"); - testEncode(8,0,"00"); - testEncode(8,1,"01"); - testEncode(8,128,"80"); - testEncode(8,254,"Fe"); - testEncode(8,255,"Ff00"); - testEncode(8,255+1,"Ff01"); - testEncode(8,255+0x7e,"Ff7e"); - testEncode(8,255+0x7f,"Ff7f"); - testEncode(8,255+0x80,"Ff8001"); - testEncode(8,255+0x00+0x80*0x80,"Ff808001"); + testEncode(8, 0, "00"); + testEncode(8, 1, "01"); + testEncode(8, 128, "80"); + testEncode(8, 254, "Fe"); + testEncode(8, 255, "Ff00"); + testEncode(8, 255 + 1, "Ff01"); + testEncode(8, 255 + 0x7e, "Ff7e"); + testEncode(8, 255 + 0x7f, "Ff7f"); + testEncode(8, 255 + 0x80, "Ff8001"); + testEncode(8, 255 + 0x00 + 0x80 * 0x80, "Ff808001"); } - public void testEncode(int n,int i,String expected) + public void testEncode(int n, int i, String expected) { ByteBuffer buf = BufferUtil.allocate(16); - int p=BufferUtil.flipToFill(buf); - if (n<8) + int p = BufferUtil.flipToFill(buf); + if (n < 8) buf.put((byte)0x00); - NBitInteger.encode(buf,n,i); - BufferUtil.flipToFlush(buf,p); - String r=TypeUtil.toHexString(BufferUtil.toArray(buf)); - assertEquals(expected,r); - - assertEquals(expected.length()/2,(n<8?1:0)+NBitInteger.octectsNeeded(n,i)); + NBitInteger.encode(buf, n, i); + BufferUtil.flipToFlush(buf, p); + String r = TypeUtil.toHexString(BufferUtil.toArray(buf)); + assertEquals(expected, r); + + assertEquals(expected.length() / 2, (n < 8 ? 1 : 0) + NBitInteger.octectsNeeded(n, i)); } - + @Test public void testDecode() { - testDecode(6,0,"00"); - testDecode(6,1,"01"); - testDecode(6,62,"3e"); - testDecode(6,63,"3f00"); - testDecode(6,63+1,"3f01"); - testDecode(6,63+0x7e,"3f7e"); - testDecode(6,63+0x7f,"3f7f"); - testDecode(6,63+0x80,"3f8001"); - testDecode(6,63+0x81,"3f8101"); - testDecode(6,63+0x7f+0x80*0x01,"3fFf01"); - testDecode(6,63+0x00+0x80*0x02,"3f8002"); - testDecode(6,63+0x01+0x80*0x02,"3f8102"); - testDecode(6,63+0x7f+0x80*0x7f,"3fFf7f"); - testDecode(6,63+0x00+0x80*0x80, "3f808001"); - testDecode(6,63+0x7f+0x80*0x80*0x7f,"3fFf807f"); - testDecode(6,63+0x00+0x80*0x80*0x80,"3f80808001"); - - testDecode(8,0,"00"); - testDecode(8,1,"01"); - testDecode(8,128,"80"); - testDecode(8,254,"Fe"); - testDecode(8,255,"Ff00"); - testDecode(8,255+1,"Ff01"); - testDecode(8,255+0x7e,"Ff7e"); - testDecode(8,255+0x7f,"Ff7f"); - testDecode(8,255+0x80,"Ff8001"); - testDecode(8,255+0x00+0x80*0x80,"Ff808001"); + testDecode(6, 0, "00"); + testDecode(6, 1, "01"); + testDecode(6, 62, "3e"); + testDecode(6, 63, "3f00"); + testDecode(6, 63 + 1, "3f01"); + testDecode(6, 63 + 0x7e, "3f7e"); + testDecode(6, 63 + 0x7f, "3f7f"); + testDecode(6, 63 + 0x80, "3f8001"); + testDecode(6, 63 + 0x81, "3f8101"); + testDecode(6, 63 + 0x7f + 0x80 * 0x01, "3fFf01"); + testDecode(6, 63 + 0x00 + 0x80 * 0x02, "3f8002"); + testDecode(6, 63 + 0x01 + 0x80 * 0x02, "3f8102"); + testDecode(6, 63 + 0x7f + 0x80 * 0x7f, "3fFf7f"); + testDecode(6, 63 + 0x00 + 0x80 * 0x80, "3f808001"); + testDecode(6, 63 + 0x7f + 0x80 * 0x80 * 0x7f, "3fFf807f"); + testDecode(6, 63 + 0x00 + 0x80 * 0x80 * 0x80, "3f80808001"); + + testDecode(8, 0, "00"); + testDecode(8, 1, "01"); + testDecode(8, 128, "80"); + testDecode(8, 254, "Fe"); + testDecode(8, 255, "Ff00"); + testDecode(8, 255 + 1, "Ff01"); + testDecode(8, 255 + 0x7e, "Ff7e"); + testDecode(8, 255 + 0x7f, "Ff7f"); + testDecode(8, 255 + 0x80, "Ff8001"); + testDecode(8, 255 + 0x00 + 0x80 * 0x80, "Ff808001"); } - - - public void testDecode(int n,int expected,String encoded) + + public void testDecode(int n, int expected, String encoded) { ByteBuffer buf = ByteBuffer.wrap(TypeUtil.fromHexString(encoded)); - buf.position(n==8?0:1); - assertEquals(expected,NBitInteger.decode(buf,n)); + buf.position(n == 8 ? 0 : 1); + assertEquals(expected, NBitInteger.decode(buf, n)); } - + @Test public void testEncodeExampleD_1_1() { ByteBuffer buf = BufferUtil.allocate(16); - int p=BufferUtil.flipToFill(buf); + int p = BufferUtil.flipToFill(buf); buf.put((byte)0x77); buf.put((byte)0xFF); - NBitInteger.encode(buf,5,10); - BufferUtil.flipToFlush(buf,p); - - String r=TypeUtil.toHexString(BufferUtil.toArray(buf)); - - assertEquals("77Ea",r); - + NBitInteger.encode(buf, 5, 10); + BufferUtil.flipToFlush(buf, p); + + String r = TypeUtil.toHexString(BufferUtil.toArray(buf)); + + assertEquals("77Ea", r); } - + @Test public void testDecodeExampleD_1_1() { ByteBuffer buf = ByteBuffer.wrap(TypeUtil.fromHexString("77EaFF")); buf.position(2); - - assertEquals(10,NBitInteger.decode(buf,5)); + + assertEquals(10, NBitInteger.decode(buf, 5)); } - @Test public void testEncodeExampleD_1_2() { ByteBuffer buf = BufferUtil.allocate(16); - int p=BufferUtil.flipToFill(buf); + int p = BufferUtil.flipToFill(buf); buf.put((byte)0x88); buf.put((byte)0x00); - NBitInteger.encode(buf,5,1337); - BufferUtil.flipToFlush(buf,p); - - String r=TypeUtil.toHexString(BufferUtil.toArray(buf)); - - assertEquals("881f9a0a",r); - + NBitInteger.encode(buf, 5, 1337); + BufferUtil.flipToFlush(buf, p); + + String r = TypeUtil.toHexString(BufferUtil.toArray(buf)); + + assertEquals("881f9a0a", r); } - + @Test public void testDecodeExampleD_1_2() { ByteBuffer buf = ByteBuffer.wrap(TypeUtil.fromHexString("881f9a0aff")); buf.position(2); - - assertEquals(1337,NBitInteger.decode(buf,5)); + + assertEquals(1337, NBitInteger.decode(buf, 5)); } - - + @Test public void testEncodeExampleD_1_3() { ByteBuffer buf = BufferUtil.allocate(16); - int p=BufferUtil.flipToFill(buf); + int p = BufferUtil.flipToFill(buf); buf.put((byte)0x88); buf.put((byte)0xFF); - NBitInteger.encode(buf,8,42); - BufferUtil.flipToFlush(buf,p); - - String r=TypeUtil.toHexString(BufferUtil.toArray(buf)); - - assertEquals("88Ff2a",r); - + NBitInteger.encode(buf, 8, 42); + BufferUtil.flipToFlush(buf, p); + + String r = TypeUtil.toHexString(BufferUtil.toArray(buf)); + + assertEquals("88Ff2a", r); } - @Test public void testDecodeExampleD_1_3() { ByteBuffer buf = ByteBuffer.wrap(TypeUtil.fromHexString("882aFf")); buf.position(1); - - assertEquals(42,NBitInteger.decode(buf,8)); - } - + assertEquals(42, NBitInteger.decode(buf, 8)); + } } diff --git a/jetty-http2/http2-http-client-transport/pom.xml b/jetty-http2/http2-http-client-transport/pom.xml index 59677412682..da589baa10d 100644 --- a/jetty-http2/http2-http-client-transport/pom.xml +++ b/jetty-http2/http2-http-client-transport/pom.xml @@ -1,6 +1,5 @@ - + org.eclipse.jetty.http2 http2-parent @@ -21,9 +20,7 @@ maven-surefire-plugin - @{argLine} ${jetty.surefire.argLine} - --add-reads org.eclipse.jetty.http2.http.client.transport=jetty.servlet.api - --add-modules jetty.servlet.api + @{argLine} ${jetty.surefire.argLine} --add-reads org.eclipse.jetty.http2.http.client.transport=jetty.servlet.api --add-modules jetty.servlet.api diff --git a/jetty-http2/http2-http-client-transport/src/main/java/org/eclipse/jetty/http2/client/http/HttpChannelOverHTTP2.java b/jetty-http2/http2-http-client-transport/src/main/java/org/eclipse/jetty/http2/client/http/HttpChannelOverHTTP2.java index 690b25474c5..3373e5a1401 100644 --- a/jetty-http2/http2-http-client-transport/src/main/java/org/eclipse/jetty/http2/client/http/HttpChannelOverHTTP2.java +++ b/jetty-http2/http2-http-client-transport/src/main/java/org/eclipse/jetty/http2/client/http/HttpChannelOverHTTP2.java @@ -129,9 +129,9 @@ public class HttpChannelOverHTTP2 extends HttpChannel public String toString() { return String.format("%s[send=%s,recv=%s]", - super.toString(), - sender, - receiver); + super.toString(), + sender, + receiver); } private class ReleaseCallback implements Callback diff --git a/jetty-http2/http2-http-client-transport/src/main/java/org/eclipse/jetty/http2/client/http/HttpConnectionOverHTTP2.java b/jetty-http2/http2-http-client-transport/src/main/java/org/eclipse/jetty/http2/client/http/HttpConnectionOverHTTP2.java index 19f8151c2c3..34da1e8feae 100644 --- a/jetty-http2/http2-http-client-transport/src/main/java/org/eclipse/jetty/http2/client/http/HttpConnectionOverHTTP2.java +++ b/jetty-http2/http2-http-client-transport/src/main/java/org/eclipse/jetty/http2/client/http/HttpConnectionOverHTTP2.java @@ -153,9 +153,9 @@ public class HttpConnectionOverHTTP2 extends HttpConnection implements Sweeper.S abort(failure); session.close(ErrorCode.NO_ERROR.code, failure.getMessage(), Callback.NOOP); - + HttpChannel channel = idleChannels.poll(); - while (channel!=null) + while (channel != null) { channel.destroy(); channel = idleChannels.poll(); @@ -179,7 +179,7 @@ public class HttpConnectionOverHTTP2 extends HttpConnection implements Sweeper.S } activeChannels.clear(); HttpChannel channel = idleChannels.poll(); - while (channel!=null) + while (channel != null) { channel.destroy(); channel = idleChannels.poll(); @@ -200,9 +200,9 @@ public class HttpConnectionOverHTTP2 extends HttpConnection implements Sweeper.S public String toString() { return String.format("%s@%x(closed=%b)[%s]", - getClass().getSimpleName(), - hashCode(), - isClosed(), - session); + getClass().getSimpleName(), + hashCode(), + isClosed(), + session); } } diff --git a/jetty-http2/http2-http-client-transport/src/test/java/org/eclipse/jetty/http2/client/http/DirectHTTP2OverTLSTest.java b/jetty-http2/http2-http-client-transport/src/test/java/org/eclipse/jetty/http2/client/http/DirectHTTP2OverTLSTest.java index bb34c209727..a0225ae4cd4 100644 --- a/jetty-http2/http2-http-client-transport/src/test/java/org/eclipse/jetty/http2/client/http/DirectHTTP2OverTLSTest.java +++ b/jetty-http2/http2-http-client-transport/src/test/java/org/eclipse/jetty/http2/client/http/DirectHTTP2OverTLSTest.java @@ -19,7 +19,6 @@ package org.eclipse.jetty.http2.client.http; import java.util.concurrent.TimeUnit; - import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; @@ -134,9 +133,9 @@ public class DirectHTTP2OverTLSTest }); ContentResponse response = client.newRequest("localhost", connector.getLocalPort()) - .scheme(HttpScheme.HTTPS.asString()) - .timeout(5, TimeUnit.SECONDS) - .send(); + .scheme(HttpScheme.HTTPS.asString()) + .timeout(5, TimeUnit.SECONDS) + .send(); assertEquals(HttpStatus.OK_200, response.getStatus()); } diff --git a/jetty-http2/http2-http-client-transport/src/test/java/org/eclipse/jetty/http2/client/http/EmptyServerHandler.java b/jetty-http2/http2-http-client-transport/src/test/java/org/eclipse/jetty/http2/client/http/EmptyServerHandler.java index 84d46744d0b..595f77ca933 100644 --- a/jetty-http2/http2-http-client-transport/src/test/java/org/eclipse/jetty/http2/client/http/EmptyServerHandler.java +++ b/jetty-http2/http2-http-client-transport/src/test/java/org/eclipse/jetty/http2/client/http/EmptyServerHandler.java @@ -19,7 +19,6 @@ package org.eclipse.jetty.http2.client.http; import java.io.IOException; - import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; diff --git a/jetty-http2/http2-http-client-transport/src/test/java/org/eclipse/jetty/http2/client/http/HttpClientTransportOverHTTP2Test.java b/jetty-http2/http2-http-client-transport/src/test/java/org/eclipse/jetty/http2/client/http/HttpClientTransportOverHTTP2Test.java index 34ee90517f8..32ccb0701cc 100644 --- a/jetty-http2/http2-http-client-transport/src/test/java/org/eclipse/jetty/http2/client/http/HttpClientTransportOverHTTP2Test.java +++ b/jetty-http2/http2-http-client-transport/src/test/java/org/eclipse/jetty/http2/client/http/HttpClientTransportOverHTTP2Test.java @@ -37,7 +37,6 @@ import java.util.concurrent.TimeoutException; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicReference; import java.util.function.UnaryOperator; - import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; @@ -133,7 +132,7 @@ public class HttpClientTransportOverHTTP2Test extends AbstractTest }); assertThrows(ExecutionException.class, () -> - client.newRequest("localhost", connector.getLocalPort()) + client.newRequest("localhost", connector.getLocalPort()) .onRequestCommit(request -> request.abort(new Exception("explicitly_aborted_by_test"))) .send()); assertTrue(resetLatch.await(5, TimeUnit.SECONDS)); @@ -171,7 +170,7 @@ public class HttpClientTransportOverHTTP2Test extends AbstractTest }); assertThrows(ExecutionException.class, () -> - client.newRequest("localhost", connector.getLocalPort()) + client.newRequest("localhost", connector.getLocalPort()) .onResponseContent((response, buffer) -> response.abort(new Exception("explicitly_aborted_by_test"))) .send()); assertTrue(resetLatch.await(5, TimeUnit.SECONDS)); @@ -192,12 +191,12 @@ public class HttpClientTransportOverHTTP2Test extends AbstractTest }); ContentResponse response = client.newRequest("localhost", connector.getLocalPort()) - .onRequestBegin(request -> - { - if (request.getVersion() != HttpVersion.HTTP_2) - request.abort(new Exception("Not a HTTP/2 request")); - }) - .send(); + .onRequestBegin(request -> + { + if (request.getVersion() != HttpVersion.HTTP_2) + request.abort(new Exception("Not a HTTP/2 request")); + }) + .send(); assertEquals(HttpStatus.OK_200, response.getStatus()); } @@ -279,14 +278,14 @@ public class HttpClientTransportOverHTTP2Test extends AbstractTest // Prime the connection to allow client and server prefaces to be exchanged. ContentResponse response = client.newRequest("localhost", connector.getLocalPort()) - .path("/zero") - .timeout(5, TimeUnit.SECONDS) - .send(); + .path("/zero") + .timeout(5, TimeUnit.SECONDS) + .send(); assertEquals(HttpStatus.OK_200, response.getStatus()); org.eclipse.jetty.client.api.Request request = client.newRequest("localhost", connector.getLocalPort()) - .method(HttpMethod.HEAD) - .path("/one"); + .method(HttpMethod.HEAD) + .path("/one"); request.send(result -> { if (result.isFailed()) @@ -318,9 +317,9 @@ public class HttpClientTransportOverHTTP2Test extends AbstractTest }); ContentResponse response = client.newRequest("localhost", connector.getLocalPort()) - .path("http://localhost:" + connector.getLocalPort() + path + "?" + query) - .timeout(5, TimeUnit.SECONDS) - .send(); + .path("http://localhost:" + connector.getLocalPort() + path + "?" + query) + .timeout(5, TimeUnit.SECONDS) + .send(); assertEquals(HttpStatus.OK_200, response.getStatus()); } @@ -346,9 +345,9 @@ public class HttpClientTransportOverHTTP2Test extends AbstractTest int serverPort = proxyPort + 1; // Any port will do, just not the same as the proxy. ContentResponse response = client.newRequest("localhost", serverPort) - .path(path + "?" + query) - .timeout(5, TimeUnit.SECONDS) - .send(); + .path(path + "?" + query) + .timeout(5, TimeUnit.SECONDS) + .send(); assertEquals(HttpStatus.OK_200, response.getStatus()); } @@ -379,7 +378,7 @@ public class HttpClientTransportOverHTTP2Test extends AbstractTest client.start(); assertThrows(TimeoutException.class, () -> - client.newRequest("localhost", connector.getLocalPort()) + client.newRequest("localhost", connector.getLocalPort()) // Make sure the connection idle times out, not the stream. .idleTimeout(2 * idleTimeout, TimeUnit.MILLISECONDS) .send()); @@ -407,11 +406,12 @@ public class HttpClientTransportOverHTTP2Test extends AbstractTest } }); - assertThrows(TimeoutException.class, ()->{ + assertThrows(TimeoutException.class, () -> + { long idleTimeout = 1000; client.newRequest("localhost", connector.getLocalPort()) - .idleTimeout(idleTimeout, TimeUnit.MILLISECONDS) - .send(); + .idleTimeout(idleTimeout, TimeUnit.MILLISECONDS) + .send(); }); assertTrue(resetLatch.await(5, TimeUnit.SECONDS)); @@ -440,11 +440,11 @@ public class HttpClientTransportOverHTTP2Test extends AbstractTest CountDownLatch resultLatch = new CountDownLatch(1); client.newRequest("localhost", server.getLocalPort()) - .send(result -> - { - if (result.getResponse().getStatus() == HttpStatus.OK_200) - resultLatch.countDown(); - }); + .send(result -> + { + if (result.getResponse().getStatus() == HttpStatus.OK_200) + resultLatch.countDown(); + }); ByteBufferPool byteBufferPool = new MappedByteBufferPool(); ByteBufferPool.Lease lease = new ByteBufferPool.Lease(byteBufferPool); @@ -484,7 +484,9 @@ public class HttpClientTransportOverHTTP2Test extends AbstractTest { // Write the frames. for (ByteBuffer buffer : lease.getByteBuffers()) + { output.write(BufferUtil.toArray(buffer)); + } lease.recycle(); } catch (Throwable x) @@ -549,15 +551,14 @@ public class HttpClientTransportOverHTTP2Test extends AbstractTest }); ContentResponse response = client.newRequest("localhost", connector.getLocalPort()) - .timeout(5, TimeUnit.SECONDS) - .send(); + .timeout(5, TimeUnit.SECONDS) + .send(); assertEquals(HttpStatus.NO_CONTENT_204, response.getStatus()); // No logic on the client to discard content for no-content status codes. assertArrayEquals(bytes, response.getContent()); } - @Test public void testInvalidResponseHPack() throws Exception { @@ -582,12 +583,12 @@ public class HttpClientTransportOverHTTP2Test extends AbstractTest CountDownLatch latch = new CountDownLatch(1); client.newRequest("localhost", connector.getLocalPort()) - .timeout(5, TimeUnit.SECONDS) - .send(result -> - { - if (result.isFailed()) - latch.countDown(); - }); + .timeout(5, TimeUnit.SECONDS) + .send(result -> + { + if (result.isFailed()) + latch.countDown(); + }); assertTrue(latch.await(5, TimeUnit.SECONDS)); } diff --git a/jetty-http2/http2-http-client-transport/src/test/java/org/eclipse/jetty/http2/client/http/MaxConcurrentStreamsTest.java b/jetty-http2/http2-http-client-transport/src/test/java/org/eclipse/jetty/http2/client/http/MaxConcurrentStreamsTest.java index 4a0c29691c7..9dd125b626a 100644 --- a/jetty-http2/http2-http-client-transport/src/test/java/org/eclipse/jetty/http2/client/http/MaxConcurrentStreamsTest.java +++ b/jetty-http2/http2-http-client-transport/src/test/java/org/eclipse/jetty/http2/client/http/MaxConcurrentStreamsTest.java @@ -30,7 +30,6 @@ import java.util.concurrent.ForkJoinPool; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; import java.util.stream.IntStream; - import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; @@ -62,7 +61,6 @@ import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertTrue; - public class MaxConcurrentStreamsTest extends AbstractTest { private void start(int maxConcurrentStreams, Handler handler) throws Exception @@ -102,21 +100,21 @@ public class MaxConcurrentStreamsTest extends AbstractTest // First request is sent immediately. client.newRequest("localhost", connector.getLocalPort()) - .path("/first") - .send(result -> - { - if (result.isSucceeded()) - latch.countDown(); - }); + .path("/first") + .send(result -> + { + if (result.isSucceeded()) + latch.countDown(); + }); // Second request is queued. client.newRequest("localhost", connector.getLocalPort()) - .path("/second") - .send(result -> - { - if (result.isSucceeded()) - latch.countDown(); - }); + .path("/second") + .send(result -> + { + if (result.isSucceeded()) + latch.countDown(); + }); // When the first request returns, the second must be sent. assertTrue(latch.await(5 * sleep, TimeUnit.MILLISECONDS)); @@ -130,21 +128,21 @@ public class MaxConcurrentStreamsTest extends AbstractTest int iterations = 50; IntStream.range(0, concurrency).parallel().forEach(i -> - IntStream.range(0, iterations).forEach(j -> + IntStream.range(0, iterations).forEach(j -> + { + try { - try - { - ContentResponse response = client.newRequest("localhost", connector.getLocalPort()) - .path("/" + i + "_" + j) - .timeout(5, TimeUnit.SECONDS) - .send(); - assertEquals(HttpStatus.OK_200, response.getStatus()); - } - catch (Throwable x) - { - throw new RuntimeException(x); - } - }) + ContentResponse response = client.newRequest("localhost", connector.getLocalPort()) + .path("/" + i + "_" + j) + .timeout(5, TimeUnit.SECONDS) + .send(); + assertEquals(HttpStatus.OK_200, response.getStatus()); + } + catch (Throwable x) + { + throw new RuntimeException(x); + } + }) ); } @@ -185,22 +183,22 @@ public class MaxConcurrentStreamsTest extends AbstractTest if (connections.incrementAndGet() == 1) { client.newRequest(host, port) - .path("/2") - .send(result -> + .path("/2") + .send(result -> + { + if (result.isSucceeded()) { - if (result.isSucceeded()) - { - Response response2 = result.getResponse(); - if (response2.getStatus() == HttpStatus.OK_200) - latch.countDown(); - else - failures.add(new HttpResponseException("", response2)); - } + Response response2 = result.getResponse(); + if (response2.getStatus() == HttpStatus.OK_200) + latch.countDown(); else - { - failures.add(result.getFailure()); - } - }); + failures.add(new HttpResponseException("", response2)); + } + else + { + failures.add(result.getFailure()); + } + }); } super.onSettings(session, frame); } @@ -215,9 +213,9 @@ public class MaxConcurrentStreamsTest extends AbstractTest // This request will be queued and establish the connection, // which will trigger the send of the second request. ContentResponse response1 = client.newRequest(host, port) - .path("/1") - .timeout(5, TimeUnit.SECONDS) - .send(); + .path("/1") + .timeout(5, TimeUnit.SECONDS) + .send(); assertEquals(HttpStatus.OK_200, response1.getStatus()); assertTrue(latch.await(5, TimeUnit.SECONDS), failures.toString()); @@ -248,20 +246,20 @@ public class MaxConcurrentStreamsTest extends AbstractTest for (int i = 0; i < maxStreams; ++i) { client.newRequest("localhost", connector.getLocalPort()) - .path("/" + i) - .send(null); + .path("/" + i) + .send(null); } // Send the request in excess. CountDownLatch latch = new CountDownLatch(1); String path = "/excess"; client.newRequest("localhost", connector.getLocalPort()) - .path(path) - .send(result -> - { - if (result.getResponse().getStatus() == HttpStatus.OK_200) - latch.countDown(); - }); + .path(path) + .send(result -> + { + if (result.getResponse().getStatus() == HttpStatus.OK_200) + latch.countDown(); + }); // The last exchange should remain in the queue. HttpDestination destination = (HttpDestination)client.getDestination("http", "localhost", connector.getLocalPort()); @@ -289,9 +287,9 @@ public class MaxConcurrentStreamsTest extends AbstractTest // Send a request that is aborted while queued. client.newRequest("localhost", connector.getLocalPort()) - .path("/aborted") - .onRequestQueued(request -> request.abort(new Exception())) - .send(null); + .path("/aborted") + .onRequestQueued(request -> request.abort(new Exception())) + .send(null); // Must be able to send another request. ContentResponse response = client.newRequest("localhost", connector.getLocalPort()).path("/check").send(); @@ -319,8 +317,8 @@ public class MaxConcurrentStreamsTest extends AbstractTest for (int i = 0; i < maxConcurrent; ++i) { client.newRequest("localhost", connector.getLocalPort()) - .path("/" + i) - .send(result -> latch.countDown()); + .path("/" + i) + .send(result -> latch.countDown()); } // The requests should be processed in parallel, not sequentially. @@ -356,14 +354,14 @@ public class MaxConcurrentStreamsTest extends AbstractTest for (int k = 0; k < iterations; ++k) { client.newRequest("localhost", connector.getLocalPort()) - .path("/" + i + "_" + j + "_" + k) - .send(result -> - { - if (result.isFailed()) - failures.offer(result); - latch.countDown(); - }); - } + .path("/" + i + "_" + j + "_" + k) + .send(result -> + { + if (result.isFailed()) + failures.offer(result); + latch.countDown(); + }); + } }))); assertTrue(latch.await(total * 10, TimeUnit.MILLISECONDS)); @@ -387,17 +385,17 @@ public class MaxConcurrentStreamsTest extends AbstractTest CountDownLatch latch = new CountDownLatch(1); client.newRequest("localhost", connector.getLocalPort()) - .path("/1") - .timeout(timeout, TimeUnit.MILLISECONDS) - .send(result -> - { - if (result.isFailed()) - latch.countDown(); - }); + .path("/1") + .timeout(timeout, TimeUnit.MILLISECONDS) + .send(result -> + { + if (result.isFailed()) + latch.countDown(); + }); ContentResponse response2 = client.newRequest("localhost", connector.getLocalPort()) - .path("/2") - .send(); + .path("/2") + .send(); assertEquals(HttpStatus.OK_200, response2.getStatus()); assertTrue(latch.await(2 * timeout, TimeUnit.MILLISECONDS)); diff --git a/jetty-http2/http2-http-client-transport/src/test/java/org/eclipse/jetty/http2/client/http/PushedResourcesTest.java b/jetty-http2/http2-http-client-transport/src/test/java/org/eclipse/jetty/http2/client/http/PushedResourcesTest.java index c2b89f2e089..9f7622aec6c 100644 --- a/jetty-http2/http2-http-client-transport/src/test/java/org/eclipse/jetty/http2/client/http/PushedResourcesTest.java +++ b/jetty-http2/http2-http-client-transport/src/test/java/org/eclipse/jetty/http2/client/http/PushedResourcesTest.java @@ -22,7 +22,6 @@ import java.io.IOException; import java.util.Random; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; - import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; @@ -88,9 +87,9 @@ public class PushedResourcesTest extends AbstractTest HttpRequest request = (HttpRequest)client.newRequest("localhost", connector.getLocalPort()); ContentResponse response = request - .pushListener((mainRequest, pushedRequest) -> null) - .timeout(5, TimeUnit.SECONDS) - .send(); + .pushListener((mainRequest, pushedRequest) -> null) + .timeout(5, TimeUnit.SECONDS) + .send(); assertEquals(HttpStatus.OK_200, response.getStatus()); assertTrue(latch.await(5, TimeUnit.SECONDS)); @@ -126,11 +125,11 @@ public class PushedResourcesTest extends AbstractTest else { baseRequest.newPushBuilder() - .path(path1) - .push(); + .path(path1) + .push(); baseRequest.newPushBuilder() - .path(path2) - .push(); + .path(path2) + .push(); response.getOutputStream().write(bytes); } } @@ -140,26 +139,26 @@ public class PushedResourcesTest extends AbstractTest CountDownLatch latch2 = new CountDownLatch(1); HttpRequest request = (HttpRequest)client.newRequest("localhost", connector.getLocalPort()); ContentResponse response = request - .pushListener((mainRequest, pushedRequest) -> new BufferingResponseListener() + .pushListener((mainRequest, pushedRequest) -> new BufferingResponseListener() + { + @Override + public void onComplete(Result result) { - @Override - public void onComplete(Result result) + assertTrue(result.isSucceeded()); + if (pushedRequest.getPath().equals(path1)) { - assertTrue(result.isSucceeded()); - if (pushedRequest.getPath().equals(path1)) - { - assertArrayEquals(pushBytes1, getContent()); - latch1.countDown(); - } - else if (pushedRequest.getPath().equals(path2)) - { - assertArrayEquals(pushBytes2, getContent()); - latch2.countDown(); - } + assertArrayEquals(pushBytes1, getContent()); + latch1.countDown(); } - }) - .timeout(5, TimeUnit.SECONDS) - .send(); + else if (pushedRequest.getPath().equals(path2)) + { + assertArrayEquals(pushBytes2, getContent()); + latch2.countDown(); + } + } + }) + .timeout(5, TimeUnit.SECONDS) + .send(); assertEquals(HttpStatus.OK_200, response.getStatus()); assertArrayEquals(bytes, response.getContent()); @@ -194,20 +193,20 @@ public class PushedResourcesTest extends AbstractTest CountDownLatch latch = new CountDownLatch(1); HttpRequest request = (HttpRequest)client.newRequest("localhost", connector.getLocalPort()); ContentResponse response = request - .pushListener((mainRequest, pushedRequest) -> new BufferingResponseListener() + .pushListener((mainRequest, pushedRequest) -> new BufferingResponseListener() + { + @Override + public void onComplete(Result result) { - @Override - public void onComplete(Result result) - { - assertTrue(result.isSucceeded()); - assertEquals(oldPath, pushedRequest.getPath()); - assertEquals(newPath, result.getRequest().getPath()); - assertArrayEquals(pushBytes, getContent()); - latch.countDown(); - } - }) - .timeout(5, TimeUnit.SECONDS) - .send(); + assertTrue(result.isSucceeded()); + assertEquals(oldPath, pushedRequest.getPath()); + assertEquals(newPath, result.getRequest().getPath()); + assertArrayEquals(pushBytes, getContent()); + latch.countDown(); + } + }) + .timeout(5, TimeUnit.SECONDS) + .send(); assertEquals(HttpStatus.OK_200, response.getStatus()); assertTrue(latch.await(5, TimeUnit.SECONDS)); diff --git a/jetty-http2/http2-server/pom.xml b/jetty-http2/http2-server/pom.xml index 8d7b290c60d..702a6204ab0 100644 --- a/jetty-http2/http2-server/pom.xml +++ b/jetty-http2/http2-server/pom.xml @@ -1,6 +1,5 @@ - + org.eclipse.jetty.http2 http2-parent @@ -21,9 +20,7 @@ maven-surefire-plugin - @{argLine} ${jetty.surefire.argLine} - --add-reads org.eclipse.jetty.http2.server=jetty.servlet.api - --add-modules jetty.servlet.api + @{argLine} ${jetty.surefire.argLine} --add-reads org.eclipse.jetty.http2.server=jetty.servlet.api --add-modules jetty.servlet.api diff --git a/jetty-http2/http2-server/src/main/java/org/eclipse/jetty/http2/server/AbstractHTTP2ServerConnectionFactory.java b/jetty-http2/http2-server/src/main/java/org/eclipse/jetty/http2/server/AbstractHTTP2ServerConnectionFactory.java index 703c48fd06e..a7492e814f8 100644 --- a/jetty-http2/http2-server/src/main/java/org/eclipse/jetty/http2/server/AbstractHTTP2ServerConnectionFactory.java +++ b/jetty-http2/http2-server/src/main/java/org/eclipse/jetty/http2/server/AbstractHTTP2ServerConnectionFactory.java @@ -63,15 +63,17 @@ public abstract class AbstractHTTP2ServerConnectionFactory extends AbstractConne public AbstractHTTP2ServerConnectionFactory(@Name("config") HttpConfiguration httpConfiguration) { - this(httpConfiguration,"h2"); + this(httpConfiguration, "h2"); } protected AbstractHTTP2ServerConnectionFactory(@Name("config") HttpConfiguration httpConfiguration, @Name("protocols") String... protocols) { super(protocols); - for (String p:protocols) + for (String p : protocols) + { if (!HTTP2ServerConnection.isSupportedProtocol(p)) - throw new IllegalArgumentException("Unsupported HTTP2 Protocol variant: "+p); + throw new IllegalArgumentException("Unsupported HTTP2 Protocol variant: " + p); + } addBean(sessionContainer); this.httpConfiguration = Objects.requireNonNull(httpConfiguration); addBean(httpConfiguration); @@ -219,7 +221,7 @@ public abstract class AbstractHTTP2ServerConnectionFactory extends AbstractConne parser.setMaxSettingsKeys(getMaxSettingsKeys()); HTTP2Connection connection = new HTTP2ServerConnection(connector.getByteBufferPool(), connector.getExecutor(), - endPoint, httpConfiguration, parser, session, getInputBufferSize(), listener); + endPoint, httpConfiguration, parser, session, getInputBufferSize(), listener); connection.addListener(sessionContainer); return configure(connection, connector, endPoint); } @@ -272,7 +274,7 @@ public abstract class AbstractHTTP2ServerConnectionFactory extends AbstractConne @Override public void dump(Appendable out, String indent) throws IOException { - Dumpable.dumpObjects(out,indent,this, sessions); + Dumpable.dumpObjects(out, indent, this, sessions); } @Override diff --git a/jetty-http2/http2-server/src/main/java/org/eclipse/jetty/http2/server/HTTP2CServerConnectionFactory.java b/jetty-http2/http2-server/src/main/java/org/eclipse/jetty/http2/server/HTTP2CServerConnectionFactory.java index ebc61045c9c..cc0b9925311 100644 --- a/jetty-http2/http2-server/src/main/java/org/eclipse/jetty/http2/server/HTTP2CServerConnectionFactory.java +++ b/jetty-http2/http2-server/src/main/java/org/eclipse/jetty/http2/server/HTTP2CServerConnectionFactory.java @@ -31,9 +31,8 @@ import org.eclipse.jetty.util.annotation.Name; import org.eclipse.jetty.util.log.Log; import org.eclipse.jetty.util.log.Logger; - -/* ------------------------------------------------------------ */ -/** HTTP2 Clear Text Connection factory. +/** + * HTTP2 Clear Text Connection factory. *

      This extension of HTTP2ServerConnection Factory sets the * protocol name to "h2c" as used by the clear text upgrade mechanism * for HTTP2 and marks all TLS ciphers as unacceptable. @@ -51,15 +50,17 @@ public class HTTP2CServerConnectionFactory extends HTTP2ServerConnectionFactory public HTTP2CServerConnectionFactory(@Name("config") HttpConfiguration httpConfiguration) { - this(httpConfiguration,"h2c"); + this(httpConfiguration, "h2c"); } - + public HTTP2CServerConnectionFactory(@Name("config") HttpConfiguration httpConfiguration, @Name("protocols") String... protocols) { - super(httpConfiguration,protocols); - for (String p:protocols) + super(httpConfiguration, protocols); + for (String p : protocols) + { if (!HTTP2ServerConnection.isSupportedProtocol(p)) - throw new IllegalArgumentException("Unsupported HTTP2 Protocol variant: "+p); + throw new IllegalArgumentException("Unsupported HTTP2 Protocol variant: " + p); + } } @Override diff --git a/jetty-http2/http2-server/src/main/java/org/eclipse/jetty/http2/server/HTTP2ServerConnection.java b/jetty-http2/http2-server/src/main/java/org/eclipse/jetty/http2/server/HTTP2ServerConnection.java index ad9b1416b51..331696417d2 100644 --- a/jetty-http2/http2-server/src/main/java/org/eclipse/jetty/http2/server/HTTP2ServerConnection.java +++ b/jetty-http2/http2-server/src/main/java/org/eclipse/jetty/http2/server/HTTP2ServerConnection.java @@ -69,7 +69,7 @@ public class HTTP2ServerConnection extends HTTP2Connection implements Connection */ public static boolean isSupportedProtocol(String protocol) { - switch(protocol) + switch (protocol) { case "h2": case "h2-17": @@ -86,7 +86,7 @@ public class HTTP2ServerConnection extends HTTP2Connection implements Connection return false; } } - + private final Queue channels = new ArrayDeque<>(); private final List upgradeFrames = new ArrayList<>(); private final AtomicLong totalRequests = new AtomicLong(); @@ -143,7 +143,9 @@ public class HTTP2ServerConnection extends HTTP2Connection implements Connection { notifyAccept(getSession()); for (Frame frame : upgradeFrames) + { getSession().onFrame(frame); + } super.onOpen(); produce(); } @@ -231,11 +233,11 @@ public class HTTP2ServerConnection extends HTTP2Connection implements Connection ISession session = getSession(); // Compute whether all requests are idle. boolean result = session.getStreams().stream() - .map(stream -> (IStream)stream) - .map(stream -> (HttpChannelOverHTTP2)stream.getAttachment()) - .filter(Objects::nonNull) - .map(HttpChannelOverHTTP2::isRequestIdle) - .reduce(true, Boolean::logicalAnd); + .map(stream -> (IStream)stream) + .map(stream -> (HttpChannelOverHTTP2)stream.getAttachment()) + .filter(Objects::nonNull) + .map(HttpChannelOverHTTP2::isRequestIdle) + .reduce(true, Boolean::logicalAnd); if (LOG.isDebugEnabled()) LOG.debug("{} idle timeout on {}: {}", result ? "Processed" : "Ignored", session, failure); return result; @@ -255,7 +257,9 @@ public class HTTP2ServerConnection extends HTTP2Connection implements Connection { CountingCallback counter = new CountingCallback(callback, streams.size()); for (Stream stream : streams) + { onStreamFailure((IStream)stream, failure, counter); + } } } @@ -336,7 +340,7 @@ public class HTTP2ServerConnection extends HTTP2Connection implements Connection final byte[] settings = Base64.getUrlDecoder().decode(value == null ? "" : value); if (LOG.isDebugEnabled()) - LOG.debug("{} settings {}",this,TypeUtil.toHexString(settings)); + LOG.debug("{} settings {}", this, TypeUtil.toHexString(settings)); SettingsFrame settingsFrame = SettingsBodyParser.parseBody(BufferUtil.toBuffer(settings)); if (settingsFrame == null) diff --git a/jetty-http2/http2-server/src/main/java/org/eclipse/jetty/http2/server/HTTP2ServerConnectionFactory.java b/jetty-http2/http2-server/src/main/java/org/eclipse/jetty/http2/server/HTTP2ServerConnectionFactory.java index f2add0f087f..22689d7af76 100644 --- a/jetty-http2/http2-server/src/main/java/org/eclipse/jetty/http2/server/HTTP2ServerConnectionFactory.java +++ b/jetty-http2/http2-server/src/main/java/org/eclipse/jetty/http2/server/HTTP2ServerConnectionFactory.java @@ -54,7 +54,7 @@ public class HTTP2ServerConnectionFactory extends AbstractHTTP2ServerConnectionF public HTTP2ServerConnectionFactory(@Name("config") HttpConfiguration httpConfiguration, @Name("protocols") String... protocols) { - super(httpConfiguration,protocols); + super(httpConfiguration, protocols); } @Override @@ -69,7 +69,7 @@ public class HTTP2ServerConnectionFactory extends AbstractHTTP2ServerConnectionF // Implement 9.2.2 for draft 14 boolean acceptable = "h2-14".equals(protocol) || !(HTTP2Cipher.isBlackListProtocol(tlsProtocol) && HTTP2Cipher.isBlackListCipher(tlsCipher)); if (LOG.isDebugEnabled()) - LOG.debug("proto={} tls={} cipher={} 9.2.2-acceptable={}",protocol,tlsProtocol,tlsCipher,acceptable); + LOG.debug("proto={} tls={} cipher={} 9.2.2-acceptable={}", protocol, tlsProtocol, tlsCipher, acceptable); return acceptable; } diff --git a/jetty-http2/http2-server/src/main/java/org/eclipse/jetty/http2/server/HttpChannelOverHTTP2.java b/jetty-http2/http2-server/src/main/java/org/eclipse/jetty/http2/server/HttpChannelOverHTTP2.java index 03b082e2e80..73919eb6500 100644 --- a/jetty-http2/http2-server/src/main/java/org/eclipse/jetty/http2/server/HttpChannelOverHTTP2.java +++ b/jetty-http2/http2-server/src/main/java/org/eclipse/jetty/http2/server/HttpChannelOverHTTP2.java @@ -127,16 +127,16 @@ public class HttpChannelOverHTTP2 extends HttpChannel implements Closeable, Writ } _delayedUntilContent = getHttpConfiguration().isDelayDispatchUntilContent() && - !endStream && !_expect100Continue; + !endStream && !_expect100Continue; if (LOG.isDebugEnabled()) { Stream stream = getStream(); LOG.debug("HTTP2 Request #{}/{}, delayed={}:{}{} {} {}{}{}", - stream.getId(), Integer.toHexString(stream.getSession().hashCode()), - _delayedUntilContent, System.lineSeparator(), - request.getMethod(), request.getURI(), request.getHttpVersion(), - System.lineSeparator(), fields); + stream.getId(), Integer.toHexString(stream.getSession().hashCode()), + _delayedUntilContent, System.lineSeparator(), + request.getMethod(), request.getURI(), request.getHttpVersion(), + System.lineSeparator(), fields); } return _delayedUntilContent ? null : this; @@ -166,9 +166,9 @@ public class HttpChannelOverHTTP2 extends HttpChannel implements Closeable, Writ { Stream stream = getStream(); LOG.debug("HTTP2 PUSH Request #{}/{}:{}{} {} {}{}{}", - stream.getId(), Integer.toHexString(stream.getSession().hashCode()), System.lineSeparator(), - request.getMethod(), request.getURI(), request.getHttpVersion(), - System.lineSeparator(), request.getFields()); + stream.getId(), Integer.toHexString(stream.getSession().hashCode()), System.lineSeparator(), + request.getMethod(), request.getURI(), request.getHttpVersion(), + System.lineSeparator(), request.getFields()); } return this; @@ -208,8 +208,8 @@ public class HttpChannelOverHTTP2 extends HttpChannel implements Closeable, Writ { Stream stream = getStream(); LOG.debug("HTTP2 Commit Response #{}/{}:{}{} {} {}{}{}", - stream.getId(), Integer.toHexString(stream.getSession().hashCode()), System.lineSeparator(), info.getHttpVersion(), info.getStatus(), info.getReason(), - System.lineSeparator(), info.getFields()); + stream.getId(), Integer.toHexString(stream.getSession().hashCode()), System.lineSeparator(), info.getHttpVersion(), info.getStatus(), info.getReason(), + System.lineSeparator(), info.getFields()); } } @@ -252,19 +252,19 @@ public class HttpChannelOverHTTP2 extends HttpChannel implements Closeable, Writ boolean endStream = frame.isEndStream(); if (endStream) { - boolean handle_content = onContentComplete(); - boolean handle_request = onRequestComplete(); - handle |= handle_content | handle_request; + boolean handleContent = onContentComplete(); + boolean handleRequest = onRequestComplete(); + handle |= handleContent | handleRequest; } if (LOG.isDebugEnabled()) { LOG.debug("HTTP2 Request #{}/{}: {} bytes of {} content, handle: {}", - stream.getId(), - Integer.toHexString(stream.getSession().hashCode()), - length, - endStream ? "last" : "some", - handle); + stream.getId(), + Integer.toHexString(stream.getSession().hashCode()), + length, + endStream ? "last" : "some", + handle); } boolean wasDelayed = _delayedUntilContent; @@ -282,8 +282,8 @@ public class HttpChannelOverHTTP2 extends HttpChannel implements Closeable, Writ { Stream stream = getStream(); LOG.debug("HTTP2 Request #{}/{}, trailers:{}{}", - stream.getId(), Integer.toHexString(stream.getSession().hashCode()), - System.lineSeparator(), trailers); + stream.getId(), Integer.toHexString(stream.getSession().hashCode()), + System.lineSeparator(), trailers); } boolean handle = onRequestComplete(); diff --git a/jetty-http2/http2-server/src/main/java/org/eclipse/jetty/http2/server/HttpTransportOverHTTP2.java b/jetty-http2/http2-server/src/main/java/org/eclipse/jetty/http2/server/HttpTransportOverHTTP2.java index b7e0fcdad8e..7b86321ac83 100644 --- a/jetty-http2/http2-server/src/main/java/org/eclipse/jetty/http2/server/HttpTransportOverHTTP2.java +++ b/jetty-http2/http2-server/src/main/java/org/eclipse/jetty/http2/server/HttpTransportOverHTTP2.java @@ -226,9 +226,9 @@ public class HttpTransportOverHTTP2 implements HttpTransport if (LOG.isDebugEnabled()) { LOG.debug("HTTP2 Response #{}/{}:{}{} {}{}{}", - stream.getId(), Integer.toHexString(stream.getSession().hashCode()), - System.lineSeparator(), HttpVersion.HTTP_2, info.getStatus(), - System.lineSeparator(), info.getFields()); + stream.getId(), Integer.toHexString(stream.getSession().hashCode()), + System.lineSeparator(), HttpVersion.HTTP_2, info.getStatus(), + System.lineSeparator(), info.getFields()); } HeadersFrame frame = new HeadersFrame(stream.getId(), info, null, endStream); @@ -240,8 +240,8 @@ public class HttpTransportOverHTTP2 implements HttpTransport if (LOG.isDebugEnabled()) { LOG.debug("HTTP2 Response #{}/{}: {} content bytes{}", - stream.getId(), Integer.toHexString(stream.getSession().hashCode()), - content.remaining(), lastContent ? " (last chunk)" : ""); + stream.getId(), Integer.toHexString(stream.getSession().hashCode()), + content.remaining(), lastContent ? " (last chunk)" : ""); } DataFrame frame = new DataFrame(stream.getId(), content, endStream); stream.data(frame, callback); @@ -252,7 +252,7 @@ public class HttpTransportOverHTTP2 implements HttpTransport if (LOG.isDebugEnabled()) { LOG.debug("HTTP2 Response #{}/{}: trailers", - stream.getId(), Integer.toHexString(stream.getSession().hashCode())); + stream.getId(), Integer.toHexString(stream.getSession().hashCode())); } HeadersFrame frame = new HeadersFrame(stream.getId(), metaData, null, true); @@ -294,7 +294,7 @@ public class HttpTransportOverHTTP2 implements HttpTransport IStream stream = this.stream; if (LOG.isDebugEnabled()) LOG.debug("HTTP2 Response #{}/{} aborted", stream == null ? -1 : stream.getId(), - stream == null ? -1 : Integer.toHexString(stream.getSession().hashCode())); + stream == null ? -1 : Integer.toHexString(stream.getSession().hashCode())); if (stream != null) stream.reset(new ResetFrame(stream.getId(), ErrorCode.INTERNAL_ERROR.code), Callback.NOOP); } @@ -346,9 +346,9 @@ public class HttpTransportOverHTTP2 implements HttpTransport } if (LOG.isDebugEnabled()) LOG.debug("HTTP2 Response #{}/{} {} {}", - stream.getId(), Integer.toHexString(stream.getSession().hashCode()), - commit ? "commit" : "flush", - callback == null ? "failure" : "success"); + stream.getId(), Integer.toHexString(stream.getSession().hashCode()), + commit ? "commit" : "flush", + callback == null ? "failure" : "success"); if (callback != null) callback.succeeded(); } diff --git a/jetty-http2/http2-server/src/test/java/org/eclipse/jetty/http2/server/AbstractServerTest.java b/jetty-http2/http2-server/src/test/java/org/eclipse/jetty/http2/server/AbstractServerTest.java index 7f0a454bdcb..15c694254fa 100644 --- a/jetty-http2/http2-server/src/test/java/org/eclipse/jetty/http2/server/AbstractServerTest.java +++ b/jetty-http2/http2-server/src/test/java/org/eclipse/jetty/http2/server/AbstractServerTest.java @@ -23,7 +23,6 @@ import java.io.InputStream; import java.net.Socket; import java.net.SocketTimeoutException; import java.nio.ByteBuffer; - import javax.servlet.http.HttpServlet; import org.eclipse.jetty.http.HostPortHttpField; @@ -63,7 +62,7 @@ public class AbstractServerTest protected void startServer(ServerSessionListener listener) throws Exception { - prepareServer(new RawHTTP2ServerConnectionFactory(new HttpConfiguration(),listener)); + prepareServer(new RawHTTP2ServerConnectionFactory(new HttpConfiguration(), listener)); server.start(); } @@ -90,7 +89,7 @@ public class AbstractServerTest @AfterEach public void dispose() throws Exception { - if (server!=null) + if (server != null) server.stop(); } diff --git a/jetty-http2/http2-server/src/test/java/org/eclipse/jetty/http2/server/CloseTest.java b/jetty-http2/http2-server/src/test/java/org/eclipse/jetty/http2/server/CloseTest.java index d68e203541e..963591f41c1 100644 --- a/jetty-http2/http2-server/src/test/java/org/eclipse/jetty/http2/server/CloseTest.java +++ b/jetty-http2/http2-server/src/test/java/org/eclipse/jetty/http2/server/CloseTest.java @@ -18,9 +18,6 @@ package org.eclipse.jetty.http2.server; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertTrue; - import java.io.IOException; import java.io.OutputStream; import java.net.Socket; @@ -48,9 +45,11 @@ import org.eclipse.jetty.io.ByteBufferPool; import org.eclipse.jetty.io.RuntimeIOException; import org.eclipse.jetty.util.BufferUtil; import org.eclipse.jetty.util.Callback; - import org.junit.jupiter.api.Test; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + public class CloseTest extends AbstractServerTest { @Test diff --git a/jetty-http2/http2-server/src/test/java/org/eclipse/jetty/http2/server/HTTP2CServer.java b/jetty-http2/http2-server/src/test/java/org/eclipse/jetty/http2/server/HTTP2CServer.java index fbb8206830b..6a9527da0de 100644 --- a/jetty-http2/http2-server/src/test/java/org/eclipse/jetty/http2/server/HTTP2CServer.java +++ b/jetty-http2/http2-server/src/test/java/org/eclipse/jetty/http2/server/HTTP2CServer.java @@ -19,20 +19,16 @@ package org.eclipse.jetty.http2.server; import java.io.IOException; -import java.net.Socket; import java.util.Date; - import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; -import org.eclipse.jetty.io.Connection; import org.eclipse.jetty.server.HttpConfiguration; import org.eclipse.jetty.server.HttpConnectionFactory; import org.eclipse.jetty.server.Request; import org.eclipse.jetty.server.Server; import org.eclipse.jetty.server.ServerConnector; -import org.eclipse.jetty.server.SocketCustomizationListener; import org.eclipse.jetty.server.handler.AbstractHandler; import org.eclipse.jetty.util.thread.QueuedThreadPool; @@ -42,20 +38,19 @@ public class HTTP2CServer extends Server { HttpConfiguration config = new HttpConfiguration(); // HTTP + HTTP/2 connector - + HttpConnectionFactory http1 = new HttpConnectionFactory(config); HTTP2CServerConnectionFactory http2c = new HTTP2CServerConnectionFactory(config); - ServerConnector connector = new ServerConnector(this,http1,http2c); + ServerConnector connector = new ServerConnector(this, http1, http2c); connector.setPort(port); addConnector(connector); ((QueuedThreadPool)getThreadPool()).setName("server"); setHandler(new SimpleHandler()); - } - public static void main(String... args ) throws Exception + public static void main(String... args) throws Exception { HTTP2CServer server = new HTTP2CServer(8080); server.start(); @@ -67,15 +62,15 @@ public class HTTP2CServer extends Server public void handle(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { baseRequest.setHandled(true); - String code=request.getParameter("code"); - if (code!=null) + String code = request.getParameter("code"); + if (code != null) response.setStatus(Integer.parseInt(code)); - response.setHeader("Custom","Value"); + response.setHeader("Custom", "Value"); response.setContentType("text/plain"); - String content = "Hello from Jetty using "+request.getProtocol() +"\n"; - content+="uri="+request.getRequestURI()+"\n"; - content+="date="+new Date()+"\n"; + String content = "Hello from Jetty using " + request.getProtocol() + "\n"; + content += "uri=" + request.getRequestURI() + "\n"; + content += "date=" + new Date() + "\n"; response.setContentLength(content.length()); response.getOutputStream().print(content); } diff --git a/jetty-http2/http2-server/src/test/java/org/eclipse/jetty/http2/server/HTTP2CServerTest.java b/jetty-http2/http2-server/src/test/java/org/eclipse/jetty/http2/server/HTTP2CServerTest.java index a4f0833fa97..134639d9429 100644 --- a/jetty-http2/http2-server/src/test/java/org/eclipse/jetty/http2/server/HTTP2CServerTest.java +++ b/jetty-http2/http2-server/src/test/java/org/eclipse/jetty/http2/server/HTTP2CServerTest.java @@ -18,12 +18,6 @@ package org.eclipse.jetty.http2.server; -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.containsString; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertNotNull; -import static org.junit.jupiter.api.Assertions.assertTrue; - import java.io.BufferedReader; import java.io.InputStream; import java.io.InputStreamReader; @@ -65,6 +59,12 @@ import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.containsString; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertTrue; + public class HTTP2CServerTest extends AbstractServerTest { @BeforeEach @@ -120,8 +120,8 @@ public class HTTP2CServerTest extends AbstractServerTest try (Socket client = new Socket("localhost", connector.getLocalPort())) { OutputStream output = client.getOutputStream(); - output.write(("" + - "GET /one HTTP/1.1\r\n" + + output.write(( + "GET /one HTTP/1.1\r\n" + "Host: localhost\r\n" + "Connection: something, else, upgrade, HTTP2-Settings\r\n" + "Upgrade: h2c\r\n" + @@ -198,7 +198,9 @@ public class HTTP2CServerTest extends AbstractServerTest MetaData.Request metaData = new MetaData.Request("GET", HttpScheme.HTTP, new HostPortHttpField("localhost:" + connector.getLocalPort()), "/two", HttpVersion.HTTP_2, new HttpFields()); generator.control(lease, new HeadersFrame(3, metaData, null, true)); for (ByteBuffer buffer : lease.getByteBuffers()) + { output.write(BufferUtil.toArray(buffer)); + } output.flush(); parseResponse(client, parser); @@ -330,7 +332,9 @@ public class HTTP2CServerTest extends AbstractServerTest { OutputStream output = client.getOutputStream(); for (ByteBuffer buffer : lease.getByteBuffers()) + { output.write(BufferUtil.toArray(buffer)); + } // We sent a HTTP/2 preface, but the server has no "h2c" connection // factory so it does not know how to handle this request. diff --git a/jetty-http2/http2-server/src/test/java/org/eclipse/jetty/http2/server/HTTP2ServerTest.java b/jetty-http2/http2-server/src/test/java/org/eclipse/jetty/http2/server/HTTP2ServerTest.java index c7722493042..53bba437cd9 100644 --- a/jetty-http2/http2-server/src/test/java/org/eclipse/jetty/http2/server/HTTP2ServerTest.java +++ b/jetty-http2/http2-server/src/test/java/org/eclipse/jetty/http2/server/HTTP2ServerTest.java @@ -18,12 +18,6 @@ package org.eclipse.jetty.http2.server; -import static org.junit.jupiter.api.Assertions.assertArrayEquals; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertFalse; -import static org.junit.jupiter.api.Assertions.assertNotNull; -import static org.junit.jupiter.api.Assertions.assertTrue; - import java.io.IOException; import java.io.InterruptedIOException; import java.io.OutputStream; @@ -40,7 +34,6 @@ import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicReference; import java.util.function.UnaryOperator; - import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; @@ -73,15 +66,20 @@ import org.eclipse.jetty.server.ServerConnector; import org.eclipse.jetty.util.BufferUtil; import org.eclipse.jetty.util.Callback; import org.eclipse.jetty.util.log.StacklessLogging; - import org.junit.jupiter.api.Test; +import static org.junit.jupiter.api.Assertions.assertArrayEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertTrue; + public class HTTP2ServerTest extends AbstractServerTest { @Test public void testNoPrefaceBytes() throws Exception { - startServer(new HttpServlet(){}); + startServer(new HttpServlet() {}); // No preface bytes. MetaData.Request metaData = newRequest("GET", new HttpFields()); @@ -242,7 +240,7 @@ public class HTTP2ServerTest extends AbstractServerTest @Test public void testBadPingWrongPayload() throws Exception { - startServer(new HttpServlet(){}); + startServer(new HttpServlet() {}); ByteBufferPool.Lease lease = new ByteBufferPool.Lease(byteBufferPool); generator.control(lease, new PrefaceFrame()); @@ -280,7 +278,7 @@ public class HTTP2ServerTest extends AbstractServerTest @Test public void testBadPingWrongStreamId() throws Exception { - startServer(new HttpServlet(){}); + startServer(new HttpServlet() {}); ByteBufferPool.Lease lease = new ByteBufferPool.Lease(byteBufferPool); generator.control(lease, new PrefaceFrame()); @@ -344,7 +342,7 @@ public class HTTP2ServerTest extends AbstractServerTest @Override protected ChannelEndPoint newEndPoint(SocketChannel channel, ManagedSelector selectSet, SelectionKey key) throws IOException { - return new SocketChannelEndPoint(channel,selectSet,key,getScheduler()) + return new SocketChannelEndPoint(channel, selectSet, key, getScheduler()) { @Override public void write(Callback callback, ByteBuffer... buffers) throws IllegalStateException @@ -369,7 +367,9 @@ public class HTTP2ServerTest extends AbstractServerTest { OutputStream output = client.getOutputStream(); for (ByteBuffer buffer : lease.getByteBuffers()) + { output.write(BufferUtil.toArray(buffer)); + } // The server will close the connection abruptly since it // cannot write and therefore cannot even send the GO_AWAY. @@ -405,7 +405,9 @@ public class HTTP2ServerTest extends AbstractServerTest { OutputStream output = client.getOutputStream(); for (ByteBuffer buffer : lease.getByteBuffers()) + { output.write(BufferUtil.toArray(buffer)); + } output.flush(); Parser parser = new Parser(byteBufferPool, new Parser.Listener.Adapter(), 4096, 8192); @@ -529,10 +531,10 @@ public class HTTP2ServerTest extends AbstractServerTest continuationFrameHeader.put(4, (byte)0); // Add a last, empty, CONTINUATION frame. ByteBuffer last = ByteBuffer.wrap(new byte[]{ - 0, 0, 0, // Length - (byte)FrameType.CONTINUATION.getType(), - (byte)Flags.END_HEADERS, - 0, 0, 0, 1 // Stream ID + 0, 0, 0, // Length + (byte)FrameType.CONTINUATION.getType(), + (byte)Flags.END_HEADERS, + 0, 0, 0, 1 // Stream ID }); lease.append(last, false); return lease; @@ -573,7 +575,9 @@ public class HTTP2ServerTest extends AbstractServerTest { OutputStream output = client.getOutputStream(); for (ByteBuffer buffer : lease.getByteBuffers()) + { output.write(BufferUtil.toArray(buffer)); + } output.flush(); assertTrue(serverLatch.await(5, TimeUnit.SECONDS)); diff --git a/jetty-infinispan/infinispan-common/pom.xml b/jetty-infinispan/infinispan-common/pom.xml index 0dc1b5b82a6..751d63b19e2 100644 --- a/jetty-infinispan/infinispan-common/pom.xml +++ b/jetty-infinispan/infinispan-common/pom.xml @@ -12,7 +12,6 @@ ${project.groupId}.infinispan.common - install @@ -37,22 +36,22 @@ - org.infinispan - infinispan-core - ${infinispan.version} - true + org.infinispan + infinispan-core + ${infinispan.version} + true - org.infinispan.protostream - protostream - 4.2.2.Final - true - provided + org.infinispan.protostream + protostream + 4.2.2.Final + true + provided - org.eclipse.jetty - jetty-server - ${project.version} + org.eclipse.jetty + jetty-server + ${project.version} org.infinispan diff --git a/jetty-infinispan/infinispan-common/src/main/java/org/eclipse/jetty/session/infinispan/InfinispanSessionData.java b/jetty-infinispan/infinispan-common/src/main/java/org/eclipse/jetty/session/infinispan/InfinispanSessionData.java index dbca0652dc3..a5f73eb9e4c 100644 --- a/jetty-infinispan/infinispan-common/src/main/java/org/eclipse/jetty/session/infinispan/InfinispanSessionData.java +++ b/jetty-infinispan/infinispan-common/src/main/java/org/eclipse/jetty/session/infinispan/InfinispanSessionData.java @@ -11,14 +11,13 @@ import org.eclipse.jetty.util.ClassLoadingObjectInputStream; /** * InfinispanSessionData - * + * * Specialization of SessionData to hold the attributes as a serialized byte * array. This is necessary because to deserialize the attributes correctly, we * need to know which classloader to use, which is normally provided as the * thread context classloader. However, infinispan marshalling uses a thread * pool and thus these threads have no knowledge of the correct classloader to * use. - * */ public class InfinispanSessionData extends SessionData { @@ -47,7 +46,8 @@ public class InfinispanSessionData extends SessionData public void deserializeAttributes() throws ClassNotFoundException, IOException { - if (_serializedAttributes == null) return; + if (_serializedAttributes == null) + return; try (ByteArrayInputStream bais = new ByteArrayInputStream(_serializedAttributes); ClassLoadingObjectInputStream ois = new ClassLoadingObjectInputStream(bais)) diff --git a/jetty-infinispan/infinispan-common/src/main/java/org/eclipse/jetty/session/infinispan/InfinispanSessionDataStore.java b/jetty-infinispan/infinispan-common/src/main/java/org/eclipse/jetty/session/infinispan/InfinispanSessionDataStore.java index d35b2c0e071..552be1c86f6 100644 --- a/jetty-infinispan/infinispan-common/src/main/java/org/eclipse/jetty/session/infinispan/InfinispanSessionDataStore.java +++ b/jetty-infinispan/infinispan-common/src/main/java/org/eclipse/jetty/session/infinispan/InfinispanSessionDataStore.java @@ -16,7 +16,6 @@ // ======================================================================== // - package org.eclipse.jetty.session.infinispan; import java.util.HashSet; @@ -34,68 +33,56 @@ import org.eclipse.jetty.util.log.Log; import org.eclipse.jetty.util.log.Logger; import org.infinispan.commons.api.BasicCache; - /** * InfinispanSessionDataStore - * - * */ @ManagedObject public class InfinispanSessionDataStore extends AbstractSessionDataStore { - private final static Logger LOG = Log.getLogger("org.eclipse.jetty.server.session"); - + private static final Logger LOG = Log.getLogger("org.eclipse.jetty.server.session"); /** * Clustered cache of sessions */ private BasicCache _cache; - private int _infinispanIdleTimeoutSec; - - private QueryManager _queryManager; - + private boolean _passivating; - /** * Get the clustered cache instance. - * + * * @return the cache */ - public BasicCache getCache() + public BasicCache getCache() { return _cache; } - - /** * Set the clustered cache instance. - * + * * @param cache the cache */ - public void setCache (BasicCache cache) + public void setCache(BasicCache cache) { this._cache = cache; } - - public QueryManager getQueryManager() + public QueryManager getQueryManager() { return _queryManager; } - - public void setQueryManager (QueryManager queryManager) + public void setQueryManager(QueryManager queryManager) { _queryManager = queryManager; } - - /** + + /** * @see org.eclipse.jetty.server.session.SessionDataStore#load(String) */ @Override @@ -103,9 +90,9 @@ public class InfinispanSessionDataStore extends AbstractSessionDataStore { super.doStart(); if (_cache == null) - throw new IllegalStateException ("No cache"); + throw new IllegalStateException("No cache"); - try + try { _passivating = false; Class remoteClass = InfinispanSessionDataStore.class.getClassLoader().loadClass("org.infinispan.client.hotrod.RemoteCache"); @@ -119,11 +106,9 @@ public class InfinispanSessionDataStore extends AbstractSessionDataStore } } - - @Override public SessionData doLoad(String id) throws Exception - { + { try { if (LOG.isDebugEnabled()) @@ -145,7 +130,6 @@ public class InfinispanSessionDataStore extends AbstractSessionDataStore } } - @Override public boolean delete(String id) throws Exception { @@ -154,100 +138,100 @@ public class InfinispanSessionDataStore extends AbstractSessionDataStore return (_cache.remove(getCacheKey(id)) != null); } - @Override public Set doGetExpired(Set candidates) { - long now = System.currentTimeMillis(); - - Set expired = new HashSet<>(); - - /* - * 1. Select sessions managed by this node for our context that have expired - */ - if(candidates != null) - { - for (String candidate:candidates) - { - if (LOG.isDebugEnabled()) - LOG.debug("Checking expiry for candidate {}", candidate); - try - { - SessionData sd = load(candidate); + long now = System.currentTimeMillis(); - //if the session no longer exists - if (sd == null) - { - expired.add(candidate); - if (LOG.isDebugEnabled()) - LOG.debug("Session {} does not exist in infinispan", candidate); - } - else - { - if (_context.getWorkerName().equals(sd.getLastNode())) - { - //we are its manager, add it to the expired set if it is expired now - if ((sd.getExpiry() > 0 ) && sd.getExpiry() <= now) - { - expired.add(candidate); - if (LOG.isDebugEnabled()) - LOG.debug("Session {} managed by {} is expired", candidate, _context.getWorkerName()); - } - } - else - { - //if we are not the session's manager, only expire it iff: - // this is our first expiryCheck and the session expired a long time ago - //or - //the session expired at least one graceperiod ago - if (_lastExpiryCheckTime <=0) - { - if ((sd.getExpiry() > 0 ) && sd.getExpiry() < (now - (1000L * (3 * _gracePeriodSec)))) - expired.add(candidate); - } - else - { - if ((sd.getExpiry() > 0 ) && sd.getExpiry() < (now - (1000L * _gracePeriodSec))) - expired.add(candidate); - } - } - } - } - catch (Exception e) - { - LOG.warn("Error checking if candidate {} is expired", candidate, e); - } - } - } - - - /* - * 2. Select sessions for any node or context that have expired - * at least 1 graceperiod since the last expiry check. If we haven't done previous expiry checks, then check - * those that have expired at least 3 graceperiod ago. - */ - if(_queryManager != null) - { - long upperBound = now; - if (_lastExpiryCheckTime <= 0) - upperBound = (now - (3*(1000L * _gracePeriodSec))); - else - upperBound = _lastExpiryCheckTime - (1000L * _gracePeriodSec); + Set expired = new HashSet<>(); - if (LOG.isDebugEnabled()) LOG.debug("{}- Pass 2: Searching for sessions expired before {}", _context.getWorkerName(), upperBound); + /* + * 1. Select sessions managed by this node for our context that have expired + */ + if (candidates != null) + { + for (String candidate : candidates) + { + if (LOG.isDebugEnabled()) + LOG.debug("Checking expiry for candidate {}", candidate); + try + { + SessionData sd = load(candidate); - for (String sessionId : _queryManager.queryExpiredSessions(upperBound)) - { - expired.add(sessionId); - if (LOG.isDebugEnabled()) LOG.debug ("{}- Found expired sessionId=",_context.getWorkerName(), sessionId); - } - } + //if the session no longer exists + if (sd == null) + { + expired.add(candidate); + if (LOG.isDebugEnabled()) + LOG.debug("Session {} does not exist in infinispan", candidate); + } + else + { + if (_context.getWorkerName().equals(sd.getLastNode())) + { + //we are its manager, add it to the expired set if it is expired now + if ((sd.getExpiry() > 0) && sd.getExpiry() <= now) + { + expired.add(candidate); + if (LOG.isDebugEnabled()) + LOG.debug("Session {} managed by {} is expired", candidate, _context.getWorkerName()); + } + } + else + { + //if we are not the session's manager, only expire it iff: + // this is our first expiryCheck and the session expired a long time ago + //or + //the session expired at least one graceperiod ago + if (_lastExpiryCheckTime <= 0) + { + if ((sd.getExpiry() > 0) && sd.getExpiry() < (now - (1000L * (3 * _gracePeriodSec)))) + expired.add(candidate); + } + else + { + if ((sd.getExpiry() > 0) && sd.getExpiry() < (now - (1000L * _gracePeriodSec))) + expired.add(candidate); + } + } + } + } + catch (Exception e) + { + LOG.warn("Error checking if candidate {} is expired", candidate, e); + } + } + } - return expired; + + /* + * 2. Select sessions for any node or context that have expired + * at least 1 graceperiod since the last expiry check. If we haven't done previous expiry checks, then check + * those that have expired at least 3 graceperiod ago. + */ + if (_queryManager != null) + { + long upperBound = now; + if (_lastExpiryCheckTime <= 0) + upperBound = (now - (3 * (1000L * _gracePeriodSec))); + else + upperBound = _lastExpiryCheckTime - (1000L * _gracePeriodSec); + + if (LOG.isDebugEnabled()) + LOG.debug("{}- Pass 2: Searching for sessions expired before {}", _context.getWorkerName(), upperBound); + + for (String sessionId : _queryManager.queryExpiredSessions(upperBound)) + { + expired.add(sessionId); + if (LOG.isDebugEnabled()) + LOG.debug("{}- Found expired sessionId=", _context.getWorkerName(), sessionId); + } + } + + return expired; } - @Override public void doStore(String id, SessionData data, long lastSaveTime) throws Exception { @@ -258,28 +242,24 @@ public class InfinispanSessionDataStore extends AbstractSessionDataStore if (data.getMaxInactiveMs() > 0 && getInfinispanIdleTimeoutSec() > 0) _cache.put(getCacheKey(id), (InfinispanSessionData)data, -1, TimeUnit.MILLISECONDS, getInfinispanIdleTimeoutSec(), TimeUnit.SECONDS); else - _cache.put(getCacheKey(id), (InfinispanSessionData)data); + _cache.put(getCacheKey(id), (InfinispanSessionData)data); if (LOG.isDebugEnabled()) LOG.debug("Session {} saved to infinispan, expires {} ", id, data.getExpiry()); } - - - public String getCacheKey (String id) + + public String getCacheKey(String id) { - return _context.getCanonicalContextPath()+"_"+_context.getVhost()+"_"+id; + return _context.getCanonicalContextPath() + "_" + _context.getVhost() + "_" + id; } - - @ManagedAttribute(value="does store serialize sessions", readonly=true) + @ManagedAttribute(value = "does store serialize sessions", readonly = true) @Override public boolean isPassivating() { return _passivating; } - - @Override public boolean exists(String id) throws Exception { @@ -291,7 +271,7 @@ public class InfinispanSessionDataStore extends AbstractSessionDataStore Runnable load = new Runnable() { @Override - public void run () + public void run() { try { @@ -313,44 +293,39 @@ public class InfinispanSessionDataStore extends AbstractSessionDataStore } } }; - + //ensure the load runs in the context classloader scope _context.run(load); - + if (exception.get() != null) throw exception.get(); - + return reference.get(); } - - @Override public SessionData newSessionData(String id, long created, long accessed, long lastAccessed, long maxInactiveMs) { return new InfinispanSessionData(id, _context.getCanonicalContextPath(), _context.getVhost(), created, accessed, lastAccessed, maxInactiveMs); } - /** * @param sec the infinispan-specific idle timeout in sec or 0 if not set */ - public void setInfinispanIdleTimeoutSec (int sec) + public void setInfinispanIdleTimeoutSec(int sec) { _infinispanIdleTimeoutSec = sec; } - - - @ManagedAttribute(value="infinispan idle timeout sec", readonly=true) - public int getInfinispanIdleTimeoutSec () + + @ManagedAttribute(value = "infinispan idle timeout sec", readonly = true) + public int getInfinispanIdleTimeoutSec() { return _infinispanIdleTimeoutSec; } - @Override public String toString() { - return String.format("%s[cache=%s,idleTimeoutSec=%d]",super.toString(), (_cache==null?"":_cache.getName()),_infinispanIdleTimeoutSec); + return String.format("%s[cache=%s,idleTimeoutSec=%d]", super.toString(), (_cache == null ? "" : _cache.getName()), _infinispanIdleTimeoutSec); } } diff --git a/jetty-infinispan/infinispan-common/src/main/java/org/eclipse/jetty/session/infinispan/InfinispanSessionDataStoreFactory.java b/jetty-infinispan/infinispan-common/src/main/java/org/eclipse/jetty/session/infinispan/InfinispanSessionDataStoreFactory.java index 241678057d3..faf275c17cb 100644 --- a/jetty-infinispan/infinispan-common/src/main/java/org/eclipse/jetty/session/infinispan/InfinispanSessionDataStoreFactory.java +++ b/jetty-infinispan/infinispan-common/src/main/java/org/eclipse/jetty/session/infinispan/InfinispanSessionDataStoreFactory.java @@ -16,7 +16,6 @@ // ======================================================================== // - package org.eclipse.jetty.session.infinispan; import org.eclipse.jetty.server.session.AbstractSessionDataStoreFactory; @@ -27,15 +26,13 @@ import org.infinispan.commons.api.BasicCache; /** * InfinispanSessionDataStoreFactory - * - * */ public class InfinispanSessionDataStoreFactory extends AbstractSessionDataStoreFactory { int _infinispanIdleTimeoutSec; BasicCache _cache; protected QueryManager _queryManager; - + /** * @return the infinispanIdleTimeoutSec */ @@ -52,11 +49,11 @@ public class InfinispanSessionDataStoreFactory extends AbstractSessionDataStoreF _infinispanIdleTimeoutSec = infinispanIdleTimeoutSec; } - /** + /** * @see org.eclipse.jetty.server.session.SessionDataStoreFactory#getSessionDataStore(org.eclipse.jetty.server.session.SessionHandler) */ @Override - public SessionDataStore getSessionDataStore (SessionHandler handler) throws Exception + public SessionDataStore getSessionDataStore(SessionHandler handler) throws Exception { InfinispanSessionDataStore store = new InfinispanSessionDataStore(); store.setGracePeriodSec(getGracePeriodSec()); @@ -66,25 +63,23 @@ public class InfinispanSessionDataStoreFactory extends AbstractSessionDataStoreF store.setQueryManager(getQueryManager()); return store; } - + /** * Get the clustered cache instance. - * + * * @return the cache */ - public BasicCache getCache() + public BasicCache getCache() { return _cache; } - - /** * Set the clustered cache instance. - * + * * @param cache the cache */ - public void setCache (BasicCache cache) + public void setCache(BasicCache cache) { this._cache = cache; } @@ -98,6 +93,4 @@ public class InfinispanSessionDataStoreFactory extends AbstractSessionDataStoreF { _queryManager = queryManager; } - - } diff --git a/jetty-infinispan/infinispan-common/src/main/java/org/eclipse/jetty/session/infinispan/InfinispanSessionLegacyConverter.java b/jetty-infinispan/infinispan-common/src/main/java/org/eclipse/jetty/session/infinispan/InfinispanSessionLegacyConverter.java index 919ad74c49c..32c162c7c6d 100644 --- a/jetty-infinispan/infinispan-common/src/main/java/org/eclipse/jetty/session/infinispan/InfinispanSessionLegacyConverter.java +++ b/jetty-infinispan/infinispan-common/src/main/java/org/eclipse/jetty/session/infinispan/InfinispanSessionLegacyConverter.java @@ -16,7 +16,6 @@ // ======================================================================== // - package org.eclipse.jetty.session.infinispan; import java.util.List; @@ -31,28 +30,25 @@ import org.infinispan.client.hotrod.marshall.ProtoStreamMarshaller; import org.infinispan.protostream.FileDescriptorSource; import org.infinispan.protostream.SerializationContext; - /** * InfinispanSessionLegacyConverter * * Converts sessions saved in the old serialization * format into the new protobuf-based serialization. - * + * * Use the -Dverbose=true system property to * print out more information about conversion failures. - * */ public class InfinispanSessionLegacyConverter { RemoteCacheManager _protoManager; - RemoteCache _protoCache; + RemoteCache _protoCache; RemoteCacheManager _legacyManager; - RemoteCache _legacyCache; + RemoteCache _legacyCache; boolean _verbose = false; - - public InfinispanSessionLegacyConverter (String cacheName) - throws Exception + public InfinispanSessionLegacyConverter(String cacheName) + throws Exception { //legacy serialization _legacyManager = new RemoteCacheManager(); @@ -77,7 +73,7 @@ public class InfinispanSessionLegacyConverter /** * Convert all sessions to protobuf format sessions. */ - public void convert () + public void convert() { long conversions = 0; List keys = null; @@ -90,11 +86,12 @@ public class InfinispanSessionLegacyConverter catch (Exception e) { System.err.println("Error listing legacy sessions, assuming previously converted. Run again using 'check' argument to verify conversion"); - if (_verbose) e.printStackTrace(); + if (_verbose) + e.printStackTrace(); System.exit(1); } - for (String s:keys) + for (String s : keys) { SessionData data = null; try @@ -103,11 +100,12 @@ public class InfinispanSessionLegacyConverter } catch (Exception e) { - System.err.println("Read of session "+s+" failed. Assuming session already converted and skipping."); - if (_verbose) e.printStackTrace(); + System.err.println("Read of session " + s + " failed. Assuming session already converted and skipping."); + if (_verbose) + e.printStackTrace(); continue; } - + if (data != null) { try @@ -116,15 +114,16 @@ public class InfinispanSessionLegacyConverter } catch (Exception e) { - System.err.println("Remove legacy session failed for "+s+" skipping conversion."); - if (_verbose) e.printStackTrace(); + System.err.println("Remove legacy session failed for " + s + " skipping conversion."); + if (_verbose) + e.printStackTrace(); continue; } try { InfinispanSessionData isd = new InfinispanSessionData(data.getId(), data.getContextPath(), data.getVhost(), data.getCreated(), - data.getAccessed(), data.getLastAccessed(), data.getMaxInactiveMs()); + data.getAccessed(), data.getLastAccessed(), data.getMaxInactiveMs()); isd.putAllAttributes(data.getAllAttributes()); isd.setExpiry(data.getExpiry()); isd.setCookieSet(data.getCookieSet()); @@ -137,7 +136,8 @@ public class InfinispanSessionLegacyConverter } catch (Exception e) { - if (_verbose) e.printStackTrace(); + if (_verbose) + e.printStackTrace(); System.err.println("Conversion failed for " + s + " re-instating legacy session."); try { @@ -152,17 +152,17 @@ public class InfinispanSessionLegacyConverter } } else - System.err.println("Unreadable legacy session "+s); + System.err.println("Unreadable legacy session " + s); } - - System.err.println("Total sessions converted: "+conversions); + + System.err.println("Total sessions converted: " + conversions); } /** - * Retrieve the sessions using protobuf format and print them out to + * Retrieve the sessions using protobuf format and print them out to * confirm they're ok. */ - public void checkConverted () + public void checkConverted() { List keys = null; try @@ -176,27 +176,27 @@ public class InfinispanSessionLegacyConverter System.exit(1); } - for (String s:keys) + for (String s : keys) { - InfinispanSessionData converted = (InfinispanSessionData)_protoCache.get(s); + InfinispanSessionData converted = _protoCache.get(s); if (converted != null) { - System.err.println("OK: "+converted); - converted.getKeys().stream().forEach((ss)->{System.err.println(ss+":"+converted.getAttribute(ss));}); + System.err.println("OK: " + converted); + converted.getKeys().stream().forEach((ss) -> System.err.println(ss + ":" + converted.getAttribute(ss))); } else - System.err.println("Failed: "+s); + System.err.println("Failed: " + s); } - System.err.println("Total converted sessions: "+keys.size()); + System.err.println("Total converted sessions: " + keys.size()); } - public static final void usage () + public static final void usage() { System.err.println("Usage: InfinispanSessionLegacyConverter [-Dhost=127.0.0.1] [-Dverbose=true] [check]"); } - - public static final void main (String... args) + + public static final void main(String... args) { if (args == null || args.length < 1) { @@ -213,7 +213,7 @@ public class InfinispanSessionLegacyConverter else if (args[1].equals("check")) converter.checkConverted(); else - usage(); + usage(); } catch (Exception e) { diff --git a/jetty-infinispan/infinispan-common/src/main/java/org/eclipse/jetty/session/infinispan/QueryManager.java b/jetty-infinispan/infinispan-common/src/main/java/org/eclipse/jetty/session/infinispan/QueryManager.java index 33711c3a506..4250553aec2 100644 --- a/jetty-infinispan/infinispan-common/src/main/java/org/eclipse/jetty/session/infinispan/QueryManager.java +++ b/jetty-infinispan/infinispan-common/src/main/java/org/eclipse/jetty/session/infinispan/QueryManager.java @@ -23,5 +23,6 @@ import java.util.Set; public interface QueryManager { Set queryExpiredSessions(); + Set queryExpiredSessions(long currentTime); } diff --git a/jetty-infinispan/infinispan-common/src/main/java/org/eclipse/jetty/session/infinispan/SessionDataMarshaller.java b/jetty-infinispan/infinispan-common/src/main/java/org/eclipse/jetty/session/infinispan/SessionDataMarshaller.java index 128182c7da9..7a16fcf1265 100644 --- a/jetty-infinispan/infinispan-common/src/main/java/org/eclipse/jetty/session/infinispan/SessionDataMarshaller.java +++ b/jetty-infinispan/infinispan-common/src/main/java/org/eclipse/jetty/session/infinispan/SessionDataMarshaller.java @@ -62,7 +62,7 @@ public class SessionDataMarshaller implements MessageMarshaller - - + + @@ -68,8 +61,8 @@ - - + + @@ -86,7 +79,7 @@ single - + src/main/assembly/config.xml @@ -97,25 +90,25 @@ - org.eclipse.jetty - infinispan-common - ${project.version} - - - org.infinispan - infinispan-core - - - org.infinispan - infinispan-commons - - + org.eclipse.jetty + infinispan-common + ${project.version} + + + org.infinispan + infinispan-core + + + org.infinispan + infinispan-commons + + org.infinispan infinispan-query ${infinispan.version} - + org.eclipse.jetty.toolchain jetty-test-helper diff --git a/jetty-infinispan/infinispan-embedded-query/src/main/java/org/eclipse/jetty/session/infinispan/EmbeddedQueryManager.java b/jetty-infinispan/infinispan-embedded-query/src/main/java/org/eclipse/jetty/session/infinispan/EmbeddedQueryManager.java index 4b5a23dfa27..621d003d185 100644 --- a/jetty-infinispan/infinispan-embedded-query/src/main/java/org/eclipse/jetty/session/infinispan/EmbeddedQueryManager.java +++ b/jetty-infinispan/infinispan-embedded-query/src/main/java/org/eclipse/jetty/session/infinispan/EmbeddedQueryManager.java @@ -13,30 +13,30 @@ import org.infinispan.query.dsl.QueryFactory; public class EmbeddedQueryManager implements QueryManager { private Cache _cache; - + public EmbeddedQueryManager(Cache cache) { _cache = cache; } - + @Override public Set queryExpiredSessions(long time) - { + { QueryFactory qf = Search.getQueryFactory(_cache); Query q = qf.from(SessionData.class).select("id").having("expiry").lte(time).build(); - - List list = q.list(); + + List list = q.list(); Set ids = new HashSet<>(); - for(Object[] sl : list) + for (Object[] sl : list) + { ids.add((String)sl[0]); + } return ids; } - - + @Override public Set queryExpiredSessions() - { + { return queryExpiredSessions(System.currentTimeMillis()); } - } diff --git a/jetty-infinispan/infinispan-embedded-query/src/main/java/org/eclipse/jetty/session/infinispan/EmbeddedQueryManagerFactory.java b/jetty-infinispan/infinispan-embedded-query/src/main/java/org/eclipse/jetty/session/infinispan/EmbeddedQueryManagerFactory.java index f33f4dcd8c3..77820bc0dd1 100644 --- a/jetty-infinispan/infinispan-embedded-query/src/main/java/org/eclipse/jetty/session/infinispan/EmbeddedQueryManagerFactory.java +++ b/jetty-infinispan/infinispan-embedded-query/src/main/java/org/eclipse/jetty/session/infinispan/EmbeddedQueryManagerFactory.java @@ -12,8 +12,7 @@ public class EmbeddedQueryManagerFactory implements QueryManagerFactory { if (!(cache instanceof Cache)) throw new IllegalArgumentException("Argument was not of type Cache"); - + return new EmbeddedQueryManager((Cache)cache); } - } diff --git a/jetty-infinispan/infinispan-embedded-query/src/test/java/org/eclipse/jetty/server/session/infinispan/EmbeddedQueryManagerTest.java b/jetty-infinispan/infinispan-embedded-query/src/test/java/org/eclipse/jetty/server/session/infinispan/EmbeddedQueryManagerTest.java index 107df7da347..a0599054ea8 100644 --- a/jetty-infinispan/infinispan-embedded-query/src/test/java/org/eclipse/jetty/server/session/infinispan/EmbeddedQueryManagerTest.java +++ b/jetty-infinispan/infinispan-embedded-query/src/test/java/org/eclipse/jetty/server/session/infinispan/EmbeddedQueryManagerTest.java @@ -42,17 +42,15 @@ import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertTrue; - public class EmbeddedQueryManagerTest { - public static final String DEFAULT_CACHE_NAME = "session_test_cache"; + public static final String DEFAULT_CACHE_NAME = "session_test_cache"; - @Test public void test() throws Exception { - String _name = DEFAULT_CACHE_NAME+System.currentTimeMillis(); + String _name = DEFAULT_CACHE_NAME + System.currentTimeMillis(); EmbeddedCacheManager _manager; _manager = new DefaultCacheManager(new GlobalConfigurationBuilder().globalJmxStatistics().allowDuplicateDomains(true).build()); @@ -71,36 +69,36 @@ public class EmbeddedQueryManagerTest b.indexing().index(Index.ALL).addIndexedEntity(SessionData.class).withProperties(properties); Configuration c = b.build(); - + _manager.defineConfiguration(_name, c); - Cache _cache = _manager.getCache(_name); - + Cache _cache = _manager.getCache(_name); + //put some sessions into the cache int numSessions = 10; long currentTime = 500; int maxExpiryTime = 1000; Set expiredSessions = new HashSet<>(); Random r = new Random(); - - for (int i=0; i queryResult = qm.queryExpiredSessions(currentTime); - + // Check that the result is correct assertEquals(expiredSessions.size(), queryResult.size()); for (String s : expiredSessions) diff --git a/jetty-infinispan/infinispan-embedded/pom.xml b/jetty-infinispan/infinispan-embedded/pom.xml index e20605c1461..04349f164a6 100644 --- a/jetty-infinispan/infinispan-embedded/pom.xml +++ b/jetty-infinispan/infinispan-embedded/pom.xml @@ -48,15 +48,8 @@ - - + + @@ -69,8 +62,8 @@ - - + + @@ -89,7 +82,7 @@ - src/main/assembly/config.xml + src/main/assembly/config.xml @@ -99,14 +92,14 @@ - org.eclipse.jetty - infinispan-common - ${project.version} - + org.eclipse.jetty + infinispan-common + ${project.version} + - org.infinispan - infinispan-core - ${infinispan.version} - + org.infinispan + infinispan-core + ${infinispan.version} + diff --git a/jetty-infinispan/infinispan-remote-query/pom.xml b/jetty-infinispan/infinispan-remote-query/pom.xml index 151716c6f5b..9c399d4d6f2 100644 --- a/jetty-infinispan/infinispan-remote-query/pom.xml +++ b/jetty-infinispan/infinispan-remote-query/pom.xml @@ -47,20 +47,9 @@ - - - + + + @@ -73,8 +62,8 @@ - - + + @@ -91,7 +80,7 @@ single - + src/main/assembly/config.xml @@ -102,26 +91,26 @@ org.apache.maven.plugins maven-surefire-plugin - true + true - org.eclipse.jetty - infinispan-common - ${project.version} - - - org.infinispan - infinispan-core - - - org.infinispan - infinispan-commons - - + org.eclipse.jetty + infinispan-common + ${project.version} + + + org.infinispan + infinispan-core + + + org.infinispan + infinispan-commons + + org.infinispan @@ -154,7 +143,7 @@ org.apache.maven.plugins maven-surefire-plugin - false + false diff --git a/jetty-infinispan/infinispan-remote-query/src/main/java/org/eclipse/jetty/session/infinispan/RemoteQueryManager.java b/jetty-infinispan/infinispan-remote-query/src/main/java/org/eclipse/jetty/session/infinispan/RemoteQueryManager.java index 8a79328a72f..5cf40613a41 100644 --- a/jetty-infinispan/infinispan-remote-query/src/main/java/org/eclipse/jetty/session/infinispan/RemoteQueryManager.java +++ b/jetty-infinispan/infinispan-remote-query/src/main/java/org/eclipse/jetty/session/infinispan/RemoteQueryManager.java @@ -32,37 +32,36 @@ import org.infinispan.query.dsl.QueryFactory; * RemoteQueryManager * * A QueryManager impl that supports doing queries against remote infinispan server. - * */ public class RemoteQueryManager implements QueryManager { private RemoteCache _cache; - + public RemoteQueryManager(RemoteCache cache) { _cache = cache; } - + @Override public Set queryExpiredSessions(long time) - { + { // TODO can the QueryFactory be created only once QueryFactory qf = Search.getQueryFactory(_cache); Query q = qf.from(InfinispanSessionData.class).select("id").having("expiry").lte(time).build(); - - List list = q.list(); + + List list = q.list(); Set ids = new HashSet<>(); - for(Object[] sl : list) + for (Object[] sl : list) + { ids.add((String)sl[0]); - + } + return ids; } - - + @Override public Set queryExpiredSessions() - { + { return queryExpiredSessions(System.currentTimeMillis()); } - } diff --git a/jetty-infinispan/infinispan-remote-query/src/main/java/org/eclipse/jetty/session/infinispan/RemoteQueryManagerFactory.java b/jetty-infinispan/infinispan-remote-query/src/main/java/org/eclipse/jetty/session/infinispan/RemoteQueryManagerFactory.java index 21bea54b821..cf4a53fa3e3 100644 --- a/jetty-infinispan/infinispan-remote-query/src/main/java/org/eclipse/jetty/session/infinispan/RemoteQueryManagerFactory.java +++ b/jetty-infinispan/infinispan-remote-query/src/main/java/org/eclipse/jetty/session/infinispan/RemoteQueryManagerFactory.java @@ -31,8 +31,7 @@ public class RemoteQueryManagerFactory implements QueryManagerFactory System.err.println(cache.getClass().getName()); if (!RemoteCache.class.isAssignableFrom(cache.getClass())) throw new IllegalArgumentException("Argument is not of type RemoteCache"); - + return new RemoteQueryManager((RemoteCache)cache); } - } diff --git a/jetty-infinispan/infinispan-remote-query/src/test/java/org/eclipse/jetty/server/session/infinispan/RemoteQueryManagerTest.java b/jetty-infinispan/infinispan-remote-query/src/test/java/org/eclipse/jetty/server/session/infinispan/RemoteQueryManagerTest.java index d3e4e08b62e..a99da415c5d 100644 --- a/jetty-infinispan/infinispan-remote-query/src/test/java/org/eclipse/jetty/server/session/infinispan/RemoteQueryManagerTest.java +++ b/jetty-infinispan/infinispan-remote-query/src/test/java/org/eclipse/jetty/server/session/infinispan/RemoteQueryManagerTest.java @@ -47,80 +47,78 @@ import static org.junit.jupiter.api.Assertions.assertTrue; public class RemoteQueryManagerTest { - public static final String DEFAULT_CACHE_NAME = "remote-session-test"; + public static final String DEFAULT_CACHE_NAME = "remote-session-test"; @Test public void test() throws Exception { SearchMapping mapping = new SearchMapping(); mapping.entity(SessionData.class).indexed().providedId().property("expiry", ElementType.FIELD).field(); - + Properties properties = new Properties(); properties.put(Environment.MODEL_MAPPING, mapping); - + ConfigurationBuilder clientBuilder = new ConfigurationBuilder(); clientBuilder.withProperties(properties).addServer().host("127.0.0.1").marshaller(new ProtoStreamMarshaller()); - + RemoteCacheManager remoteCacheManager = new RemoteCacheManager(clientBuilder.build()); - - + FileDescriptorSource fds = new FileDescriptorSource(); fds.addProtoFiles("/session.proto"); - + SerializationContext serCtx = ProtoStreamMarshaller.getSerializationContext(remoteCacheManager); serCtx.registerProtoFiles(fds); serCtx.registerMarshaller(new SessionDataMarshaller()); - + RemoteCache _cache = remoteCacheManager.getCache(DEFAULT_CACHE_NAME); - - + ByteArrayOutputStream baos; - try(InputStream is = RemoteQueryManagerTest.class.getClassLoader().getResourceAsStream("session.proto")) + try (InputStream is = RemoteQueryManagerTest.class.getClassLoader().getResourceAsStream("session.proto")) { if (is == null) throw new IllegalStateException("inputstream is null"); - + baos = new ByteArrayOutputStream(); IO.copy(is, baos); } - + String content = baos.toString("UTF-8"); remoteCacheManager.getCache("___protobuf_metadata").put("session.proto", content); - + //put some sessions into the remote cache int numSessions = 10; long currentTime = 500; int maxExpiryTime = 1000; Set expiredSessions = new HashSet<>(); Random r = new Random(); - - for(int i=0; i queryResult = qm.queryExpiredSessions(currentTime); - + Set queryResult = qm.queryExpiredSessions(currentTime); + // Check that the result is correct assertEquals(expiredSessions.size(), queryResult.size()); - for(String s : expiredSessions) + for (String s : expiredSessions) { assertTrue(queryResult.contains(s)); - } + } } } diff --git a/jetty-infinispan/infinispan-remote/pom.xml b/jetty-infinispan/infinispan-remote/pom.xml index 19917c3b74f..6d20c59c0be 100644 --- a/jetty-infinispan/infinispan-remote/pom.xml +++ b/jetty-infinispan/infinispan-remote/pom.xml @@ -15,7 +15,7 @@ install - + org.apache.maven.plugins maven-dependency-plugin @@ -48,20 +48,9 @@ - - - + + + @@ -74,8 +63,8 @@ - - + + @@ -94,7 +83,7 @@ - src/main/assembly/config.xml + src/main/assembly/config.xml @@ -104,27 +93,27 @@ - org.eclipse.jetty - infinispan-common - ${project.version} + org.eclipse.jetty + infinispan-common + ${project.version} - org.infinispan - infinispan-client-hotrod - ${infinispan.version} - provided + org.infinispan + infinispan-client-hotrod + ${infinispan.version} + provided - org.infinispan - infinispan-remote-query-client - ${infinispan.version} - provided + org.infinispan + infinispan-remote-query-client + ${infinispan.version} + provided - org.infinispan.protostream - protostream - 4.2.2.Final - provided + org.infinispan.protostream + protostream + 4.2.2.Final + provided diff --git a/jetty-io/pom.xml b/jetty-io/pom.xml index 903f24e8d04..ef53deabed6 100644 --- a/jetty-io/pom.xml +++ b/jetty-io/pom.xml @@ -1,4 +1,5 @@ - + + jetty-project org.eclipse.jetty diff --git a/jetty-io/src/main/java/org/eclipse/jetty/io/AbstractByteBufferPool.java b/jetty-io/src/main/java/org/eclipse/jetty/io/AbstractByteBufferPool.java index 0b599e47596..71c0fec0c55 100644 --- a/jetty-io/src/main/java/org/eclipse/jetty/io/AbstractByteBufferPool.java +++ b/jetty-io/src/main/java/org/eclipse/jetty/io/AbstractByteBufferPool.java @@ -77,7 +77,9 @@ abstract class AbstractByteBufferPool implements ByteBufferPool if (maxMemory > 0) { while (getMemory(direct) > maxMemory) + { clearFn.accept(direct); + } } } diff --git a/jetty-io/src/main/java/org/eclipse/jetty/io/AbstractConnection.java b/jetty-io/src/main/java/org/eclipse/jetty/io/AbstractConnection.java index d859c34619f..4a06932e70a 100644 --- a/jetty-io/src/main/java/org/eclipse/jetty/io/AbstractConnection.java +++ b/jetty-io/src/main/java/org/eclipse/jetty/io/AbstractConnection.java @@ -41,11 +41,11 @@ public abstract class AbstractConnection implements Connection private static final Logger LOG = Log.getLogger(AbstractConnection.class); private final List _listeners = new CopyOnWriteArrayList<>(); - private final long _created=System.currentTimeMillis(); + private final long _created = System.currentTimeMillis(); private final EndPoint _endPoint; private final Executor _executor; private final Callback _readCallback; - private int _inputBufferSize=2048; + private int _inputBufferSize = 2048; protected AbstractConnection(EndPoint endp, Executor executor) { @@ -96,28 +96,27 @@ public abstract class AbstractConnection implements Connection LOG.warn(e); } }; - - switch(Invocable.getInvocationType(callback)) + + switch (Invocable.getInvocationType(callback)) { case BLOCKING: try { - getExecutor().execute(failCallback); + getExecutor().execute(failCallback); } - catch(RejectedExecutionException e) + catch (RejectedExecutionException e) { LOG.debug(e); callback.failed(x); } break; - + case NON_BLOCKING: failCallback.run(); break; - + case EITHER: Invocable.invokeNonBlocking(failCallback); - } } @@ -125,12 +124,13 @@ public abstract class AbstractConnection implements Connection *

      Utility method to be called to register read interest.

      *

      After a call to this method, {@link #onFillable()} or {@link #onFillInterestedFailed(Throwable)} * will be called back as appropriate.

      + * * @see #onFillable() */ public void fillInterested() { if (LOG.isDebugEnabled()) - LOG.debug("fillInterested {}",this); + LOG.debug("fillInterested {}", this); getEndPoint().fillInterested(_readCallback); } @@ -151,12 +151,14 @@ public abstract class AbstractConnection implements Connection /** *

      Callback method invoked when the endpoint is ready to be read.

      + * * @see #fillInterested() */ public abstract void onFillable(); /** *

      Callback method invoked when the endpoint failed to be ready to be read.

      + * * @param cause the exception that caused the failure */ protected void onFillInterestedFailed(Throwable cause) @@ -199,7 +201,9 @@ public abstract class AbstractConnection implements Connection LOG.debug("onOpen {}", this); for (Listener listener : _listeners) + { onOpened(listener); + } } private void onOpened(Listener listener) @@ -219,13 +223,15 @@ public abstract class AbstractConnection implements Connection { if (LOG.isDebugEnabled()) { - if (cause==null) + if (cause == null) LOG.debug("onClose {}", this); else LOG.debug("onClose " + this, cause); } for (Listener listener : _listeners) + { onClosed(listener); + } } private void onClosed(Listener listener) @@ -291,7 +297,7 @@ public abstract class AbstractConnection implements Connection @Override public final String toString() { - return String.format("%s@%h::%s",getClass().getSimpleName(),this,getEndPoint()); + return String.format("%s@%h::%s", getClass().getSimpleName(), this, getEndPoint()); } public String toConnectionString() @@ -318,8 +324,7 @@ public abstract class AbstractConnection implements Connection @Override public String toString() { - return String.format("AC.ReadCB@%h{%s}", AbstractConnection.this,AbstractConnection.this); + return String.format("AC.ReadCB@%h{%s}", AbstractConnection.this, AbstractConnection.this); } } - } diff --git a/jetty-io/src/main/java/org/eclipse/jetty/io/AbstractEndPoint.java b/jetty-io/src/main/java/org/eclipse/jetty/io/AbstractEndPoint.java index 262e402212c..892105df960 100644 --- a/jetty-io/src/main/java/org/eclipse/jetty/io/AbstractEndPoint.java +++ b/jetty-io/src/main/java/org/eclipse/jetty/io/AbstractEndPoint.java @@ -34,7 +34,7 @@ public abstract class AbstractEndPoint extends IdleTimeout implements EndPoint private static final Logger LOG = Log.getLogger(AbstractEndPoint.class); private final AtomicReference _state = new AtomicReference<>(State.OPEN); - private final long _created=System.currentTimeMillis(); + private final long _created = System.currentTimeMillis(); private volatile Connection _connection; private final FillInterest _fillInterest = new FillInterest() @@ -63,14 +63,14 @@ public abstract class AbstractEndPoint extends IdleTimeout implements EndPoint protected final void shutdownInput() { if (LOG.isDebugEnabled()) - LOG.debug("shutdownInput {}",this); - while(true) + LOG.debug("shutdownInput {}", this); + while (true) { State s = _state.get(); - switch(s) + switch (s) { case OPEN: - if (!_state.compareAndSet(s,State.ISHUTTING)) + if (!_state.compareAndSet(s, State.ISHUTTING)) continue; try { @@ -78,11 +78,11 @@ public abstract class AbstractEndPoint extends IdleTimeout implements EndPoint } finally { - if(!_state.compareAndSet(State.ISHUTTING,State.ISHUT)) + if (!_state.compareAndSet(State.ISHUTTING, State.ISHUT)) { // If somebody else switched to CLOSED while we were ishutting, // then we do the close for them - if (_state.get()==State.CLOSED) + if (_state.get() == State.CLOSED) doOnClose(null); else throw new IllegalStateException(); @@ -95,13 +95,13 @@ public abstract class AbstractEndPoint extends IdleTimeout implements EndPoint return; case OSHUTTING: - if (!_state.compareAndSet(s,State.CLOSED)) + if (!_state.compareAndSet(s, State.CLOSED)) continue; // The thread doing the OSHUT will close return; case OSHUT: - if (!_state.compareAndSet(s,State.CLOSED)) + if (!_state.compareAndSet(s, State.CLOSED)) continue; // Already OSHUT so we close doOnClose(null); @@ -117,14 +117,14 @@ public abstract class AbstractEndPoint extends IdleTimeout implements EndPoint public final void shutdownOutput() { if (LOG.isDebugEnabled()) - LOG.debug("shutdownOutput {}",this); - while(true) + LOG.debug("shutdownOutput {}", this); + while (true) { State s = _state.get(); - switch(s) + switch (s) { case OPEN: - if (!_state.compareAndSet(s,State.OSHUTTING)) + if (!_state.compareAndSet(s, State.OSHUTTING)) continue; try { @@ -132,11 +132,11 @@ public abstract class AbstractEndPoint extends IdleTimeout implements EndPoint } finally { - if(!_state.compareAndSet(State.OSHUTTING,State.OSHUT)) + if (!_state.compareAndSet(State.OSHUTTING, State.OSHUT)) { // If somebody else switched to CLOSED while we were oshutting, // then we do the close for them - if (_state.get()==State.CLOSED) + if (_state.get() == State.CLOSED) doOnClose(null); else throw new IllegalStateException(); @@ -145,13 +145,13 @@ public abstract class AbstractEndPoint extends IdleTimeout implements EndPoint return; case ISHUTTING: - if (!_state.compareAndSet(s,State.CLOSED)) + if (!_state.compareAndSet(s, State.CLOSED)) continue; // The thread doing the ISHUT will close return; case ISHUT: - if (!_state.compareAndSet(s,State.CLOSED)) + if (!_state.compareAndSet(s, State.CLOSED)) continue; // Already ISHUT so we close doOnClose(null); @@ -171,30 +171,30 @@ public abstract class AbstractEndPoint extends IdleTimeout implements EndPoint public final void close() { if (LOG.isDebugEnabled()) - LOG.debug("close {}",this); + LOG.debug("close {}", this); close(null); } public final void close(Throwable failure) { if (LOG.isDebugEnabled()) - LOG.debug("close({}) {}",failure,this); - while(true) + LOG.debug("close({}) {}", failure, this); + while (true) { State s = _state.get(); - switch(s) + switch (s) { case OPEN: case ISHUT: // Already ishut case OSHUT: // Already oshut - if (!_state.compareAndSet(s,State.CLOSED)) + if (!_state.compareAndSet(s, State.CLOSED)) continue; doOnClose(failure); return; case ISHUTTING: // Somebody else ishutting case OSHUTTING: // Somebody else oshutting - if (!_state.compareAndSet(s,State.CLOSED)) + if (!_state.compareAndSet(s, State.CLOSED)) continue; // The thread doing the IO SHUT will call doOnClose return; @@ -235,7 +235,7 @@ public abstract class AbstractEndPoint extends IdleTimeout implements EndPoint @Override public boolean isOutputShutdown() { - switch(_state.get()) + switch (_state.get()) { case CLOSED: case OSHUT: @@ -245,10 +245,11 @@ public abstract class AbstractEndPoint extends IdleTimeout implements EndPoint return false; } } + @Override public boolean isInputShutdown() { - switch(_state.get()) + switch (_state.get()) { case CLOSED: case ISHUT: @@ -262,7 +263,7 @@ public abstract class AbstractEndPoint extends IdleTimeout implements EndPoint @Override public boolean isOpen() { - switch(_state.get()) + switch (_state.get()) { case CLOSED: return false; @@ -273,8 +274,8 @@ public abstract class AbstractEndPoint extends IdleTimeout implements EndPoint public void checkFlush() throws IOException { - State s=_state.get(); - switch(s) + State s = _state.get(); + switch (s) { case OSHUT: case OSHUTTING: @@ -287,8 +288,8 @@ public abstract class AbstractEndPoint extends IdleTimeout implements EndPoint public void checkFill() throws IOException { - State s=_state.get(); - switch(s) + State s = _state.get(); + switch (s) { case ISHUT: case ISHUTTING: @@ -334,8 +335,8 @@ public abstract class AbstractEndPoint extends IdleTimeout implements EndPoint public void onOpen() { if (LOG.isDebugEnabled()) - LOG.debug("onOpen {}",this); - if (_state.get()!=State.OPEN) + LOG.debug("onOpen {}", this); + if (_state.get() != State.OPEN) throw new IllegalStateException(); } @@ -349,7 +350,7 @@ public abstract class AbstractEndPoint extends IdleTimeout implements EndPoint public void onClose(Throwable failure) { super.onClose(); - if (failure==null) + if (failure == null) { _writeFlusher.onClose(); _fillInterest.onClose(); @@ -361,7 +362,6 @@ public abstract class AbstractEndPoint extends IdleTimeout implements EndPoint } } - @Override public void fillInterested(Callback callback) { @@ -409,8 +409,8 @@ public abstract class AbstractEndPoint extends IdleTimeout implements EndPoint if (connection != null && !connection.onIdleExpired()) return; - boolean output_shutdown=isOutputShutdown(); - boolean input_shutdown=isInputShutdown(); + boolean outputShutdown = isOutputShutdown(); + boolean inputShutdown = isInputShutdown(); boolean fillFailed = _fillInterest.onFail(timeout); boolean writeFailed = _writeFlusher.onFail(timeout); @@ -421,26 +421,26 @@ public abstract class AbstractEndPoint extends IdleTimeout implements EndPoint // for a dispatched servlet or suspended request to extend beyond the connections idle // time. So if this test would always close an idle endpoint that is not handled, then // we would need a mode to ignore timeouts for some HTTP states - if (isOpen() && (output_shutdown || input_shutdown) && !(fillFailed || writeFailed)) + if (isOpen() && (outputShutdown || inputShutdown) && !(fillFailed || writeFailed)) close(); else - LOG.debug("Ignored idle endpoint {}",this); + LOG.debug("Ignored idle endpoint {}", this); } @Override public void upgrade(Connection newConnection) { - Connection old_connection = getConnection(); + Connection oldConnection = getConnection(); - ByteBuffer prefilled = (old_connection instanceof Connection.UpgradeFrom) ? - ((Connection.UpgradeFrom)old_connection).onUpgradeFrom() : - null; - old_connection.onClose(null); - old_connection.getEndPoint().setConnection(newConnection); + ByteBuffer prefilled = (oldConnection instanceof Connection.UpgradeFrom) + ? ((Connection.UpgradeFrom)oldConnection).onUpgradeFrom() + : null; + oldConnection.onClose(null); + oldConnection.getEndPoint().setConnection(newConnection); if (LOG.isDebugEnabled()) LOG.debug("{} upgrading from {} to {} with {}", - this, old_connection, newConnection, BufferUtil.toDetailString(prefilled)); + this, oldConnection, newConnection, BufferUtil.toDetailString(prefilled)); if (newConnection instanceof Connection.UpgradeTo) ((Connection.UpgradeTo)newConnection).onUpgradeTo(prefilled); @@ -453,31 +453,31 @@ public abstract class AbstractEndPoint extends IdleTimeout implements EndPoint @Override public String toString() { - return String.format("%s->%s",toEndPointString(),toConnectionString()); + return String.format("%s->%s", toEndPointString(), toConnectionString()); } - + public String toEndPointString() { - Class c=getClass(); - String name=c.getSimpleName(); - while (name.length()==0 && c.getSuperclass()!=null) + Class c = getClass(); + String name = c.getSimpleName(); + while (name.length() == 0 && c.getSuperclass() != null) { - c=c.getSuperclass(); - name=c.getSimpleName(); + c = c.getSuperclass(); + name = c.getSimpleName(); } return String.format("%s@%h{%s<->%s,%s,fill=%s,flush=%s,to=%d/%d}", - name, - this, - getRemoteAddress(), - getLocalAddress(), - _state.get(), - _fillInterest.toStateString(), - _writeFlusher.toStateString(), - getIdleFor(), - getIdleTimeout()); + name, + this, + getRemoteAddress(), + getLocalAddress(), + _state.get(), + _fillInterest.toStateString(), + _writeFlusher.toStateString(), + getIdleFor(), + getIdleTimeout()); } - + public String toConnectionString() { Connection connection = getConnection(); @@ -485,9 +485,8 @@ public abstract class AbstractEndPoint extends IdleTimeout implements EndPoint return ""; if (connection instanceof AbstractConnection) return ((AbstractConnection)connection).toConnectionString(); - return String.format("%s@%x",connection.getClass().getSimpleName(),connection.hashCode()); + return String.format("%s@%x", connection.getClass().getSimpleName(), connection.hashCode()); } - private enum State { diff --git a/jetty-io/src/main/java/org/eclipse/jetty/io/ArrayByteBufferPool.java b/jetty-io/src/main/java/org/eclipse/jetty/io/ArrayByteBufferPool.java index 1adb97256a3..6c00d73d822 100644 --- a/jetty-io/src/main/java/org/eclipse/jetty/io/ArrayByteBufferPool.java +++ b/jetty-io/src/main/java/org/eclipse/jetty/io/ArrayByteBufferPool.java @@ -213,9 +213,9 @@ public class ArrayByteBufferPool extends AbstractByteBufferPool private long getByteBufferCount(boolean direct) { return Arrays.stream(bucketsFor(direct)) - .filter(Objects::nonNull) - .mapToLong(Bucket::size) - .sum(); + .filter(Objects::nonNull) + .mapToLong(Bucket::size) + .sum(); } // Package local for testing diff --git a/jetty-io/src/main/java/org/eclipse/jetty/io/ByteArrayEndPoint.java b/jetty-io/src/main/java/org/eclipse/jetty/io/ByteArrayEndPoint.java index 88921e2a39d..542365364d7 100644 --- a/jetty-io/src/main/java/org/eclipse/jetty/io/ByteArrayEndPoint.java +++ b/jetty-io/src/main/java/org/eclipse/jetty/io/ByteArrayEndPoint.java @@ -39,19 +39,18 @@ import org.eclipse.jetty.util.log.Logger; import org.eclipse.jetty.util.thread.Locker; import org.eclipse.jetty.util.thread.Scheduler; -/* ------------------------------------------------------------ */ -/** ByteArrayEndPoint. - * +/** + * ByteArrayEndPoint. */ public class ByteArrayEndPoint extends AbstractEndPoint { static final Logger LOG = Log.getLogger(ByteArrayEndPoint.class); - static final InetAddress NOIP; + static final InetAddress NOIP; static final InetSocketAddress NOIPPORT; - + static { - InetAddress noip=null; + InetAddress noip = null; try { noip = Inet4Address.getByName("0.0.0.0"); @@ -62,12 +61,11 @@ public class ByteArrayEndPoint extends AbstractEndPoint } finally { - NOIP=noip; - NOIPPORT=new InetSocketAddress(NOIP,0); + NOIP = noip; + NOIPPORT = new InetSocketAddress(NOIP, 0); } } - - + private static final ByteBuffer EOF = BufferUtil.allocate(0); private final Runnable _runFillable = new Runnable() @@ -85,118 +83,104 @@ public class ByteArrayEndPoint extends AbstractEndPoint private ByteBuffer _out; private boolean _growOutput; - /* ------------------------------------------------------------ */ /** * */ public ByteArrayEndPoint() { - this(null,0,null,null); + this(null, 0, null, null); } - /* ------------------------------------------------------------ */ /** * @param input the input bytes * @param outputSize the output size */ public ByteArrayEndPoint(byte[] input, int outputSize) { - this(null,0,input!=null?BufferUtil.toBuffer(input):null,BufferUtil.allocate(outputSize)); + this(null, 0, input != null ? BufferUtil.toBuffer(input) : null, BufferUtil.allocate(outputSize)); } - /* ------------------------------------------------------------ */ /** * @param input the input string (converted to bytes using default encoding charset) * @param outputSize the output size */ public ByteArrayEndPoint(String input, int outputSize) { - this(null,0,input!=null?BufferUtil.toBuffer(input):null,BufferUtil.allocate(outputSize)); + this(null, 0, input != null ? BufferUtil.toBuffer(input) : null, BufferUtil.allocate(outputSize)); } - /* ------------------------------------------------------------ */ public ByteArrayEndPoint(Scheduler scheduler, long idleTimeoutMs) { - this(scheduler,idleTimeoutMs,null,null); + this(scheduler, idleTimeoutMs, null, null); } - /* ------------------------------------------------------------ */ public ByteArrayEndPoint(Scheduler timer, long idleTimeoutMs, byte[] input, int outputSize) { - this(timer,idleTimeoutMs,input!=null?BufferUtil.toBuffer(input):null,BufferUtil.allocate(outputSize)); + this(timer, idleTimeoutMs, input != null ? BufferUtil.toBuffer(input) : null, BufferUtil.allocate(outputSize)); } - /* ------------------------------------------------------------ */ public ByteArrayEndPoint(Scheduler timer, long idleTimeoutMs, String input, int outputSize) { - this(timer,idleTimeoutMs,input!=null?BufferUtil.toBuffer(input):null,BufferUtil.allocate(outputSize)); + this(timer, idleTimeoutMs, input != null ? BufferUtil.toBuffer(input) : null, BufferUtil.allocate(outputSize)); } - /* ------------------------------------------------------------ */ public ByteArrayEndPoint(Scheduler timer, long idleTimeoutMs, ByteBuffer input, ByteBuffer output) { super(timer); if (BufferUtil.hasContent(input)) addInput(input); - _out=output==null?BufferUtil.allocate(1024):output; + _out = output == null ? BufferUtil.allocate(1024) : output; setIdleTimeout(idleTimeoutMs); onOpen(); } - - /* ------------------------------------------------------------ */ + @Override public void doShutdownOutput() { - super.doShutdownOutput(); - try(Locker.Lock lock = _locker.lock()) - { - _hasOutput.signalAll(); - } - } - - /* ------------------------------------------------------------ */ - @Override - public void doClose() - { - super.doClose(); - try(Locker.Lock lock = _locker.lock()) + super.doShutdownOutput(); + try (Locker.Lock lock = _locker.lock()) + { + _hasOutput.signalAll(); + } + } + + @Override + public void doClose() + { + super.doClose(); + try (Locker.Lock lock = _locker.lock()) { _hasOutput.signalAll(); } } - /* ------------------------------------------------------------ */ @Override public InetSocketAddress getLocalAddress() { return NOIPPORT; } - /* ------------------------------------------------------------ */ @Override public InetSocketAddress getRemoteAddress() { return NOIPPORT; } - /* ------------------------------------------------------------ */ @Override protected void onIncompleteFlush() { // Don't need to do anything here as takeOutput does the signalling. } - /* ------------------------------------------------------------ */ protected void execute(Runnable task) { - new Thread(task,"BAEPoint-"+Integer.toHexString(hashCode())).start(); + new Thread(task, "BAEPoint-" + Integer.toHexString(hashCode())).start(); } - /* ------------------------------------------------------------ */ @Override protected void needsFillInterest() throws IOException { - try(Locker.Lock lock = _locker.lock()) + try (Locker.Lock lock = _locker.lock()) { if (!isOpen()) throw new ClosedChannelException(); @@ -207,90 +191,84 @@ public class ByteArrayEndPoint extends AbstractEndPoint } } - /* ------------------------------------------------------------ */ /** + * */ public void addInputEOF() { addInput((ByteBuffer)null); } - /* ------------------------------------------------------------ */ /** * @param in The in to set. */ public void addInput(ByteBuffer in) { - boolean fillable=false; - try(Locker.Lock lock = _locker.lock()) + boolean fillable = false; + try (Locker.Lock lock = _locker.lock()) { if (isEOF(_inQ.peek())) throw new RuntimeIOException(new EOFException()); - boolean was_empty=_inQ.isEmpty(); - if (in==null) + boolean wasEmpty = _inQ.isEmpty(); + if (in == null) { _inQ.add(EOF); - fillable=true; + fillable = true; } if (BufferUtil.hasContent(in)) { _inQ.add(in); - fillable=was_empty; + fillable = wasEmpty; } } if (fillable) _runFillable.run(); } - /* ------------------------------------------------------------ */ public void addInputAndExecute(ByteBuffer in) { - boolean fillable=false; - try(Locker.Lock lock = _locker.lock()) + boolean fillable = false; + try (Locker.Lock lock = _locker.lock()) { if (isEOF(_inQ.peek())) throw new RuntimeIOException(new EOFException()); - boolean was_empty=_inQ.isEmpty(); - if (in==null) + boolean wasEmpty = _inQ.isEmpty(); + if (in == null) { _inQ.add(EOF); - fillable=true; + fillable = true; } if (BufferUtil.hasContent(in)) { _inQ.add(in); - fillable=was_empty; + fillable = wasEmpty; } } if (fillable) execute(_runFillable); } - /* ------------------------------------------------------------ */ public void addInput(String s) { - addInput(BufferUtil.toBuffer(s,StandardCharsets.UTF_8)); + addInput(BufferUtil.toBuffer(s, StandardCharsets.UTF_8)); } - /* ------------------------------------------------------------ */ - public void addInput(String s,Charset charset) + public void addInput(String s, Charset charset) { - addInput(BufferUtil.toBuffer(s,charset)); + addInput(BufferUtil.toBuffer(s, charset)); } - /* ------------------------------------------------------------ */ /** * @return Returns the out. */ public ByteBuffer getOutput() { - try(Locker.Lock lock = _locker.lock()) + try (Locker.Lock lock = _locker.lock()) { return _out; } } - /* ------------------------------------------------------------ */ /** * @return Returns the out. */ @@ -299,17 +277,15 @@ public class ByteArrayEndPoint extends AbstractEndPoint return getOutputString(StandardCharsets.UTF_8); } - /* ------------------------------------------------------------ */ /** * @param charset the charset to encode the output as * @return Returns the out. */ public String getOutputString(Charset charset) { - return BufferUtil.toString(_out,charset); + return BufferUtil.toString(_out, charset); } - /* ------------------------------------------------------------ */ /** * @return Returns the out. */ @@ -317,41 +293,41 @@ public class ByteArrayEndPoint extends AbstractEndPoint { ByteBuffer b; - try(Locker.Lock lock = _locker.lock()) + try (Locker.Lock lock = _locker.lock()) { - b=_out; - _out=BufferUtil.allocate(b.capacity()); + b = _out; + _out = BufferUtil.allocate(b.capacity()); } getWriteFlusher().completeWrite(); return b; } - /* ------------------------------------------------------------ */ - /** Wait for some output + /** + * Wait for some output + * * @param time Time to wait * @param unit Units for time to wait * @return The buffer of output * @throws InterruptedException if interrupted */ - public ByteBuffer waitForOutput(long time,TimeUnit unit) throws InterruptedException + public ByteBuffer waitForOutput(long time, TimeUnit unit) throws InterruptedException { ByteBuffer b; - try(Locker.Lock lock = _locker.lock()) + try (Locker.Lock lock = _locker.lock()) { while (BufferUtil.isEmpty(_out) && !isOutputShutdown()) { - if (!_hasOutput.await(time,unit)) + if (!_hasOutput.await(time, unit)) return null; } - b=_out; - _out=BufferUtil.allocate(b.capacity()); + b = _out; + _out = BufferUtil.allocate(b.capacity()); } getWriteFlusher().completeWrite(); return b; } - /* ------------------------------------------------------------ */ /** * @return Returns the out. */ @@ -360,50 +336,46 @@ public class ByteArrayEndPoint extends AbstractEndPoint return takeOutputString(StandardCharsets.UTF_8); } - /* ------------------------------------------------------------ */ /** * @param charset the charset to encode the output as * @return Returns the out. */ public String takeOutputString(Charset charset) { - ByteBuffer buffer=takeOutput(); - return BufferUtil.toString(buffer,charset); + ByteBuffer buffer = takeOutput(); + return BufferUtil.toString(buffer, charset); } - /* ------------------------------------------------------------ */ /** * @param out The out to set. */ public void setOutput(ByteBuffer out) { - try(Locker.Lock lock = _locker.lock()) + try (Locker.Lock lock = _locker.lock()) { _out = out; } getWriteFlusher().completeWrite(); } - /* ------------------------------------------------------------ */ /** * @return true if there are bytes remaining to be read from the encoded input */ public boolean hasMore() { - return getOutput().position()>0; + return getOutput().position() > 0; } - /* ------------------------------------------------------------ */ /* * @see org.eclipse.io.EndPoint#fill(org.eclipse.io.Buffer) */ @Override public int fill(ByteBuffer buffer) throws IOException { - int filled=0; - try(Locker.Lock lock = _locker.lock()) + int filled = 0; + try (Locker.Lock lock = _locker.lock()) { - while(true) + while (true) { if (!isOpen()) throw new EofException("CLOSED"); @@ -414,16 +386,16 @@ public class ByteArrayEndPoint extends AbstractEndPoint if (_inQ.isEmpty()) break; - ByteBuffer in= _inQ.peek(); + ByteBuffer in = _inQ.peek(); if (isEOF(in)) { - filled=-1; + filled = -1; break; } if (BufferUtil.hasContent(in)) { - filled=BufferUtil.append(buffer,in); + filled = BufferUtil.append(buffer, in); if (BufferUtil.isEmpty(in)) _inQ.poll(); break; @@ -432,51 +404,50 @@ public class ByteArrayEndPoint extends AbstractEndPoint } } - if (filled>0) + if (filled > 0) notIdle(); - else if (filled<0) + else if (filled < 0) shutdownInput(); return filled; } - /* ------------------------------------------------------------ */ /* * @see org.eclipse.io.EndPoint#flush(org.eclipse.io.Buffer, org.eclipse.io.Buffer, org.eclipse.io.Buffer) */ @Override public boolean flush(ByteBuffer... buffers) throws IOException { - boolean flushed=true; - try(Locker.Lock lock = _locker.lock()) + boolean flushed = true; + try (Locker.Lock lock = _locker.lock()) { if (!isOpen()) throw new IOException("CLOSED"); if (isOutputShutdown()) throw new IOException("OSHUT"); - - boolean idle=true; + + boolean idle = true; for (ByteBuffer b : buffers) { if (BufferUtil.hasContent(b)) { - if (_growOutput && b.remaining()>BufferUtil.space(_out)) + if (_growOutput && b.remaining() > BufferUtil.space(_out)) { BufferUtil.compact(_out); - if (b.remaining()>BufferUtil.space(_out)) + if (b.remaining() > BufferUtil.space(_out)) { - ByteBuffer n = BufferUtil.allocate(_out.capacity()+b.remaining()*2); - BufferUtil.append(n,_out); - _out=n; + ByteBuffer n = BufferUtil.allocate(_out.capacity() + b.remaining() * 2); + BufferUtil.append(n, _out); + _out = n; } } - if (BufferUtil.append(_out,b)>0) - idle=false; + if (BufferUtil.append(_out, b) > 0) + idle = false; if (BufferUtil.hasContent(b)) { - flushed=false; + flushed = false; break; } } @@ -490,14 +461,13 @@ public class ByteArrayEndPoint extends AbstractEndPoint return flushed; } - /* ------------------------------------------------------------ */ /** * */ @Override public void reset() { - try(Locker.Lock lock = _locker.lock()) + try (Locker.Lock lock = _locker.lock()) { _inQ.clear(); _hasOutput.signalAll(); @@ -506,7 +476,6 @@ public class ByteArrayEndPoint extends AbstractEndPoint super.reset(); } - /* ------------------------------------------------------------ */ /* * @see org.eclipse.io.EndPoint#getConnection() */ @@ -516,7 +485,6 @@ public class ByteArrayEndPoint extends AbstractEndPoint return null; } - /* ------------------------------------------------------------ */ /** * @return the growOutput */ @@ -525,41 +493,39 @@ public class ByteArrayEndPoint extends AbstractEndPoint return _growOutput; } - /* ------------------------------------------------------------ */ /** * @param growOutput the growOutput to set */ public void setGrowOutput(boolean growOutput) { - _growOutput=growOutput; + _growOutput = growOutput; } - /* ------------------------------------------------------------ */ @Override public String toString() { int q; ByteBuffer b; String o; - try(Locker.Lock lock = _locker.lock()) + try (Locker.Lock lock = _locker.lock()) { - q=_inQ.size(); - b=_inQ.peek(); - o=BufferUtil.toDetailString(_out); + q = _inQ.size(); + b = _inQ.peek(); + o = BufferUtil.toDetailString(_out); } - return String.format("%s[q=%d,q[0]=%s,o=%s]",super.toString(),q,b,o); + return String.format("%s[q=%d,q[0]=%s,o=%s]", super.toString(), q, b, o); } - /* ------------------------------------------------------------ */ /** * Compares a ByteBuffer Object to EOF by Reference + * * @param buffer the input ByteBuffer to be compared to EOF * @return Whether the reference buffer is equal to that of EOF */ private static boolean isEOF(ByteBuffer buffer) { @SuppressWarnings("ReferenceEquality") - boolean is_EOF = (buffer==EOF); - return is_EOF; + boolean isEof = (buffer == EOF); + return isEof; } } diff --git a/jetty-io/src/main/java/org/eclipse/jetty/io/ByteBufferPool.java b/jetty-io/src/main/java/org/eclipse/jetty/io/ByteBufferPool.java index 95e52124a28..68db0b2880b 100644 --- a/jetty-io/src/main/java/org/eclipse/jetty/io/ByteBufferPool.java +++ b/jetty-io/src/main/java/org/eclipse/jetty/io/ByteBufferPool.java @@ -41,7 +41,7 @@ public interface ByteBufferPool *

      The returned buffer may have a bigger capacity than the size being * requested but it will have the limit set to the given size.

      * - * @param size the size of the buffer + * @param size the size of the buffer * @param direct whether the buffer must be direct or not * @return the requested buffer * @see #release(ByteBuffer) @@ -61,7 +61,7 @@ public interface ByteBufferPool *

      Creates a new ByteBuffer of the given capacity and the given directness.

      * * @param capacity the ByteBuffer capacity - * @param direct the ByteBuffer directness + * @param direct the ByteBuffer directness * @return a newly allocated ByteBuffer */ default ByteBuffer newByteBuffer(int capacity, boolean direct) @@ -110,7 +110,9 @@ public interface ByteBufferPool { long length = 0; for (ByteBuffer buffer : buffers) + { length += buffer.remaining(); + } return length; } diff --git a/jetty-io/src/main/java/org/eclipse/jetty/io/ChannelEndPoint.java b/jetty-io/src/main/java/org/eclipse/jetty/io/ChannelEndPoint.java index 117bb49fea9..0d58fde8245 100644 --- a/jetty-io/src/main/java/org/eclipse/jetty/io/ChannelEndPoint.java +++ b/jetty-io/src/main/java/org/eclipse/jetty/io/ChannelEndPoint.java @@ -57,19 +57,19 @@ public abstract class ChannelEndPoint extends AbstractEndPoint implements Manage */ protected int _desiredInterestOps; - private abstract class RunnableTask implements Runnable, Invocable + private abstract class RunnableTask implements Runnable, Invocable { final String _operation; protected RunnableTask(String op) { - _operation=op; + _operation = op; } @Override public String toString() { - return String.format("CEP:%s:%s:%s",ChannelEndPoint.this,_operation,getInvocationType()); + return String.format("CEP:%s:%s:%s", ChannelEndPoint.this, _operation, getInvocationType()); } } @@ -110,7 +110,7 @@ public abstract class ChannelEndPoint extends AbstractEndPoint implements Manage { return getFillInterest().getCallbackInvocationType(); } - + @Override public void run() { @@ -125,7 +125,7 @@ public abstract class ChannelEndPoint extends AbstractEndPoint implements Manage { return getWriteFlusher().getCallbackInvocationType(); } - + @Override public void run() { @@ -135,9 +135,8 @@ public abstract class ChannelEndPoint extends AbstractEndPoint implements Manage @Override public String toString() { - return String.format("CEP:%s:%s:%s->%s",ChannelEndPoint.this,_operation,getInvocationType(),getWriteFlusher()); + return String.format("CEP:%s:%s:%s->%s", ChannelEndPoint.this, _operation, getInvocationType(), getWriteFlusher()); } - }; private final Runnable _runCompleteWriteFillable = new RunnableCloseable("runCompleteWriteFillable") @@ -147,18 +146,18 @@ public abstract class ChannelEndPoint extends AbstractEndPoint implements Manage { InvocationType fillT = getFillInterest().getCallbackInvocationType(); InvocationType flushT = getWriteFlusher().getCallbackInvocationType(); - if (fillT==flushT) + if (fillT == flushT) return fillT; - - if (fillT==InvocationType.EITHER && flushT==InvocationType.NON_BLOCKING) + + if (fillT == InvocationType.EITHER && flushT == InvocationType.NON_BLOCKING) return InvocationType.EITHER; - - if (fillT==InvocationType.NON_BLOCKING && flushT==InvocationType.EITHER) + + if (fillT == InvocationType.NON_BLOCKING && flushT == InvocationType.EITHER) return InvocationType.EITHER; - + return InvocationType.BLOCKING; } - + @Override public void run() { @@ -170,10 +169,10 @@ public abstract class ChannelEndPoint extends AbstractEndPoint implements Manage public ChannelEndPoint(ByteChannel channel, ManagedSelector selector, SelectionKey key, Scheduler scheduler) { super(scheduler); - _channel=channel; - _selector=selector; - _key=key; - _gather=(channel instanceof GatheringByteChannel)?(GatheringByteChannel)channel:null; + _channel = channel; + _selector = selector; + _key = key; + _gather = (channel instanceof GatheringByteChannel) ? (GatheringByteChannel)channel : null; } @Override @@ -216,7 +215,7 @@ public abstract class ChannelEndPoint extends AbstractEndPoint implements Manage } finally { - if (_selector!=null) + if (_selector != null) _selector.destroyEndPoint(this, cause); } } @@ -227,17 +226,17 @@ public abstract class ChannelEndPoint extends AbstractEndPoint implements Manage if (isInputShutdown()) return -1; - int pos=BufferUtil.flipToFill(buffer); + int pos = BufferUtil.flipToFill(buffer); int filled; try { filled = _channel.read(buffer); - if (filled>0) + if (filled > 0) notIdle(); - else if (filled==-1) + else if (filled == -1) shutdownInput(); } - catch(IOException e) + catch (IOException e) { LOG.debug(e); shutdownInput(); @@ -245,7 +244,7 @@ public abstract class ChannelEndPoint extends AbstractEndPoint implements Manage } finally { - BufferUtil.flipToFlush(buffer,pos); + BufferUtil.flipToFlush(buffer, pos); } if (LOG.isDebugEnabled()) LOG.debug("filled {} {}", filled, BufferUtil.toDetailString(buffer)); @@ -255,22 +254,22 @@ public abstract class ChannelEndPoint extends AbstractEndPoint implements Manage @Override public boolean flush(ByteBuffer... buffers) throws IOException { - long flushed=0; + long flushed = 0; try { - if (buffers.length==1) - flushed=_channel.write(buffers[0]); - else if (_gather!=null && buffers.length>1) - flushed=_gather.write(buffers,0,buffers.length); + if (buffers.length == 1) + flushed = _channel.write(buffers[0]); + else if (_gather != null && buffers.length > 1) + flushed = _gather.write(buffers, 0, buffers.length); else { for (ByteBuffer b : buffers) { if (b.hasRemaining()) { - int l=_channel.write(b); - if (l>0) - flushed+=l; + int l = _channel.write(b); + if (l > 0) + flushed += l; if (b.hasRemaining()) break; } @@ -284,12 +283,14 @@ public abstract class ChannelEndPoint extends AbstractEndPoint implements Manage throw new EofException(e); } - if (flushed>0) + if (flushed > 0) notIdle(); for (ByteBuffer b : buffers) + { if (!BufferUtil.isEmpty(b)) return false; + } return true; } @@ -305,7 +306,6 @@ public abstract class ChannelEndPoint extends AbstractEndPoint implements Manage return _channel; } - @Override protected void needsFillInterest() { @@ -328,7 +328,7 @@ public abstract class ChannelEndPoint extends AbstractEndPoint implements Manage int readyOps = _key.readyOps(); int oldInterestOps; int newInterestOps; - synchronized(this) + synchronized (this) { _updatePending = true; // Remove the readyOps, that here can only be OP_READ or OP_WRITE (or both). @@ -344,16 +344,16 @@ public abstract class ChannelEndPoint extends AbstractEndPoint implements Manage LOG.debug("onSelected {}->{} r={} w={} for {}", oldInterestOps, newInterestOps, fillable, flushable, this); // return task to complete the job - Runnable task= fillable - ? (flushable - ? _runCompleteWriteFillable - : _runFillable) - : (flushable - ? _runCompleteWrite - : null); + Runnable task = fillable + ? (flushable + ? _runCompleteWriteFillable + : _runFillable) + : (flushable + ? _runCompleteWrite + : null); if (LOG.isDebugEnabled()) - LOG.debug("task {}",task); + LOG.debug("task {}", task); return task; } @@ -368,7 +368,7 @@ public abstract class ChannelEndPoint extends AbstractEndPoint implements Manage { int oldInterestOps; int newInterestOps; - synchronized(this) + synchronized (this) { _updatePending = false; oldInterestOps = _currentInterestOps; @@ -405,7 +405,7 @@ public abstract class ChannelEndPoint extends AbstractEndPoint implements Manage int oldInterestOps; int newInterestOps; boolean pending; - synchronized(this) + synchronized (this) { pending = _updatePending; oldInterestOps = _desiredInterestOps; @@ -417,7 +417,7 @@ public abstract class ChannelEndPoint extends AbstractEndPoint implements Manage if (LOG.isDebugEnabled()) LOG.debug("changeInterests p={} {}->{} for {}", pending, oldInterestOps, newInterestOps, this); - if (!pending && _selector!=null) + if (!pending && _selector != null) _selector.submit(_updateKeyAction); } @@ -426,10 +426,10 @@ public abstract class ChannelEndPoint extends AbstractEndPoint implements Manage { // We do a best effort to print the right toString() and that's it. return String.format("%s{io=%d/%d,kio=%d,kro=%d}", - super.toEndPointString(), - _currentInterestOps, - _desiredInterestOps, - ManagedSelector.safeInterestOps(_key), - ManagedSelector.safeReadyOps(_key)); + super.toEndPointString(), + _currentInterestOps, + _desiredInterestOps, + ManagedSelector.safeInterestOps(_key), + ManagedSelector.safeReadyOps(_key)); } } diff --git a/jetty-io/src/main/java/org/eclipse/jetty/io/Connection.java b/jetty-io/src/main/java/org/eclipse/jetty/io/Connection.java index 50ca3833ec1..885aee928cd 100644 --- a/jetty-io/src/main/java/org/eclipse/jetty/io/Connection.java +++ b/jetty-io/src/main/java/org/eclipse/jetty/io/Connection.java @@ -56,6 +56,7 @@ public interface Connection extends Closeable /** *

      Callback method invoked when this connection is closed.

      *

      Creators of the connection implementation are responsible for calling this method.

      + * * @param cause The cause of the close or null for a normal close */ public void onClose(Throwable cause); @@ -64,7 +65,7 @@ public interface Connection extends Closeable * @return the {@link EndPoint} associated with this Connection. */ public EndPoint getEndPoint(); - + /** *

      Performs a logical close of this connection.

      *

      For simple connections, this may just mean to delegate the close to the associated @@ -83,16 +84,20 @@ public interface Connection extends Closeable * immediately and the EndPoint left in the state it was before the idle timeout event.

      * * @return true to let the EndPoint handle the idle timeout, - * false to tell the EndPoint to halt the handling of the idle timeout. + * false to tell the EndPoint to halt the handling of the idle timeout. */ public boolean onIdleExpired(); public long getMessagesIn(); + public long getMessagesOut(); + public long getBytesIn(); + public long getBytesOut(); + public long getCreatedTimeStamp(); - + public interface UpgradeFrom { /** @@ -105,12 +110,13 @@ public interface Connection extends Closeable */ ByteBuffer onUpgradeFrom(); } - + public interface UpgradeTo { /** *

      Callback method invoked when this connection is upgraded.

      *

      This must be called before {@link #onOpen()}.

      + * * @param prefilled An optional buffer that can contain prefilled data. Typically this * results from an upgrade of one protocol to the other where the old connection has buffered * data destined for the new connection. The new connection must take ownership of the buffer @@ -118,8 +124,8 @@ public interface Connection extends Closeable */ void onUpgradeTo(ByteBuffer prefilled); } - - /** + + /** *

      A Listener for connection events.

      *

      Listeners can be added to a {@link Connection} to get open and close events. * The AbstractConnectionFactory implements a pattern where objects implement diff --git a/jetty-io/src/main/java/org/eclipse/jetty/io/ConnectionStatistics.java b/jetty-io/src/main/java/org/eclipse/jetty/io/ConnectionStatistics.java index 62daa30a0c8..bf062408cb0 100644 --- a/jetty-io/src/main/java/org/eclipse/jetty/io/ConnectionStatistics.java +++ b/jetty-io/src/main/java/org/eclipse/jetty/io/ConnectionStatistics.java @@ -213,7 +213,7 @@ public class ConnectionStatistics extends AbstractLifeCycle implements Connectio @Override public void dump(Appendable out, String indent) throws IOException { - Dumpable.dumpObjects(out,indent,this, + Dumpable.dumpObjects(out, indent, this, String.format("connections=%s", _connections), String.format("durations=%s", _connectionsDuration), String.format("bytes in/out=%s/%s", getReceivedBytes(), getSentBytes()), diff --git a/jetty-io/src/main/java/org/eclipse/jetty/io/CyclicTimeout.java b/jetty-io/src/main/java/org/eclipse/jetty/io/CyclicTimeout.java index c9f05f95591..211b1e11ed2 100644 --- a/jetty-io/src/main/java/org/eclipse/jetty/io/CyclicTimeout.java +++ b/jetty-io/src/main/java/org/eclipse/jetty/io/CyclicTimeout.java @@ -84,9 +84,9 @@ public abstract class CyclicTimeout implements Destroyable public boolean schedule(long delay, TimeUnit units) { long now = System.nanoTime(); - long new_timeout_at = now + units.toNanos(delay); + long newTimeoutAt = now + units.toNanos(delay); - Wakeup new_wakeup = null; + Wakeup newWakeup = null; boolean result; while (true) { @@ -95,16 +95,16 @@ public abstract class CyclicTimeout implements Destroyable // Is the current wakeup good to use? ie before our timeout time? Wakeup wakeup = timeout._wakeup; - if (wakeup == null || wakeup._at > new_timeout_at) + if (wakeup == null || wakeup._at > newTimeoutAt) // No, we need an earlier wakeup. - wakeup = new_wakeup = new Wakeup(new_timeout_at, wakeup); + wakeup = newWakeup = new Wakeup(newTimeoutAt, wakeup); - if (_timeout.compareAndSet(timeout, new Timeout(new_timeout_at, wakeup))) + if (_timeout.compareAndSet(timeout, new Timeout(newTimeoutAt, wakeup))) { if (LOG.isDebugEnabled()) LOG.debug("Installed timeout in {} ms, waking up in {} ms", - units.toMillis(delay), - TimeUnit.NANOSECONDS.toMillis(wakeup._at - now)); + units.toMillis(delay), + TimeUnit.NANOSECONDS.toMillis(wakeup._at - now)); break; } } @@ -112,8 +112,8 @@ public abstract class CyclicTimeout implements Destroyable // If we created a new wakeup, we need to actually schedule it. // Any wakeup that is created and discarded by the failed CAS will not be // in the wakeup chain, will not have a scheduler task set and will be GC'd. - if (new_wakeup != null) - new_wakeup.schedule(now); + if (newWakeup != null) + newWakeup.schedule(now); return result; } @@ -133,8 +133,8 @@ public abstract class CyclicTimeout implements Destroyable Timeout timeout = _timeout.get(); result = timeout._at != MAX_VALUE; Wakeup wakeup = timeout._wakeup; - Timeout new_timeout = wakeup == null ? NOT_SET : new Timeout(MAX_VALUE, wakeup); - if (_timeout.compareAndSet(timeout, new_timeout)) + Timeout newTimeout = wakeup == null ? NOT_SET : new Timeout(MAX_VALUE, wakeup); + if (_timeout.compareAndSet(timeout, newTimeout)) break; } return result; @@ -179,10 +179,10 @@ public abstract class CyclicTimeout implements Destroyable public String toString() { return String.format("%s@%x:%dms,%s", - getClass().getSimpleName(), - hashCode(), - TimeUnit.NANOSECONDS.toMillis(_at - System.nanoTime()), - _wakeup); + getClass().getSimpleName(), + hashCode(), + TimeUnit.NANOSECONDS.toMillis(_at - System.nanoTime()), + _wakeup); } } @@ -217,8 +217,8 @@ public abstract class CyclicTimeout implements Destroyable public void run() { long now = System.nanoTime(); - Wakeup new_wakeup = null; - boolean has_expired = false; + Wakeup newWakeup = null; + boolean hasExpired = false; while (true) { Timeout timeout = _timeout.get(); @@ -246,12 +246,12 @@ public abstract class CyclicTimeout implements Destroyable // Remove ourselves (and any prior Wakeup) from the wakeup list. wakeup = wakeup._next; - Timeout new_timeout; + Timeout newTimeout; if (timeout._at <= now) { // We have timed out! - has_expired = true; - new_timeout = wakeup == null ? NOT_SET : new Timeout(MAX_VALUE, wakeup); + hasExpired = true; + newTimeout = wakeup == null ? NOT_SET : new Timeout(MAX_VALUE, wakeup); } else if (timeout._at != MAX_VALUE) { @@ -259,26 +259,26 @@ public abstract class CyclicTimeout implements Destroyable // Is the current wakeup good to use? ie before our timeout time? if (wakeup == null || wakeup._at >= timeout._at) // No, we need an earlier wakeup. - wakeup = new_wakeup = new Wakeup(timeout._at, wakeup); - new_timeout = new Timeout(timeout._at, wakeup); + wakeup = newWakeup = new Wakeup(timeout._at, wakeup); + newTimeout = new Timeout(timeout._at, wakeup); } else { // We don't timeout, preserve scheduled chain. - new_timeout = wakeup == null ? NOT_SET : new Timeout(MAX_VALUE, wakeup); + newTimeout = wakeup == null ? NOT_SET : new Timeout(MAX_VALUE, wakeup); } // Loop until we succeed in changing state or we are a noop! - if (_timeout.compareAndSet(timeout, new_timeout)) + if (_timeout.compareAndSet(timeout, newTimeout)) break; } // If we created a new wakeup, we need to actually schedule it. - if (new_wakeup != null) - new_wakeup.schedule(now); + if (newWakeup != null) + newWakeup.schedule(now); // If we expired, then do the callback. - if (has_expired) + if (hasExpired) onTimeoutExpired(); } @@ -286,10 +286,10 @@ public abstract class CyclicTimeout implements Destroyable public String toString() { return String.format("%s@%x:%dms->%s", - getClass().getSimpleName(), - hashCode(), - _at == MAX_VALUE ? _at : TimeUnit.NANOSECONDS.toMillis(_at - System.nanoTime()), - _next); + getClass().getSimpleName(), + hashCode(), + _at == MAX_VALUE ? _at : TimeUnit.NANOSECONDS.toMillis(_at - System.nanoTime()), + _next); } } } diff --git a/jetty-io/src/main/java/org/eclipse/jetty/io/EndPoint.java b/jetty-io/src/main/java/org/eclipse/jetty/io/EndPoint.java index b5cec4ce63f..875ad2521da 100644 --- a/jetty-io/src/main/java/org/eclipse/jetty/io/EndPoint.java +++ b/jetty-io/src/main/java/org/eclipse/jetty/io/EndPoint.java @@ -31,7 +31,6 @@ import org.eclipse.jetty.util.IteratingCallback; import org.eclipse.jetty.util.thread.Invocable; /** - * * A transport EndPoint * *

      Asynchronous Methods

      @@ -95,29 +94,26 @@ import org.eclipse.jetty.util.thread.Invocable; *
    */ public interface EndPoint extends Closeable -{ - /* ------------------------------------------------------------ */ +{ + /** * @return The local Inet address to which this EndPoint is bound, or null * if this EndPoint does not represent a network connection. */ InetSocketAddress getLocalAddress(); - /* ------------------------------------------------------------ */ /** * @return The remote Inet address to which this EndPoint is bound, or null * if this EndPoint does not represent a network connection. */ InetSocketAddress getRemoteAddress(); - /* ------------------------------------------------------------ */ boolean isOpen(); - /* ------------------------------------------------------------ */ long getCreatedTimeStamp(); - /* ------------------------------------------------------------ */ - /** Shutdown the output. + /** + * Shutdown the output. *

    This call indicates that no more data will be sent on this endpoint that * that the remote end should read an EOF once all previously sent data has been * consumed. Shutdown may be done either at the TCP/IP level, as a protocol exchange (Eg @@ -128,20 +124,22 @@ public interface EndPoint extends Closeable */ void shutdownOutput(); - /* ------------------------------------------------------------ */ - /** Test if output is shutdown. + /** + * Test if output is shutdown. * The output is shutdown by a call to {@link #shutdownOutput()} * or {@link #close()}. + * * @return true if the output is shutdown or the endpoint is closed. */ boolean isOutputShutdown(); - /* ------------------------------------------------------------ */ - /** Test if the input is shutdown. + /** + * Test if the input is shutdown. * The input is shutdown if an EOF has been read while doing * a {@link #fill(ByteBuffer)}. Once the input is shutdown, all calls to * {@link #fill(ByteBuffer)} will return -1, until such time as the * end point is close, when they will return {@link EofException}. + * * @return True if the input is shutdown or the endpoint is closed. */ boolean isInputShutdown(); @@ -152,11 +150,12 @@ public interface EndPoint extends Closeable @Override default void close() { - close (null); + close(null); } /** * Close any backing stream associated with the endpoint, passing a cause + * * @param cause the reason for the close or null */ void close(Throwable cause); @@ -174,11 +173,11 @@ public interface EndPoint extends Closeable */ int fill(ByteBuffer buffer) throws IOException; - /** * Flush data from the passed header/buffer to this endpoint. As many bytes as can be consumed * are taken from the header/buffer position up until the buffer limit. The header/buffers position * is updated to indicate how many bytes have been consumed. + * * @param buffer the buffers to flush * @return True IFF all the buffers have been consumed and the endpoint has flushed the data to its * destination (ie is not buffering any data). @@ -186,32 +185,32 @@ public interface EndPoint extends Closeable */ boolean flush(ByteBuffer... buffer) throws IOException; - /* ------------------------------------------------------------ */ /** * @return The underlying transport object (socket, channel, etc.) */ Object getTransport(); - /* ------------------------------------------------------------ */ - /** Get the max idle time in ms. + /** + * Get the max idle time in ms. *

    The max idle time is the time the endpoint can be idle before * extraordinary handling takes place. + * * @return the max idle time in ms or if ms <= 0 implies an infinite timeout */ long getIdleTimeout(); - /* ------------------------------------------------------------ */ - /** Set the idle timeout. + /** + * Set the idle timeout. + * * @param idleTimeout the idle timeout in MS. Timeout <= 0 implies an infinite timeout */ void setIdleTimeout(long idleTimeout); - /** *

    Requests callback methods to be invoked when a call to {@link #fill(ByteBuffer)} would return data or EOF.

    * * @param callback the callback to call when an error occurs or we are readable. The callback may implement the {@link Invocable} interface to - * self declare its blocking status. Non-blocking callbacks may be called more efficiently without dispatch delays. + * self declare its blocking status. Non-blocking callbacks may be called more efficiently without dispatch delays. * @throws ReadPendingException if another read operation is concurrent. */ void fillInterested(Callback callback) throws ReadPendingException; @@ -257,28 +256,33 @@ public interface EndPoint extends Closeable /** *

    Callback method invoked when this {@link EndPoint} is opened.

    + * * @see #onClose(Throwable) */ void onOpen(); /** *

    Callback method invoked when this {@link EndPoint} is close.

    + * * @param cause The reason for the close, or null if a normal close. * @see #onOpen() */ void onClose(Throwable cause); - /** Is the endpoint optimized for DirectBuffer usage + /** + * Is the endpoint optimized for DirectBuffer usage + * * @return True if direct buffers can be used optimally. */ boolean isOptimizedForDirectBuffers(); - - /** Upgrade connections. + /** + * Upgrade connections. * Close the old connection, update the endpoint and open the new connection. * If the oldConnection is an instance of {@link Connection.UpgradeFrom} then * a prefilled buffer is requested and passed to the newConnection if it is an instance * of {@link Connection.UpgradeTo} + * * @param newConnection The connection to upgrade to */ public void upgrade(Connection newConnection); diff --git a/jetty-io/src/main/java/org/eclipse/jetty/io/EofException.java b/jetty-io/src/main/java/org/eclipse/jetty/io/EofException.java index eb90f970b47..fc8c0aa21e0 100644 --- a/jetty-io/src/main/java/org/eclipse/jetty/io/EofException.java +++ b/jetty-io/src/main/java/org/eclipse/jetty/io/EofException.java @@ -20,10 +20,9 @@ package org.eclipse.jetty.io; import java.io.EOFException; - -/* ------------------------------------------------------------ */ -/** A Jetty specialization of EOFException. - *

    This is thrown by Jetty to distinguish between EOF received from +/** + * A Jetty specialization of EOFException. + *

    This is thrown by Jetty to distinguish between EOF received from * the connection, vs and EOF thrown by some application talking to some other file/socket etc. * The only difference in handling is that Jetty EOFs are logged less verbosely. */ @@ -32,15 +31,15 @@ public class EofException extends EOFException implements QuietException public EofException() { } - + public EofException(String reason) { super(reason); } - + public EofException(Throwable th) { - if (th!=null) + if (th != null) initCause(th); } } diff --git a/jetty-io/src/main/java/org/eclipse/jetty/io/FillInterest.java b/jetty-io/src/main/java/org/eclipse/jetty/io/FillInterest.java index 5daad36db21..6a90d9c2153 100644 --- a/jetty-io/src/main/java/org/eclipse/jetty/io/FillInterest.java +++ b/jetty-io/src/main/java/org/eclipse/jetty/io/FillInterest.java @@ -35,7 +35,7 @@ import org.eclipse.jetty.util.thread.Invocable.InvocationType; */ public abstract class FillInterest { - private final static Logger LOG = Log.getLogger(FillInterest.class); + private static final Logger LOG = Log.getLogger(FillInterest.class); private final AtomicReference _interested = new AtomicReference<>(null); protected FillInterest() @@ -56,9 +56,9 @@ public abstract class FillInterest { LOG.warn("Read pending for {} prevented {}", _interested, callback); throw new ReadPendingException(); - } + } } - + /** * Call to register interest in a callback when a read is possible. * The callback will be called either immediately if {@link #needsFillInterest()} @@ -76,8 +76,8 @@ public abstract class FillInterest return false; if (LOG.isDebugEnabled()) - LOG.debug("interested {}",this); - + LOG.debug("interested {}", this); + try { needsFillInterest(); @@ -86,7 +86,7 @@ public abstract class FillInterest { onFail(e); } - + return true; } @@ -96,7 +96,7 @@ public abstract class FillInterest public boolean fillable() { if (LOG.isDebugEnabled()) - LOG.debug("fillable {}",this); + LOG.debug("fillable {}", this); Callback callback = _interested.get(); if (callback != null && _interested.compareAndSet(callback, null)) { @@ -104,7 +104,7 @@ public abstract class FillInterest return true; } if (LOG.isDebugEnabled()) - LOG.debug("{} lost race {}",this,callback); + LOG.debug("{} lost race {}", this, callback); return false; } @@ -115,7 +115,7 @@ public abstract class FillInterest { return _interested.get() != null; } - + public InvocationType getCallbackInvocationType() { Callback callback = _interested.get(); @@ -144,7 +144,7 @@ public abstract class FillInterest public void onClose() { if (LOG.isDebugEnabled()) - LOG.debug("onClose {}",this); + LOG.debug("onClose {}", this); Callback callback = _interested.get(); if (callback != null && _interested.compareAndSet(callback, null)) callback.failed(new ClosedChannelException()); @@ -156,10 +156,9 @@ public abstract class FillInterest return String.format("FillInterest@%x{%s}", hashCode(), _interested.get()); } - public String toStateString() { - return _interested.get()==null?"-":"FI"; + return _interested.get() == null ? "-" : "FI"; } /** @@ -169,5 +168,5 @@ public abstract class FillInterest * * @throws IOException if unable to fulfill interest in fill */ - abstract protected void needsFillInterest() throws IOException; + protected abstract void needsFillInterest() throws IOException; } diff --git a/jetty-io/src/main/java/org/eclipse/jetty/io/LeakTrackingByteBufferPool.java b/jetty-io/src/main/java/org/eclipse/jetty/io/LeakTrackingByteBufferPool.java index f286d5cc97e..300fceb2430 100644 --- a/jetty-io/src/main/java/org/eclipse/jetty/io/LeakTrackingByteBufferPool.java +++ b/jetty-io/src/main/java/org/eclipse/jetty/io/LeakTrackingByteBufferPool.java @@ -47,7 +47,7 @@ public class LeakTrackingByteBufferPool extends ContainerLifeCycle implements By } }; - private final static boolean NOISY = Boolean.getBoolean(LeakTrackingByteBufferPool.class.getName() + ".NOISY"); + private static final boolean NOISY = Boolean.getBoolean(LeakTrackingByteBufferPool.class.getName() + ".NOISY"); private final ByteBufferPool delegate; private final AtomicLong leakedReleases = new AtomicLong(0); private final AtomicLong leakedAcquires = new AtomicLong(0); @@ -69,7 +69,7 @@ public class LeakTrackingByteBufferPool extends ContainerLifeCycle implements By { leakedAcquires.incrementAndGet(); LOG.info(String.format("ByteBuffer acquire %s leaked.acquired=%s", leakDetector.id(buffer), leaked ? "normal" : "LEAK"), - new Throwable("LeakStack.Acquire")); + new Throwable("LeakStack.Acquire")); } return buffer; } @@ -84,7 +84,7 @@ public class LeakTrackingByteBufferPool extends ContainerLifeCycle implements By { leakedReleases.incrementAndGet(); LOG.info(String.format("ByteBuffer release %s leaked.released=%s", leakDetector.id(buffer), leaked ? "normal" : "LEAK"), new Throwable( - "LeakStack.Release")); + "LeakStack.Release")); } delegate.release(buffer); } diff --git a/jetty-io/src/main/java/org/eclipse/jetty/io/ManagedSelector.java b/jetty-io/src/main/java/org/eclipse/jetty/io/ManagedSelector.java index 88a604f1130..e23ca67b078 100644 --- a/jetty-io/src/main/java/org/eclipse/jetty/io/ManagedSelector.java +++ b/jetty-io/src/main/java/org/eclipse/jetty/io/ManagedSelector.java @@ -62,6 +62,7 @@ public class ManagedSelector extends ContainerLifeCycle implements Dumpable { private static final Logger LOG = Log.getLogger(ManagedSelector.class); private static final boolean FORCE_SELECT_NOW; + static { String property = System.getProperty("org.eclipse.jetty.io.forceSelectNow"); @@ -91,8 +92,8 @@ public class ManagedSelector extends ContainerLifeCycle implements Dumpable _id = id; SelectorProducer producer = new SelectorProducer(); Executor executor = selectorManager.getExecutor(); - _strategy = new EatWhatYouKill(producer,executor); - addBean(_strategy,true); + _strategy = new EatWhatYouKill(producer, executor); + addBean(_strategy, true); setStopTimeout(5000); } @@ -131,20 +132,20 @@ public class ManagedSelector extends ContainerLifeCycle implements Dumpable @Override protected void doStop() throws Exception - { + { // doStop might be called for a failed managedSelector, // We do not want to wait twice, so we only stop once for each start - if (_started.compareAndSet(true,false)) + if (_started.compareAndSet(true, false)) { // Close connections, but only wait a single selector cycle for it to take effect - CloseConnections close_connections = new CloseConnections(); - submit(close_connections); - close_connections._complete.await(); + CloseConnections closeConnections = new CloseConnections(); + submit(closeConnections); + closeConnections._complete.await(); // Wait for any remaining endpoints to be closed and the selector to be stopped - StopSelector stop_selector = new StopSelector(); - submit(stop_selector); - stop_selector._stopped.await(); + StopSelector stopSelector = new StopSelector(); + submit(stopSelector); + stopSelector._stopped.await(); } super.doStop(); @@ -152,6 +153,7 @@ public class ManagedSelector extends ContainerLifeCycle implements Dumpable /** * Submit an {@link SelectorUpdate} to be acted on between calls to {@link Selector#select()} + * * @param update The selector update to apply at next wakeup */ public void submit(SelectorUpdate update) @@ -160,10 +162,10 @@ public class ManagedSelector extends ContainerLifeCycle implements Dumpable LOG.debug("Queued change {} on {}", update, this); Selector selector = null; - synchronized(ManagedSelector.this) + synchronized (ManagedSelector.this) { _updates.offer(update); - + if (_selecting) { selector = _selector; @@ -171,7 +173,7 @@ public class ManagedSelector extends ContainerLifeCycle implements Dumpable _selecting = false; } } - + if (selector != null) { if (LOG.isDebugEnabled()) @@ -226,7 +228,7 @@ public class ManagedSelector extends ContainerLifeCycle implements Dumpable if (connect.timeout.cancel()) { key.interestOps(0); - execute(new CreateEndPoint(connect,key)); + execute(new CreateEndPoint(connect, key)); } else { @@ -281,7 +283,7 @@ public class ManagedSelector extends ContainerLifeCycle implements Dumpable private int getActionSize() { - synchronized(ManagedSelector.this) + synchronized (ManagedSelector.this) { return _updates.size(); } @@ -323,7 +325,7 @@ public class ManagedSelector extends ContainerLifeCycle implements Dumpable { DumpKeys dump = new DumpKeys(); String updatesAt = DateTimeFormatter.ISO_OFFSET_DATE_TIME.format(ZonedDateTime.now()); - synchronized(ManagedSelector.this) + synchronized (ManagedSelector.this) { updates = new ArrayList<>(_updates); _updates.addFirst(dump); @@ -334,12 +336,12 @@ public class ManagedSelector extends ContainerLifeCycle implements Dumpable selector.wakeup(); keys = dump.get(5, TimeUnit.SECONDS); String keysAt = DateTimeFormatter.ISO_OFFSET_DATE_TIME.format(ZonedDateTime.now()); - if (keys==null) + if (keys == null) keys = Collections.singletonList("No dump keys retrieved"); dumpObjects(out, indent, - new DumpableCollection("updates @ "+updatesAt, updates), - new DumpableCollection("keys @ "+keysAt, keys)); + new DumpableCollection("updates @ " + updatesAt, updates), + new DumpableCollection("keys @ " + keysAt, keys)); } else { @@ -352,11 +354,11 @@ public class ManagedSelector extends ContainerLifeCycle implements Dumpable { Selector selector = _selector; return String.format("%s id=%s keys=%d selected=%d updates=%d", - super.toString(), - _id, - selector != null && selector.isOpen() ? selector.keys().size() : -1, - selector != null && selector.isOpen() ? selector.selectedKeys().size() : -1, - getActionSize()); + super.toString(), + _id, + selector != null && selector.isOpen() ? selector.keys().size() : -1, + selector != null && selector.isOpen() ? selector.selectedKeys().size() : -1, + getActionSize()); } /** @@ -405,27 +407,27 @@ public class ManagedSelector extends ContainerLifeCycle implements Dumpable private void processUpdates() { - synchronized(ManagedSelector.this) + synchronized (ManagedSelector.this) { Deque updates = _updates; _updates = _updateable; _updateable = updates; } - + if (LOG.isDebugEnabled()) - LOG.debug("updateable {}",_updateable.size()); - + LOG.debug("updateable {}", _updateable.size()); + for (SelectorUpdate update : _updateable) { - if (_selector==null) + if (_selector == null) break; try { if (LOG.isDebugEnabled()) - LOG.debug("update {}",update); + LOG.debug("update {}", update); update.update(_selector); } - catch(Throwable th) + catch (Throwable th) { LOG.warn(th); } @@ -434,16 +436,16 @@ public class ManagedSelector extends ContainerLifeCycle implements Dumpable Selector selector; int updates; - synchronized(ManagedSelector.this) + synchronized (ManagedSelector.this) { updates = _updates.size(); - _selecting = updates==0; - selector = _selecting?null:_selector; + _selecting = updates == 0; + selector = _selecting ? null : _selector; } if (LOG.isDebugEnabled()) - LOG.debug("updates {}",updates); - + LOG.debug("updates {}", updates); + if (selector != null) { if (LOG.isDebugEnabled()) @@ -477,7 +479,7 @@ public class ManagedSelector extends ContainerLifeCycle implements Dumpable LOG.debug("Selector {} woken up from select, {}/{}/{} selected", selector, selected, selector.selectedKeys().size(), selector.keys().size()); int updates; - synchronized(ManagedSelector.this) + synchronized (ManagedSelector.this) { // finished selecting _selecting = false; @@ -580,7 +582,7 @@ public class ManagedSelector extends ContainerLifeCycle implements Dumpable return String.format("%s@%x", getClass().getSimpleName(), hashCode()); } } - + /** * A selector update to be done when the selector has been woken. */ @@ -605,13 +607,13 @@ public class ManagedSelector extends ContainerLifeCycle implements Dumpable { private CountDownLatch latch = new CountDownLatch(1); private List keys; - + @Override public void update(Selector selector) { - Set selector_keys = selector.keys(); - List list = new ArrayList<>(selector_keys.size()); - for (SelectionKey key : selector_keys) + Set selectorKeys = selector.keys(); + List list = new ArrayList<>(selectorKeys.size()); + for (SelectionKey key : selectorKeys) { if (key != null) list.add(String.format("SelectionKey@%x{i=%d}->%s", key.hashCode(), safeInterestOps(key), key.attachment())); @@ -649,10 +651,10 @@ public class ManagedSelector extends ContainerLifeCycle implements Dumpable { try { - if (_key==null) + if (_key == null) { _key = _channel.register(selector, SelectionKey.OP_ACCEPT, this); - } + } if (LOG.isDebugEnabled()) LOG.debug("{} acceptor={}", this, _key); @@ -671,10 +673,10 @@ public class ManagedSelector extends ContainerLifeCycle implements Dumpable SelectableChannel channel = null; try { - while(true) + while (true) { channel = _selectorManager.doAccept(server); - if (channel==null) + if (channel == null) break; _selectorManager.accepted(channel); } @@ -684,7 +686,7 @@ public class ManagedSelector extends ContainerLifeCycle implements Dumpable closeNoExceptions(channel); LOG.warn("Accept failed for channel " + channel, x); } - + return null; } @@ -698,7 +700,7 @@ public class ManagedSelector extends ContainerLifeCycle implements Dumpable { SelectionKey key = _key; _key = null; - if (key!=null && key.isValid()) + if (key != null && key.isValid()) key.cancel(); } } @@ -734,7 +736,7 @@ public class ManagedSelector extends ContainerLifeCycle implements Dumpable catch (Throwable x) { closeNoExceptions(channel); - _selectorManager.onAcceptFailed(channel,x); + _selectorManager.onAcceptFailed(channel, x); LOG.debug(x); } } @@ -759,11 +761,10 @@ public class ManagedSelector extends ContainerLifeCycle implements Dumpable closeNoExceptions(channel); LOG.warn(String.valueOf(failure)); LOG.debug(failure); - _selectorManager.onAcceptFailed(channel,failure); + _selectorManager.onAcceptFailed(channel, failure); } } - class Connect implements SelectorUpdate, Runnable { private final AtomicBoolean failed = new AtomicBoolean(); @@ -790,7 +791,7 @@ public class ManagedSelector extends ContainerLifeCycle implements Dumpable failed(x); } } - + @Override public void run() { @@ -811,11 +812,11 @@ public class ManagedSelector extends ContainerLifeCycle implements Dumpable ManagedSelector.this._selectorManager.connectionFailed(channel, failure, attachment); } } - + @Override public String toString() { - return String.format("Connect@%x{%s,%s}",hashCode(),channel,attachment); + return String.format("Connect@%x{%s,%s}", hashCode(), channel, attachment); } } @@ -829,7 +830,7 @@ public class ManagedSelector extends ContainerLifeCycle implements Dumpable { this(null); } - + public CloseConnections(Set closed) { _closed = closed; @@ -837,13 +838,13 @@ public class ManagedSelector extends ContainerLifeCycle implements Dumpable @Override public void update(Selector selector) - { + { if (LOG.isDebugEnabled()) LOG.debug("Closing {} connections on {}", selector.keys().size(), ManagedSelector.this); boolean zero = true; for (SelectionKey key : selector.keys()) { - if (key!=null && key.isValid()) + if (key != null && key.isValid()) { Closeable closeable = null; Object attachment = key.attachment(); @@ -858,45 +859,45 @@ public class ManagedSelector extends ContainerLifeCycle implements Dumpable else closeable = endp; } - - if (closeable!=null) + + if (closeable != null) { - if (_closed==null) + if (_closed == null) { closeNoExceptions(closeable); } else if (!_closed.contains(closeable)) - { + { _closed.add(closeable); closeNoExceptions(closeable); } } } } - + if (zero) _noEndPoints.countDown(); _complete.countDown(); } } - + private class StopSelector implements SelectorUpdate { CountDownLatch _stopped = new CountDownLatch(1); - + @Override public void update(Selector selector) { for (SelectionKey key : selector.keys()) { - if (key!=null && key.isValid()) + if (key != null && key.isValid()) { Object attachment = key.attachment(); if (attachment instanceof EndPoint) closeNoExceptions((EndPoint)attachment); } } - + _selector = null; closeNoExceptions(selector); _stopped.countDown(); @@ -919,9 +920,9 @@ public class ManagedSelector extends ContainerLifeCycle implements Dumpable { try { - createEndPoint(_connect.channel,_key); + createEndPoint(_connect.channel, _key); } - catch(Throwable failure) + catch (Throwable failure) { closeNoExceptions(_connect.channel); LOG.warn(String.valueOf(failure)); @@ -929,14 +930,14 @@ public class ManagedSelector extends ContainerLifeCycle implements Dumpable _connect.failed(failure); } } - + @Override public String toString() { - return String.format("CreateEndPoint@%x{%s,%s}",hashCode(),_connect,_key); + return String.format("CreateEndPoint@%x{%s,%s}", hashCode(), _connect, _key); } } - + private class DestroyEndPoint implements Runnable, Closeable { private final EndPoint endPoint; diff --git a/jetty-io/src/main/java/org/eclipse/jetty/io/MappedByteBufferPool.java b/jetty-io/src/main/java/org/eclipse/jetty/io/MappedByteBufferPool.java index ca5e7e3d57f..603378c95f6 100644 --- a/jetty-io/src/main/java/org/eclipse/jetty/io/MappedByteBufferPool.java +++ b/jetty-io/src/main/java/org/eclipse/jetty/io/MappedByteBufferPool.java @@ -197,8 +197,8 @@ public class MappedByteBufferPool extends AbstractByteBufferPool private long getByteBufferCount(boolean direct) { return bucketsFor(direct).values().stream() - .mapToLong(Bucket::size) - .sum(); + .mapToLong(Bucket::size) + .sum(); } // Package local for testing diff --git a/jetty-io/src/main/java/org/eclipse/jetty/io/NegotiatingClientConnection.java b/jetty-io/src/main/java/org/eclipse/jetty/io/NegotiatingClientConnection.java index b7574f1363b..c9853ea6fd3 100644 --- a/jetty-io/src/main/java/org/eclipse/jetty/io/NegotiatingClientConnection.java +++ b/jetty-io/src/main/java/org/eclipse/jetty/io/NegotiatingClientConnection.java @@ -21,7 +21,6 @@ package org.eclipse.jetty.io; import java.io.IOException; import java.util.Map; import java.util.concurrent.Executor; - import javax.net.ssl.SSLEngine; import org.eclipse.jetty.util.BufferUtil; diff --git a/jetty-io/src/main/java/org/eclipse/jetty/io/NegotiatingClientConnectionFactory.java b/jetty-io/src/main/java/org/eclipse/jetty/io/NegotiatingClientConnectionFactory.java index 8bf4a52e262..54b66f791a7 100644 --- a/jetty-io/src/main/java/org/eclipse/jetty/io/NegotiatingClientConnectionFactory.java +++ b/jetty-io/src/main/java/org/eclipse/jetty/io/NegotiatingClientConnectionFactory.java @@ -18,7 +18,6 @@ package org.eclipse.jetty.io; - public abstract class NegotiatingClientConnectionFactory implements ClientConnectionFactory { private final ClientConnectionFactory connectionFactory; diff --git a/jetty-io/src/main/java/org/eclipse/jetty/io/NetworkTrafficListener.java b/jetty-io/src/main/java/org/eclipse/jetty/io/NetworkTrafficListener.java index 1c0b0f7c2e9..b2717d0403b 100644 --- a/jetty-io/src/main/java/org/eclipse/jetty/io/NetworkTrafficListener.java +++ b/jetty-io/src/main/java/org/eclipse/jetty/io/NetworkTrafficListener.java @@ -51,7 +51,7 @@ public interface NetworkTrafficListener *

    Callback method invoked when bytes sent by a remote client arrived on the server.

    * * @param socket the socket associated with the remote client - * @param bytes the read-only buffer containing the incoming bytes + * @param bytes the read-only buffer containing the incoming bytes */ public void incoming(Socket socket, ByteBuffer bytes); @@ -60,7 +60,7 @@ public interface NetworkTrafficListener *

    This method is invoked after the bytes have been actually written to the remote client.

    * * @param socket the socket associated with the remote client - * @param bytes the read-only buffer containing the outgoing bytes + * @param bytes the read-only buffer containing the outgoing bytes */ public void outgoing(Socket socket, ByteBuffer bytes); diff --git a/jetty-io/src/main/java/org/eclipse/jetty/io/NetworkTrafficSelectChannelEndPoint.java b/jetty-io/src/main/java/org/eclipse/jetty/io/NetworkTrafficSelectChannelEndPoint.java index 5fbaca308d3..5ecf5d57d73 100644 --- a/jetty-io/src/main/java/org/eclipse/jetty/io/NetworkTrafficSelectChannelEndPoint.java +++ b/jetty-io/src/main/java/org/eclipse/jetty/io/NetworkTrafficSelectChannelEndPoint.java @@ -53,16 +53,16 @@ public class NetworkTrafficSelectChannelEndPoint extends SocketChannelEndPoint @Override public boolean flush(ByteBuffer... buffers) throws IOException { - boolean flushed=true; + boolean flushed = true; for (ByteBuffer b : buffers) { if (b.hasRemaining()) { int position = b.position(); - ByteBuffer view=b.slice(); - flushed&=super.flush(b); - int l=b.position()-position; - view.limit(view.position()+l); + ByteBuffer view = b.slice(); + flushed &= super.flush(b); + int l = b.position() - position; + view.limit(view.position() + l); notifyOutgoing(view); if (!flushed) break; @@ -71,8 +71,6 @@ public class NetworkTrafficSelectChannelEndPoint extends SocketChannelEndPoint return flushed; } - - @Override public void onOpen() { @@ -113,7 +111,6 @@ public class NetworkTrafficSelectChannelEndPoint extends SocketChannelEndPoint } } - public void notifyIncoming(ByteBuffer buffer, int read) { if (listeners != null && !listeners.isEmpty() && read > 0) @@ -137,12 +134,12 @@ public class NetworkTrafficSelectChannelEndPoint extends SocketChannelEndPoint { if (listeners != null && !listeners.isEmpty() && view.hasRemaining()) { - Socket socket=getSocket(); + Socket socket = getSocket(); for (NetworkTrafficListener listener : listeners) { try { - listener.outgoing(socket, view); + listener.outgoing(socket, view); } catch (Exception x) { @@ -151,5 +148,4 @@ public class NetworkTrafficSelectChannelEndPoint extends SocketChannelEndPoint } } } - } diff --git a/jetty-io/src/main/java/org/eclipse/jetty/io/QuietException.java b/jetty-io/src/main/java/org/eclipse/jetty/io/QuietException.java index 197c64e588f..4e913d8cfb5 100644 --- a/jetty-io/src/main/java/org/eclipse/jetty/io/QuietException.java +++ b/jetty-io/src/main/java/org/eclipse/jetty/io/QuietException.java @@ -18,9 +18,8 @@ package org.eclipse.jetty.io; - -/* ------------------------------------------------------------ */ -/** A Quiet Exception. +/** + * A Quiet Exception. *

    Exception classes that extend this interface will be logged * less verbosely. */ diff --git a/jetty-io/src/main/java/org/eclipse/jetty/io/RuntimeIOException.java b/jetty-io/src/main/java/org/eclipse/jetty/io/RuntimeIOException.java index dfda06b8cfa..a552ec8c7ec 100644 --- a/jetty-io/src/main/java/org/eclipse/jetty/io/RuntimeIOException.java +++ b/jetty-io/src/main/java/org/eclipse/jetty/io/RuntimeIOException.java @@ -16,10 +16,8 @@ // ======================================================================== // - package org.eclipse.jetty.io; -/* ------------------------------------------------------------ */ /** * Subclass of {@link java.lang.RuntimeException} used to signal that there * was an {@link java.io.IOException} thrown by underlying {@link java.io.Writer} @@ -43,6 +41,6 @@ public class RuntimeIOException extends RuntimeException public RuntimeIOException(String message, Throwable cause) { - super(message,cause); + super(message, cause); } } diff --git a/jetty-io/src/main/java/org/eclipse/jetty/io/SelectorManager.java b/jetty-io/src/main/java/org/eclipse/jetty/io/SelectorManager.java index 313aad7211c..29abac57e68 100644 --- a/jetty-io/src/main/java/org/eclipse/jetty/io/SelectorManager.java +++ b/jetty-io/src/main/java/org/eclipse/jetty/io/SelectorManager.java @@ -74,9 +74,9 @@ public abstract class SelectorManager extends ContainerLifeCycle implements Dump { int threads = ((ThreadPool.SizedThreadPool)executor).getMaxThreads(); int cpus = ProcessorUtils.availableProcessors(); - return Math.max(1,Math.min(cpus/2,threads/16)); + return Math.max(1, Math.min(cpus / 2, threads / 16)); } - return Math.max(1,ProcessorUtils.availableProcessors()/2); + return Math.max(1, ProcessorUtils.availableProcessors() / 2); } protected SelectorManager(Executor executor, Scheduler scheduler) @@ -97,7 +97,7 @@ public abstract class SelectorManager extends ContainerLifeCycle implements Dump this.executor = executor; this.scheduler = scheduler; _selectors = new ManagedSelector[selectors]; - _selectorIndexUpdate = index -> (index+1)%_selectors.length; + _selectorIndexUpdate = index -> (index + 1) % _selectors.length; } @ManagedAttribute("The Executor") @@ -163,7 +163,7 @@ public abstract class SelectorManager extends ContainerLifeCycle implements Dump * must be called prior to calling this method, and the connect operation must not be completed * (the return value of {@link SocketChannel#connect(SocketAddress)} must be false).

    * - * @param channel the channel to register + * @param channel the channel to register * @param attachment the attachment object * @see #accept(SelectableChannel, Object) */ @@ -189,7 +189,7 @@ public abstract class SelectorManager extends ContainerLifeCycle implements Dump * just after a non-blocking connect via {@link SocketChannel#connect(SocketAddress)} that completed * successfully.

    * - * @param channel the channel to register + * @param channel the channel to register * @param attachment the attachment object */ public void accept(SelectableChannel channel, Object attachment) @@ -265,10 +265,10 @@ public abstract class SelectorManager extends ContainerLifeCycle implements Dump // Cleanup for (ManagedSelector selector : _selectors) { - if (selector!=null) + if (selector != null) removeBean(selector); } - Arrays.fill(_selectors,null); + Arrays.fill(_selectors, null); if (_lease != null) _lease.close(); } @@ -346,13 +346,12 @@ public abstract class SelectorManager extends ContainerLifeCycle implements Dump return ((ServerSocketChannel)server).accept(); } - /** *

    Callback method invoked when a non-blocking connect cannot be completed.

    *

    By default it just logs with level warning.

    * - * @param channel the channel that attempted the connect - * @param ex the exception that caused the connect to fail + * @param channel the channel that attempted the connect + * @param ex the exception that caused the connect to fail * @param attachment the attachment object associated at registration */ protected void connectionFailed(SelectableChannel channel, Throwable ex, Object attachment) @@ -370,8 +369,8 @@ public abstract class SelectorManager extends ContainerLifeCycle implements Dump *

    This method is invoked as a result of the registration of a channel via {@link #connect(SelectableChannel, Object)} * or {@link #accept(SelectableChannel)}.

    * - * @param channel the channel associated to the endpoint - * @param selector the selector the channel is registered to + * @param channel the channel associated to the endpoint + * @param selector the selector the channel is registered to * @param selectionKey the selection key * @return a new endpoint * @throws IOException if the endPoint cannot be created @@ -382,8 +381,8 @@ public abstract class SelectorManager extends ContainerLifeCycle implements Dump /** *

    Factory method to create {@link Connection}.

    * - * @param channel the channel associated to the connection - * @param endpoint the endpoint + * @param channel the channel associated to the connection + * @param endpoint the endpoint * @param attachment the attachment * @return a new connection * @throws IOException if unable to create new connection @@ -396,8 +395,8 @@ public abstract class SelectorManager extends ContainerLifeCycle implements Dump throw new IllegalStateException(this.toString()); if (listener instanceof AcceptListener) addAcceptListener(AcceptListener.class.cast(listener)); - } - + } + public void removeEventListener(EventListener listener) { if (isRunning()) @@ -414,9 +413,9 @@ public abstract class SelectorManager extends ContainerLifeCycle implements Dump public void removeAcceptListener(AcceptListener listener) { - _acceptListeners.remove(listener); + _acceptListeners.remove(listener); } - + protected void onAccepting(SelectableChannel channel) { for (AcceptListener l : _acceptListeners) @@ -431,14 +430,14 @@ public abstract class SelectorManager extends ContainerLifeCycle implements Dump } } } - + protected void onAcceptFailed(SelectableChannel channel, Throwable cause) { for (AcceptListener l : _acceptListeners) { try { - l.onAcceptFailed(channel,cause); + l.onAcceptFailed(channel, cause); } catch (Throwable x) { @@ -446,7 +445,7 @@ public abstract class SelectorManager extends ContainerLifeCycle implements Dump } } } - + protected void onAccepted(SelectableChannel channel) { for (AcceptListener l : _acceptListeners) @@ -472,24 +471,33 @@ public abstract class SelectorManager extends ContainerLifeCycle implements Dump /** * Called immediately after a new SelectableChannel is accepted, but * before it has been submitted to the {@link SelectorManager}. + * * @param channel the accepted channel */ - default void onAccepting(SelectableChannel channel) {} - + default void onAccepting(SelectableChannel channel) + { + } + /** * Called if the processing of the accepted channel fails prior to calling * {@link #onAccepted(SelectableChannel)}. + * * @param channel the accepted channel * @param cause the cause of the failure */ - default void onAcceptFailed(SelectableChannel channel, Throwable cause) {} - + default void onAcceptFailed(SelectableChannel channel, Throwable cause) + { + } + /** - * Called after the accepted channel has been allocated an {@link EndPoint} + * Called after the accepted channel has been allocated an {@link EndPoint} * and associated {@link Connection}, and after the onOpen notifications have * been called on both endPoint and connection. + * * @param channel the accepted channel */ - default void onAccepted(SelectableChannel channel) {} + default void onAccepted(SelectableChannel channel) + { + } } } diff --git a/jetty-io/src/main/java/org/eclipse/jetty/io/SocketChannelEndPoint.java b/jetty-io/src/main/java/org/eclipse/jetty/io/SocketChannelEndPoint.java index 71a77f3885a..249e8419d47 100644 --- a/jetty-io/src/main/java/org/eclipse/jetty/io/SocketChannelEndPoint.java +++ b/jetty-io/src/main/java/org/eclipse/jetty/io/SocketChannelEndPoint.java @@ -38,16 +38,16 @@ public class SocketChannelEndPoint extends ChannelEndPoint public SocketChannelEndPoint(SelectableChannel channel, ManagedSelector selector, SelectionKey key, Scheduler scheduler) { - this((SocketChannel)channel,selector,key,scheduler); + this((SocketChannel)channel, selector, key, scheduler); } - + public SocketChannelEndPoint(SocketChannel channel, ManagedSelector selector, SelectionKey key, Scheduler scheduler) { - super(channel,selector,key,scheduler); - - _socket=channel.socket(); - _local=(InetSocketAddress)_socket.getLocalSocketAddress(); - _remote=(InetSocketAddress)_socket.getRemoteSocketAddress(); + super(channel, selector, key, scheduler); + + _socket = channel.socket(); + _local = (InetSocketAddress)_socket.getLocalSocketAddress(); + _remote = (InetSocketAddress)_socket.getRemoteSocketAddress(); } public Socket getSocket() @@ -66,7 +66,7 @@ public class SocketChannelEndPoint extends ChannelEndPoint { return _remote; } - + @Override protected void doShutdownOutput() { diff --git a/jetty-io/src/main/java/org/eclipse/jetty/io/WriteFlusher.java b/jetty-io/src/main/java/org/eclipse/jetty/io/WriteFlusher.java index 574d7ae7525..931052bc618 100644 --- a/jetty-io/src/main/java/org/eclipse/jetty/io/WriteFlusher.java +++ b/jetty-io/src/main/java/org/eclipse/jetty/io/WriteFlusher.java @@ -43,7 +43,7 @@ import org.eclipse.jetty.util.thread.Invocable.InvocationType; * flush and should organize for the {@link #completeWrite()} method to be called when a subsequent call to flush * should be able to make more progress. */ -abstract public class WriteFlusher +public abstract class WriteFlusher { private static final Logger LOG = Log.getLogger(WriteFlusher.class); private static final boolean DEBUG = LOG.isDebugEnabled(); // Easy for the compiler to remove the code if DEBUG==false @@ -98,7 +98,7 @@ abstract public class WriteFlusher * Tries to update the current state to the given new state. * * @param previous the expected current state - * @param next the desired new state + * @param next the desired new state * @return the previous state or null if the state transition failed * @throws IllegalStateException if previous to next is not a legal state transition (api usage error) */ @@ -233,15 +233,15 @@ abstract public class WriteFlusher { State s = _state.get(); return (s instanceof PendingState) - ? ((PendingState)s).getCallbackInvocationType() - : Invocable.InvocationType.BLOCKING; + ? ((PendingState)s).getCallbackInvocationType() + : Invocable.InvocationType.BLOCKING; } /** * Abstract call to be implemented by specific WriteFlushers. It should schedule a call to {@link #completeWrite()} * or {@link #onFail(Throwable)} when appropriate. */ - abstract protected void onIncompleteFlush(); + protected abstract void onIncompleteFlush(); /** * Tries to switch state to WRITING. If successful it writes the given buffers to the EndPoint. If state transition @@ -253,14 +253,14 @@ abstract public class WriteFlusher * If all buffers have been written it calls callback.complete(). * * @param callback the callback to call on either failed or complete - * @param buffers the buffers to flush to the endpoint + * @param buffers the buffers to flush to the endpoint * @throws WritePendingException if unable to write due to prior pending write */ public void write(Callback callback, ByteBuffer... buffers) throws WritePendingException { callback = Objects.requireNonNull(callback); - if(isFailed()) + if (isFailed()) { fail(callback); return; @@ -324,7 +324,9 @@ abstract public class WriteFlusher case IDLE: for (Throwable t : suppressed) + { LOG.warn(t); + } return; default: diff --git a/jetty-io/src/main/java/org/eclipse/jetty/io/WriterOutputStream.java b/jetty-io/src/main/java/org/eclipse/jetty/io/WriterOutputStream.java index a8272ecf157..126448c1cfc 100644 --- a/jetty-io/src/main/java/org/eclipse/jetty/io/WriterOutputStream.java +++ b/jetty-io/src/main/java/org/eclipse/jetty/io/WriterOutputStream.java @@ -23,78 +23,69 @@ import java.io.OutputStream; import java.io.Writer; import java.nio.charset.Charset; - -/* ------------------------------------------------------------ */ -/** Wrap a Writer as an OutputStream. +/** + * Wrap a Writer as an OutputStream. * When all you have is a Writer and only an OutputStream will do. * Try not to use this as it indicates that your design is a dogs * breakfast (JSP made me write it). - * */ public class WriterOutputStream extends OutputStream { protected final Writer _writer; protected final Charset _encoding; - private final byte[] _buf=new byte[1]; - - /* ------------------------------------------------------------ */ + private final byte[] _buf = new byte[1]; + public WriterOutputStream(Writer writer, String encoding) { - _writer=writer; - _encoding=encoding==null?null:Charset.forName(encoding); - } - - /* ------------------------------------------------------------ */ - public WriterOutputStream(Writer writer) - { - _writer=writer; - _encoding=null; + _writer = writer; + _encoding = encoding == null ? null : Charset.forName(encoding); + } + + public WriterOutputStream(Writer writer) + { + _writer = writer; + _encoding = null; } - /* ------------------------------------------------------------ */ @Override public void close() throws IOException { _writer.close(); } - - /* ------------------------------------------------------------ */ + @Override public void flush() throws IOException { _writer.flush(); } - - /* ------------------------------------------------------------ */ + @Override - public void write(byte[] b) + public void write(byte[] b) throws IOException { - if (_encoding==null) + if (_encoding == null) _writer.write(new String(b)); else - _writer.write(new String(b,_encoding)); + _writer.write(new String(b, _encoding)); } - - /* ------------------------------------------------------------ */ + @Override public void write(byte[] b, int off, int len) throws IOException { - if (_encoding==null) - _writer.write(new String(b,off,len)); + if (_encoding == null) + _writer.write(new String(b, off, len)); else - _writer.write(new String(b,off,len,_encoding)); + _writer.write(new String(b, off, len, _encoding)); } - - /* ------------------------------------------------------------ */ + @Override public synchronized void write(int b) throws IOException { - _buf[0]=(byte)b; + _buf[0] = (byte)b; write(_buf); } } diff --git a/jetty-io/src/main/java/org/eclipse/jetty/io/ssl/SslClientConnectionFactory.java b/jetty-io/src/main/java/org/eclipse/jetty/io/ssl/SslClientConnectionFactory.java index d75e29fbd4e..45b0be514fd 100644 --- a/jetty-io/src/main/java/org/eclipse/jetty/io/ssl/SslClientConnectionFactory.java +++ b/jetty-io/src/main/java/org/eclipse/jetty/io/ssl/SslClientConnectionFactory.java @@ -23,7 +23,6 @@ import java.net.InetSocketAddress; import java.util.Map; import java.util.Objects; import java.util.concurrent.Executor; - import javax.net.ssl.HostnameVerifier; import javax.net.ssl.SSLEngine; import javax.net.ssl.SSLException; diff --git a/jetty-io/src/main/java/org/eclipse/jetty/io/ssl/SslConnection.java b/jetty-io/src/main/java/org/eclipse/jetty/io/ssl/SslConnection.java index 9c0ecb2f18c..35f603caa35 100644 --- a/jetty-io/src/main/java/org/eclipse/jetty/io/ssl/SslConnection.java +++ b/jetty-io/src/main/java/org/eclipse/jetty/io/ssl/SslConnection.java @@ -74,7 +74,6 @@ import org.eclipse.jetty.util.thread.Invocable; * MOST IMPORTANTLY, the encrypted callbacks from the active methods (#onFillable() and WriteFlusher#completeWrite()) do no filling or flushing * themselves. Instead they simple make the callbacks to the decrypted callbacks, so that the passive encrypted fill/flush will * be called again and make another best effort attempt to progress the connection. - * */ public class SslConnection extends AbstractConnection implements Connection.UpgradeTo { @@ -242,8 +241,8 @@ public class SslConnection extends AbstractConnection implements Connection.Upgr /** * @param renegotiationLimit The number of renegotions allowed for this connection. - * When the limit is 0 renegotiation will be denied. If the limit is less than 0 then no limit is applied. - * Default -1. + * When the limit is 0 renegotiation will be denied. If the limit is less than 0 then no limit is applied. + * Default -1. */ public void setRenegotiationLimit(int renegotiationLimit) { @@ -342,13 +341,13 @@ public class SslConnection extends AbstractConnection implements Connection.Upgr Connection connection = _decryptedEndPoint.getConnection(); return String.format("%s@%x{%s,eio=%d/%d,di=%d,fill=%s,flush=%s}~>%s=>%s", - getClass().getSimpleName(), - hashCode(), - _sslEngine.getHandshakeStatus(), - ei, eo, di, - _fillState, _flushState, - _decryptedEndPoint.toEndPointString(), - connection instanceof AbstractConnection ? ((AbstractConnection)connection).toConnectionString() : connection); + getClass().getSimpleName(), + hashCode(), + _sslEngine.getHandshakeStatus(), + ei, eo, di, + _fillState, _flushState, + _decryptedEndPoint.toEndPointString(), + connection instanceof AbstractConnection ? ((AbstractConnection)connection).toConnectionString() : connection); } private void releaseEncryptedOutputBuffer() @@ -414,25 +413,25 @@ public class SslConnection extends AbstractConnection implements Connection.Upgr try { // If we are handshaking, then wake up any waiting write as well as it may have been blocked on the read - boolean waiting_for_fill; + boolean waitingForFill; synchronized (_decryptedEndPoint) { if (LOG.isDebugEnabled()) LOG.debug("onFillable {}", SslConnection.this); _fillState = FillState.IDLE; - waiting_for_fill = _flushState == FlushState.WAIT_FOR_FILL; + waitingForFill = _flushState == FlushState.WAIT_FOR_FILL; } getFillInterest().fillable(); - if (waiting_for_fill) + if (waitingForFill) { synchronized (_decryptedEndPoint) { - waiting_for_fill = _flushState == FlushState.WAIT_FOR_FILL; + waitingForFill = _flushState == FlushState.WAIT_FOR_FILL; } - if (waiting_for_fill) + if (waitingForFill) fill(BufferUtil.EMPTY_BUFFER); } } @@ -545,49 +544,49 @@ public class SslConnection extends AbstractConnection implements Connection.Upgr acquireEncryptedInput(); // can we use the passed buffer if it is big enough - ByteBuffer app_in; + ByteBuffer appIn; if (_decryptedInput == null) { if (BufferUtil.space(buffer) > _sslEngine.getSession().getApplicationBufferSize()) - app_in = buffer; + appIn = buffer; else - app_in = _decryptedInput = _bufferPool.acquire(_sslEngine.getSession().getApplicationBufferSize(), _decryptedDirectBuffers); + appIn = _decryptedInput = _bufferPool.acquire(_sslEngine.getSession().getApplicationBufferSize(), _decryptedDirectBuffers); } else { - app_in = _decryptedInput; + appIn = _decryptedInput; BufferUtil.compact(_encryptedInput); } // Let's try reading some encrypted data... even if we have some already. - int net_filled = getEndPoint().fill(_encryptedInput); + int netFilled = getEndPoint().fill(_encryptedInput); if (LOG.isDebugEnabled()) - LOG.debug("net filled={}", net_filled); + LOG.debug("net filled={}", netFilled); - if (net_filled > 0 && _handshake.get() == Handshake.INITIAL && isOutboundDone()) + if (netFilled > 0 && _handshake.get() == Handshake.INITIAL && isOutboundDone()) throw new SSLHandshakeException("Closed during handshake"); // Let's unwrap even if we have no net data because in that // case we want to fall through to the handshake handling - int pos = BufferUtil.flipToFill(app_in); + int pos = BufferUtil.flipToFill(appIn); SSLEngineResult unwrapResult; try { _underflown = false; - unwrapResult = _sslEngine.unwrap(_encryptedInput, app_in); + unwrapResult = _sslEngine.unwrap(_encryptedInput, appIn); } finally { - BufferUtil.flipToFlush(app_in, pos); + BufferUtil.flipToFlush(appIn, pos); } if (LOG.isDebugEnabled()) LOG.debug("unwrap net_filled={} {} encryptedBuffer={} unwrapBuffer={} appBuffer={}", - net_filled, - StringUtil.replace(unwrapResult.toString(), '\n', ' '), - BufferUtil.toSummaryString(_encryptedInput), - BufferUtil.toDetailString(app_in), - BufferUtil.toDetailString(buffer)); + netFilled, + StringUtil.replace(unwrapResult.toString(), '\n', ' '), + BufferUtil.toSummaryString(_encryptedInput), + BufferUtil.toDetailString(appIn), + BufferUtil.toDetailString(buffer)); SSLEngineResult.Status unwrap = unwrapResult.getStatus(); @@ -602,15 +601,15 @@ public class SslConnection extends AbstractConnection implements Connection.Upgr return filled = -1; case BUFFER_UNDERFLOW: - if (net_filled > 0) + if (netFilled > 0) continue; // try filling some more _underflown = true; - if (net_filled < 0 && _sslEngine.getUseClientMode()) + if (netFilled < 0 && _sslEngine.getUseClientMode()) { closeInbound(); return filled = -1; } - return filled = net_filled; + return filled = netFilled; case OK: { @@ -625,7 +624,7 @@ public class SslConnection extends AbstractConnection implements Connection.Upgr // another call to fill() or flush(). if (unwrapResult.bytesProduced() > 0) { - if (app_in == buffer) + if (appIn == buffer) return filled = unwrapResult.bytesProduced(); return filled = BufferUtil.append(buffer, _decryptedInput); } @@ -765,8 +764,8 @@ public class SslConnection extends AbstractConnection implements Connection.Upgr { if (LOG.isDebugEnabled()) LOG.debug("handshake succeeded {} {} {}/{}", SslConnection.this, - _sslEngine.getUseClientMode() ? "client" : "resumed server", - _sslEngine.getSession().getProtocol(), _sslEngine.getSession().getCipherSuite()); + _sslEngine.getUseClientMode() ? "client" : "resumed server", + _sslEngine.getSession().getProtocol(), _sslEngine.getSession().getCipherSuite()); notifyHandshakeSucceeded(_sslEngine); } else if (_handshake.get() == Handshake.SUCCEEDED) @@ -832,7 +831,9 @@ public class SslConnection extends AbstractConnection implements Connection.Upgr LOG.debug(">flush {}", SslConnection.this); int i = 0; for (ByteBuffer b : appOuts) + { LOG.debug("flush b[{}]={}", i++, BufferUtil.toDetailString(b)); + } } // finish of any previous flushes @@ -895,10 +896,10 @@ public class SslConnection extends AbstractConnection implements Connection.Upgr } if (LOG.isDebugEnabled()) LOG.debug("wrap {} {} ioDone={}/{}", - StringUtil.replace(wrapResult.toString(), '\n', ' '), - BufferUtil.toSummaryString(_encryptedOutput), - _sslEngine.isInboundDone(), - _sslEngine.isOutboundDone()); + StringUtil.replace(wrapResult.toString(), '\n', ' '), + BufferUtil.toSummaryString(_encryptedOutput), + _sslEngine.isInboundDone(), + _sslEngine.isOutboundDone()); // Was all the data consumed? isEmpty = BufferUtil.isEmpty(appOuts); @@ -950,7 +951,7 @@ public class SslConnection extends AbstractConnection implements Connection.Upgr if (isEmpty) { if (wrapResult.getHandshakeStatus() != HandshakeStatus.NEED_WRAP || - wrapResult.bytesProduced() == 0) + wrapResult.bytesProduced() == 0) return result = true; } break; @@ -1115,7 +1116,9 @@ public class SslConnection extends AbstractConnection implements Connection.Upgr // and continue as if we are closed. The assumption here is that // the encrypted buffer will contain the entire close handshake // and that a call to flush(EMPTY_BUFFER) is not needed. - endp.write(Callback.from(() -> {}, t -> endp.close()), _encryptedOutput); + endp.write(Callback.from(() -> + { + }, t -> endp.close()), _encryptedOutput); } } @@ -1314,7 +1317,7 @@ public class SslConnection extends AbstractConnection implements Connection.Upgr @Override public void failed(final Throwable x) { - boolean fail_fill_interest; + boolean failFillInterest; synchronized (_decryptedEndPoint) { if (LOG.isDebugEnabled()) @@ -1324,14 +1327,14 @@ public class SslConnection extends AbstractConnection implements Connection.Upgr releaseEncryptedOutputBuffer(); _flushState = FlushState.IDLE; - fail_fill_interest = _fillState == FillState.WAIT_FOR_FLUSH; - if (fail_fill_interest) + failFillInterest = _fillState == FillState.WAIT_FOR_FLUSH; + if (failFillInterest) _fillState = FillState.IDLE; } getExecutor().execute(() -> { - if (fail_fill_interest) + if (failFillInterest) _decryptedEndPoint.getFillInterest().onFail(x); _decryptedEndPoint.getWriteFlusher().onFail(x); }); diff --git a/jetty-io/src/main/java/org/eclipse/jetty/io/ssl/SslHandshakeListener.java b/jetty-io/src/main/java/org/eclipse/jetty/io/ssl/SslHandshakeListener.java index edba6925749..22c5924c9ac 100644 --- a/jetty-io/src/main/java/org/eclipse/jetty/io/ssl/SslHandshakeListener.java +++ b/jetty-io/src/main/java/org/eclipse/jetty/io/ssl/SslHandshakeListener.java @@ -20,7 +20,6 @@ package org.eclipse.jetty.io.ssl; import java.util.EventListener; import java.util.EventObject; - import javax.net.ssl.SSLEngine; import javax.net.ssl.SSLException; diff --git a/jetty-io/src/test/java/org/eclipse/jetty/io/ArrayByteBufferPoolTest.java b/jetty-io/src/test/java/org/eclipse/jetty/io/ArrayByteBufferPoolTest.java index eabdfe6f7bc..57d6b496a6d 100644 --- a/jetty-io/src/test/java/org/eclipse/jetty/io/ArrayByteBufferPoolTest.java +++ b/jetty-io/src/test/java/org/eclipse/jetty/io/ArrayByteBufferPoolTest.java @@ -87,9 +87,9 @@ public class ArrayByteBufferPoolTest bufferPool.release(buffer); int pooled = Arrays.stream(buckets) - .filter(Objects::nonNull) - .mapToInt(Bucket::size) - .sum(); + .filter(Objects::nonNull) + .mapToInt(Bucket::size) + .sum(); assertEquals(size <= 1000, 1 == pooled); } } @@ -116,9 +116,9 @@ public class ArrayByteBufferPoolTest bufferPool.release(buffer); int pooled = Arrays.stream(buckets) - .filter(Objects::nonNull) - .mapToInt(Bucket::size) - .sum(); + .filter(Objects::nonNull) + .mapToInt(Bucket::size) + .sum(); assertEquals(1, pooled); } } @@ -140,9 +140,9 @@ public class ArrayByteBufferPoolTest bufferPool.release(buffer3); int pooled = Arrays.stream(buckets) - .filter(Objects::nonNull) - .mapToInt(Bucket::size) - .sum(); + .filter(Objects::nonNull) + .mapToInt(Bucket::size) + .sum(); assertEquals(1, pooled); assertSame(buffer1, buffer2); @@ -161,15 +161,15 @@ public class ArrayByteBufferPoolTest Bucket[] buckets = bufferPool.bucketsFor(false); Arrays.stream(buckets) - .filter(Objects::nonNull) - .forEach(b -> assertEquals(0, b.size())); + .filter(Objects::nonNull) + .forEach(b -> assertEquals(0, b.size())); bufferPool.release(buffer1); Bucket bucket = Arrays.stream(buckets) - .filter(Objects::nonNull) - .filter(b -> b.size() > 0) - .findFirst() - .orElseThrow(AssertionError::new); + .filter(Objects::nonNull) + .filter(b -> b.size() > 0) + .findFirst() + .orElseThrow(AssertionError::new); assertEquals(1, bucket.size()); bufferPool.release(buffer2); diff --git a/jetty-io/src/test/java/org/eclipse/jetty/io/ByteArrayEndPointTest.java b/jetty-io/src/test/java/org/eclipse/jetty/io/ByteArrayEndPointTest.java index bcbec949ce5..01dc31af16f 100644 --- a/jetty-io/src/test/java/org/eclipse/jetty/io/ByteArrayEndPointTest.java +++ b/jetty-io/src/test/java/org/eclipse/jetty/io/ByteArrayEndPointTest.java @@ -18,16 +18,6 @@ package org.eclipse.jetty.io; -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.containsString; -import static org.hamcrest.Matchers.greaterThan; -import static org.hamcrest.Matchers.instanceOf; -import static org.hamcrest.Matchers.is; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertFalse; -import static org.junit.jupiter.api.Assertions.assertTrue; -import static org.junit.jupiter.api.Assertions.fail; - import java.io.IOException; import java.nio.ByteBuffer; import java.util.concurrent.ExecutionException; @@ -42,6 +32,16 @@ import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.containsString; +import static org.hamcrest.Matchers.greaterThan; +import static org.hamcrest.Matchers.instanceOf; +import static org.hamcrest.Matchers.is; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.fail; + public class ByteArrayEndPointTest { private Scheduler _scheduler; @@ -67,20 +67,20 @@ public class ByteArrayEndPointTest ByteBuffer buffer = BufferUtil.allocate(1024); - assertEquals(10,endp.fill(buffer)); - assertEquals("test input",BufferUtil.toString(buffer)); + assertEquals(10, endp.fill(buffer)); + assertEquals("test input", BufferUtil.toString(buffer)); - assertEquals(0,endp.fill(buffer)); + assertEquals(0, endp.fill(buffer)); endp.addInput(" more"); - assertEquals(5,endp.fill(buffer)); - assertEquals("test input more",BufferUtil.toString(buffer)); + assertEquals(5, endp.fill(buffer)); + assertEquals("test input more", BufferUtil.toString(buffer)); - assertEquals(0,endp.fill(buffer)); + assertEquals(0, endp.fill(buffer)); endp.addInput((ByteBuffer)null); - assertEquals(-1,endp.fill(buffer)); + assertEquals(-1, endp.fill(buffer)); endp.close(); @@ -89,66 +89,65 @@ public class ByteArrayEndPointTest endp.fill(buffer); fail("Expected IOException"); } - catch(IOException e) + catch (IOException e) { - assertThat(e.getMessage(),containsString("CLOSED")); + assertThat(e.getMessage(), containsString("CLOSED")); } endp.reset(); endp.addInput("and more"); buffer = BufferUtil.allocate(4); - assertEquals(4,endp.fill(buffer)); - assertEquals("and ",BufferUtil.toString(buffer)); - assertEquals(0,endp.fill(buffer)); + assertEquals(4, endp.fill(buffer)); + assertEquals("and ", BufferUtil.toString(buffer)); + assertEquals(0, endp.fill(buffer)); BufferUtil.clear(buffer); - assertEquals(4,endp.fill(buffer)); - assertEquals("more",BufferUtil.toString(buffer)); + assertEquals(4, endp.fill(buffer)); + assertEquals("more", BufferUtil.toString(buffer)); } @Test public void testGrowingFlush() throws Exception { - ByteArrayEndPoint endp = new ByteArrayEndPoint((byte[])null,15); + ByteArrayEndPoint endp = new ByteArrayEndPoint((byte[])null, 15); endp.setGrowOutput(true); - assertEquals(true,endp.flush(BufferUtil.toBuffer("some output"))); - assertEquals("some output",endp.getOutputString()); + assertEquals(true, endp.flush(BufferUtil.toBuffer("some output"))); + assertEquals("some output", endp.getOutputString()); - assertEquals(true,endp.flush(BufferUtil.toBuffer(" some more"))); - assertEquals("some output some more",endp.getOutputString()); + assertEquals(true, endp.flush(BufferUtil.toBuffer(" some more"))); + assertEquals("some output some more", endp.getOutputString()); - assertEquals(true,endp.flush()); - assertEquals("some output some more",endp.getOutputString()); + assertEquals(true, endp.flush()); + assertEquals("some output some more", endp.getOutputString()); - assertEquals(true,endp.flush(BufferUtil.EMPTY_BUFFER)); - assertEquals("some output some more",endp.getOutputString()); + assertEquals(true, endp.flush(BufferUtil.EMPTY_BUFFER)); + assertEquals("some output some more", endp.getOutputString()); - assertEquals(true,endp.flush(BufferUtil.EMPTY_BUFFER,BufferUtil.toBuffer(" and"),BufferUtil.toBuffer(" more"))); - assertEquals("some output some more and more",endp.getOutputString()); + assertEquals(true, endp.flush(BufferUtil.EMPTY_BUFFER, BufferUtil.toBuffer(" and"), BufferUtil.toBuffer(" more"))); + assertEquals("some output some more and more", endp.getOutputString()); endp.close(); } @Test public void testFlush() throws Exception { - ByteArrayEndPoint endp = new ByteArrayEndPoint((byte[])null,15); + ByteArrayEndPoint endp = new ByteArrayEndPoint((byte[])null, 15); endp.setGrowOutput(false); endp.setOutput(BufferUtil.allocate(10)); ByteBuffer data = BufferUtil.toBuffer("Some more data."); - assertEquals(false,endp.flush(data)); - assertEquals("Some more ",endp.getOutputString()); - assertEquals("data.",BufferUtil.toString(data)); + assertEquals(false, endp.flush(data)); + assertEquals("Some more ", endp.getOutputString()); + assertEquals("data.", BufferUtil.toString(data)); - assertEquals("Some more ",endp.takeOutputString()); + assertEquals("Some more ", endp.takeOutputString()); - assertEquals(true,endp.flush(data)); - assertEquals("data.",BufferUtil.toString(endp.takeOutput())); + assertEquals(true, endp.flush(data)); + assertEquals("data.", BufferUtil.toString(endp.takeOutput())); endp.close(); } - @Test public void testReadable() throws Exception { @@ -159,7 +158,7 @@ public class ByteArrayEndPointTest FutureCallback fcb = new FutureCallback(); endp.fillInterested(fcb); - fcb.get(100,TimeUnit.MILLISECONDS); + fcb.get(100, TimeUnit.MILLISECONDS); assertTrue(fcb.isDone()); assertEquals(null, fcb.get()); assertEquals(10, endp.fill(buffer)); @@ -172,7 +171,7 @@ public class ByteArrayEndPointTest assertEquals(0, endp.fill(buffer)); endp.addInput(" more"); - fcb.get(1000,TimeUnit.MILLISECONDS); + fcb.get(1000, TimeUnit.MILLISECONDS); assertTrue(fcb.isDone()); assertEquals(null, fcb.get()); assertEquals(5, endp.fill(buffer)); @@ -191,7 +190,7 @@ public class ByteArrayEndPointTest fcb = new FutureCallback(); endp.fillInterested(fcb); - fcb.get(1000,TimeUnit.MILLISECONDS); + fcb.get(1000, TimeUnit.MILLISECONDS); assertTrue(fcb.isDone()); assertEquals(null, fcb.get()); assertEquals(-1, endp.fill(buffer)); @@ -203,7 +202,7 @@ public class ByteArrayEndPointTest try { - fcb.get(1000,TimeUnit.MILLISECONDS); + fcb.get(1000, TimeUnit.MILLISECONDS); fail("Expected ExecutionException"); } catch (ExecutionException e) @@ -223,7 +222,7 @@ public class ByteArrayEndPointTest ByteBuffer more = BufferUtil.toBuffer(" Some more."); FutureCallback fcb = new FutureCallback(); - endp.write( fcb, data); + endp.write(fcb, data); assertTrue(fcb.isDone()); assertEquals(null, fcb.get()); assertEquals("Data.", endp.getOutputString()); @@ -240,7 +239,7 @@ public class ByteArrayEndPointTest assertEquals(" more.", endp.getOutputString()); endp.close(); } - + /** * Simulate AbstractConnection.ReadCallback.failed() */ @@ -303,6 +302,5 @@ public class ByteArrayEndPointTest } assertThat(TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - start), greaterThan(halfIdleTimeout)); assertThat("Endpoint open", endp.isOpen(), is(true)); - } } diff --git a/jetty-io/src/test/java/org/eclipse/jetty/io/CyclicTimeoutTest.java b/jetty-io/src/test/java/org/eclipse/jetty/io/CyclicTimeoutTest.java index 293f8954d3e..e9438fd43d8 100644 --- a/jetty-io/src/test/java/org/eclipse/jetty/io/CyclicTimeoutTest.java +++ b/jetty-io/src/test/java/org/eclipse/jetty/io/CyclicTimeoutTest.java @@ -18,20 +18,19 @@ package org.eclipse.jetty.io; -import static org.junit.jupiter.api.Assertions.assertFalse; -import static org.junit.jupiter.api.Assertions.assertTrue; - import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; import org.eclipse.jetty.util.thread.QueuedThreadPool; import org.eclipse.jetty.util.thread.ScheduledExecutorScheduler; import org.junit.jupiter.api.AfterEach; - import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.Test; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; + public class CyclicTimeoutTest { private volatile boolean _expired; @@ -41,10 +40,10 @@ public class CyclicTimeoutTest @BeforeEach public void before() throws Exception { - _expired=false; + _expired = false; _timer.start(); - - _timeout=new CyclicTimeout(_timer) + + _timeout = new CyclicTimeout(_timer) { @Override public void onTimeoutExpired() @@ -52,8 +51,8 @@ public class CyclicTimeoutTest _expired = true; } }; - - _timeout.schedule(1000,TimeUnit.MILLISECONDS); + + _timeout.schedule(1000, TimeUnit.MILLISECONDS); } @AfterEach @@ -66,10 +65,10 @@ public class CyclicTimeoutTest @Test public void testReschedule() throws Exception { - for (int i=0;i<20;i++) + for (int i = 0; i < 20; i++) { Thread.sleep(100); - assertTrue(_timeout.schedule(1000,TimeUnit.MILLISECONDS)); + assertTrue(_timeout.schedule(1000, TimeUnit.MILLISECONDS)); } assertFalse(_expired); } @@ -77,10 +76,10 @@ public class CyclicTimeoutTest @Test public void testExpire() throws Exception { - for (int i=0;i<5;i++) + for (int i = 0; i < 5; i++) { Thread.sleep(100); - assertTrue(_timeout.schedule(1000,TimeUnit.MILLISECONDS)); + assertTrue(_timeout.schedule(1000, TimeUnit.MILLISECONDS)); } Thread.sleep(1500); assertTrue(_expired); @@ -89,10 +88,10 @@ public class CyclicTimeoutTest @Test public void testCancel() throws Exception { - for (int i=0;i<5;i++) + for (int i = 0; i < 5; i++) { Thread.sleep(100); - assertTrue(_timeout.schedule(1000,TimeUnit.MILLISECONDS)); + assertTrue(_timeout.schedule(1000, TimeUnit.MILLISECONDS)); } _timeout.cancel(); Thread.sleep(1500); @@ -102,12 +101,12 @@ public class CyclicTimeoutTest @Test public void testShorten() throws Exception { - for (int i=0;i<5;i++) + for (int i = 0; i < 5; i++) { Thread.sleep(100); - assertTrue(_timeout.schedule(1000,TimeUnit.MILLISECONDS)); + assertTrue(_timeout.schedule(1000, TimeUnit.MILLISECONDS)); } - assertTrue(_timeout.schedule(100,TimeUnit.MILLISECONDS)); + assertTrue(_timeout.schedule(100, TimeUnit.MILLISECONDS)); Thread.sleep(400); assertTrue(_expired); } @@ -115,12 +114,12 @@ public class CyclicTimeoutTest @Test public void testLengthen() throws Exception { - for (int i=0;i<5;i++) + for (int i = 0; i < 5; i++) { Thread.sleep(100); - assertTrue(_timeout.schedule(1000,TimeUnit.MILLISECONDS)); + assertTrue(_timeout.schedule(1000, TimeUnit.MILLISECONDS)); } - assertTrue(_timeout.schedule(10000,TimeUnit.MILLISECONDS)); + assertTrue(_timeout.schedule(10000, TimeUnit.MILLISECONDS)); Thread.sleep(1500); assertFalse(_expired); } @@ -130,12 +129,12 @@ public class CyclicTimeoutTest { Thread.sleep(1500); assertTrue(_expired); - _expired=false; - assertFalse(_timeout.schedule(500,TimeUnit.MILLISECONDS)); + _expired = false; + assertFalse(_timeout.schedule(500, TimeUnit.MILLISECONDS)); Thread.sleep(1000); assertTrue(_expired); - _expired=false; - _timeout.schedule(500,TimeUnit.MILLISECONDS); + _expired = false; + _timeout.schedule(500, TimeUnit.MILLISECONDS); Thread.sleep(1000); assertTrue(_expired); } @@ -146,16 +145,16 @@ public class CyclicTimeoutTest { QueuedThreadPool pool = new QueuedThreadPool(200); pool.start(); - + long test_until = System.nanoTime() + TimeUnit.MILLISECONDS.toNanos(1500); - assertTrue(_timeout.schedule(100,TimeUnit.MILLISECONDS)); - while(System.nanoTime() + pool.execute(() -> { - _timeout.schedule(100,TimeUnit.MILLISECONDS); + _timeout.schedule(100, TimeUnit.MILLISECONDS); latch.countDown(); }); latch.await(); diff --git a/jetty-io/src/test/java/org/eclipse/jetty/io/IOTest.java b/jetty-io/src/test/java/org/eclipse/jetty/io/IOTest.java index 697a60184b9..a9b198eaced 100644 --- a/jetty-io/src/test/java/org/eclipse/jetty/io/IOTest.java +++ b/jetty-io/src/test/java/org/eclipse/jetty/io/IOTest.java @@ -18,15 +18,6 @@ package org.eclipse.jetty.io; -import static org.hamcrest.Matchers.is; -import static org.hamcrest.Matchers.notNullValue; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertFalse; -import static org.hamcrest.MatcherAssert.assertThat; -import static org.junit.jupiter.api.Assertions.assertThrows; -import static org.junit.jupiter.api.Assertions.assertTrue; -import static org.junit.jupiter.api.Assertions.fail; - import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.File; @@ -52,10 +43,18 @@ import java.util.concurrent.TimeUnit; import org.eclipse.jetty.toolchain.test.MavenTestingUtils; import org.eclipse.jetty.util.BufferUtil; import org.eclipse.jetty.util.IO; - import org.junit.jupiter.api.Test; import org.junit.jupiter.api.condition.OS; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.is; +import static org.hamcrest.Matchers.notNullValue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.fail; + public class IOTest { @Test @@ -227,7 +226,7 @@ public class IOTest catch (Exception e) { e.printStackTrace(); - assertTrue( OS.MAC.isCurrentOs()); + assertTrue(OS.MAC.isCurrentOs()); } } } @@ -289,10 +288,13 @@ public class IOTest client.getOutputStream().write(1); // Client eventually sees Broken Pipe - assertThrows(IOException.class, ()->{ + assertThrows(IOException.class, () -> + { int i = 0; for (i = 0; i < 100000; i++) + { client.getOutputStream().write(1); + } }); } } @@ -342,7 +344,9 @@ public class IOTest }); acceptor.start(); while (latch.getCount() == 2) + { Thread.sleep(10); + } // interrupt the acceptor acceptor.interrupt(); @@ -371,14 +375,12 @@ public class IOTest } } - - @Test public void testReset() throws Exception { try (ServerSocket connector = new ServerSocket(0); - Socket client = new Socket("127.0.0.1", connector.getLocalPort()); - Socket server = connector.accept()) + Socket client = new Socket("127.0.0.1", connector.getLocalPort()); + Socket server = connector.accept()) { client.setTcpNoDelay(true); client.setSoLinger(true, 0); @@ -417,12 +419,12 @@ public class IOTest { AsynchronousServerSocketChannel connector = AsynchronousServerSocketChannel.open(); connector.bind(null); - InetSocketAddress addr=(InetSocketAddress)connector.getLocalAddress(); + InetSocketAddress addr = (InetSocketAddress)connector.getLocalAddress(); Future acceptor = connector.accept(); AsynchronousSocketChannel client = AsynchronousSocketChannel.open(); - client.connect(new InetSocketAddress("127.0.0.1",addr.getPort())).get(5, TimeUnit.SECONDS); + client.connect(new InetSocketAddress("127.0.0.1", addr.getPort())).get(5, TimeUnit.SECONDS); AsynchronousSocketChannel server = acceptor.get(5, TimeUnit.SECONDS); @@ -447,31 +449,32 @@ public class IOTest if (!dir.exists()) dir.mkdir(); - File file = File.createTempFile("test",".txt",dir); + File file = File.createTempFile("test", ".txt", dir); file.deleteOnExit(); FileChannel out = FileChannel.open(file.toPath(), - StandardOpenOption.CREATE, - StandardOpenOption.READ, - StandardOpenOption.WRITE, - StandardOpenOption.DELETE_ON_CLOSE); + StandardOpenOption.CREATE, + StandardOpenOption.READ, + StandardOpenOption.WRITE, + StandardOpenOption.DELETE_ON_CLOSE); ByteBuffer[] buffers = new ByteBuffer[4096]; - long expected=0; - for (int i=0;i 0) + { clientInput.read(); + } assertNull(failure.get()); } diff --git a/jetty-io/src/test/java/org/eclipse/jetty/io/SocketChannelEndPointOpenCloseTest.java b/jetty-io/src/test/java/org/eclipse/jetty/io/SocketChannelEndPointOpenCloseTest.java index 332e48f869c..b3fa6288093 100644 --- a/jetty-io/src/test/java/org/eclipse/jetty/io/SocketChannelEndPointOpenCloseTest.java +++ b/jetty-io/src/test/java/org/eclipse/jetty/io/SocketChannelEndPointOpenCloseTest.java @@ -18,10 +18,6 @@ package org.eclipse.jetty.io; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertFalse; -import static org.junit.jupiter.api.Assertions.assertTrue; - import java.nio.ByteBuffer; import java.nio.channels.ServerSocketChannel; import java.nio.channels.SocketChannel; @@ -31,6 +27,10 @@ import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; + public class SocketChannelEndPointOpenCloseTest { public static class EndPointPair @@ -52,15 +52,15 @@ public class SocketChannelEndPointOpenCloseTest public static void close() throws Exception { connector.close(); - connector=null; + connector = null; } private EndPointPair newConnection() throws Exception { EndPointPair c = new EndPointPair(); - c.client=new SocketChannelEndPoint(SocketChannel.open(connector.socket().getLocalSocketAddress()),null,null,null); - c.server=new SocketChannelEndPoint(connector.accept(),null,null,null); + c.client = new SocketChannelEndPoint(SocketChannel.open(connector.socket().getLocalSocketAddress()), null, null, null); + c.server = new SocketChannelEndPoint(connector.accept(), null, null, null); return c; } @@ -75,8 +75,8 @@ public class SocketChannelEndPointOpenCloseTest // Server receives the request int len = c.server.fill(buffer); - assertEquals(7,len); - assertEquals("request",BufferUtil.toString(buffer)); + assertEquals(7, len); + assertEquals("request", BufferUtil.toString(buffer)); // Client and server are open assertTrue(c.client.isOpen()); @@ -97,8 +97,8 @@ public class SocketChannelEndPointOpenCloseTest // Client reads response BufferUtil.clear(buffer); len = c.client.fill(buffer); - assertEquals(8,len); - assertEquals("response",BufferUtil.toString(buffer)); + assertEquals(8, len); + assertEquals("response", BufferUtil.toString(buffer)); // Client and server are open, server is oshut assertTrue(c.client.isOpen()); @@ -109,7 +109,7 @@ public class SocketChannelEndPointOpenCloseTest // Client reads -1 BufferUtil.clear(buffer); len = c.client.fill(buffer); - assertEquals(-1,len); + assertEquals(-1, len); // Client and server are open, server is oshut, client is ishut assertTrue(c.client.isOpen()); @@ -129,7 +129,7 @@ public class SocketChannelEndPointOpenCloseTest // Server reads close BufferUtil.clear(buffer); len = c.server.fill(buffer); - assertEquals(-1,len); + assertEquals(-1, len); // Client and Server are closed assertFalse(c.client.isOpen()); @@ -146,8 +146,8 @@ public class SocketChannelEndPointOpenCloseTest c.client.flush(BufferUtil.toBuffer("request")); int len = c.server.fill(buffer); - assertEquals(7,len); - assertEquals("request",BufferUtil.toString(buffer)); + assertEquals(7, len); + assertEquals("request", BufferUtil.toString(buffer)); assertTrue(c.client.isOpen()); assertFalse(c.client.isOutputShutdown()); @@ -162,7 +162,7 @@ public class SocketChannelEndPointOpenCloseTest assertFalse(c.server.isOutputShutdown()); len = c.server.fill(buffer); - assertEquals(-1,len); + assertEquals(-1, len); assertFalse(c.client.isOpen()); assertTrue(c.client.isOutputShutdown()); @@ -176,5 +176,4 @@ public class SocketChannelEndPointOpenCloseTest assertFalse(c.server.isOpen()); assertTrue(c.server.isOutputShutdown()); } - } diff --git a/jetty-io/src/test/java/org/eclipse/jetty/io/SocketChannelEndPointTest.java b/jetty-io/src/test/java/org/eclipse/jetty/io/SocketChannelEndPointTest.java index a2292d3a298..7970e1e0e8c 100644 --- a/jetty-io/src/test/java/org/eclipse/jetty/io/SocketChannelEndPointTest.java +++ b/jetty-io/src/test/java/org/eclipse/jetty/io/SocketChannelEndPointTest.java @@ -158,7 +158,7 @@ public class SocketChannelEndPointTest // wait for read timeout client.setSoTimeout(500); long start = TimeUnit.NANOSECONDS.toMillis(System.nanoTime()); - assertThrows(SocketTimeoutException.class, ()-> client.getInputStream().read()); + assertThrows(SocketTimeoutException.class, () -> client.getInputStream().read()); long duration = TimeUnit.NANOSECONDS.toMillis(System.nanoTime()) - start; assertThat("timeout duration", duration, greaterThanOrEqualTo(400L)); @@ -170,7 +170,7 @@ public class SocketChannelEndPointTest { int b = client.getInputStream().read(); assertThat("expect valid char integer", b, greaterThan(0)); - assertEquals(c, (char) b, "expect characters to be same"); + assertEquals(c, (char)b, "expect characters to be same"); } client.close(); @@ -213,7 +213,7 @@ public class SocketChannelEndPointTest // wait for read timeout long start = TimeUnit.NANOSECONDS.toMillis(System.nanoTime()); - assertThrows(SocketTimeoutException.class, ()-> client.getInputStream().read()); + assertThrows(SocketTimeoutException.class, () -> client.getInputStream().read()); assertTrue(TimeUnit.NANOSECONDS.toMillis(System.nanoTime()) - start >= 400); // write then shutdown @@ -261,8 +261,8 @@ public class SocketChannelEndPointTest Thread.sleep((11 * specifiedTimeout) / 10); long start = TimeUnit.NANOSECONDS.toMillis(System.nanoTime()); - assertThrows(SocketTimeoutException.class, ()-> clientInputStream.read()); - int elapsed = (int) (TimeUnit.NANOSECONDS.toMillis(System.nanoTime()) - start); + assertThrows(SocketTimeoutException.class, () -> clientInputStream.read()); + int elapsed = (int)(TimeUnit.NANOSECONDS.toMillis(System.nanoTime()) - start); assertThat("Expected timeout", elapsed, greaterThanOrEqualTo(3 * specifiedTimeout / 4)); // write remaining characters @@ -416,7 +416,7 @@ public class SocketChannelEndPointTest int b = in.read(); byteNum++; assertTrue(b > 0); - assertEquals(c, (char) b, "test-" + i + "/" + j); + assertEquals(c, (char)b, "test-" + i + "/" + j); } if (i == 0) @@ -445,7 +445,6 @@ public class SocketChannelEndPointTest } } - @ParameterizedTest @MethodSource("scenarios") @Tag("Unstable") @@ -815,7 +814,7 @@ public class SocketChannelEndPointTest } catch (InterruptedException | EofException e) { - if(LOG.isDebugEnabled()) + if (LOG.isDebugEnabled()) LOG.debug(e); else LOG.info(e.getClass().getName()); diff --git a/jetty-io/src/test/java/org/eclipse/jetty/io/SslConnectionTest.java b/jetty-io/src/test/java/org/eclipse/jetty/io/SslConnectionTest.java index 70634cac55a..92395418ceb 100644 --- a/jetty-io/src/test/java/org/eclipse/jetty/io/SslConnectionTest.java +++ b/jetty-io/src/test/java/org/eclipse/jetty/io/SslConnectionTest.java @@ -34,7 +34,6 @@ import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; - import javax.net.ssl.SSLEngine; import javax.net.ssl.SSLException; import javax.net.ssl.SSLSocket; @@ -66,8 +65,8 @@ public class SslConnectionTest private final SslContextFactory _sslCtxFactory = new SslContextFactory.Server(); protected volatile EndPoint _lastEndp; - private volatile boolean _testFill=true; - private volatile boolean _onXWriteThenShutdown=false; + private volatile boolean _testFill = true; + private volatile boolean _onXWriteThenShutdown = false; private volatile FutureCallback _writeCallback; protected ServerSocketChannel _connector; @@ -80,7 +79,6 @@ public class SslConnectionTest _dispatches.incrementAndGet(); super.execute(job); } - }; protected Scheduler _scheduler = new TimerScheduler(); protected SelectorManager _manager = new SelectorManager(_threadPool, _scheduler) @@ -103,7 +101,7 @@ public class SslConnectionTest { SocketChannelEndPoint endp = new TestEP(channel, selector, selectionKey, getScheduler()); endp.setIdleTimeout(TIMEOUT); - _lastEndp=endp; + _lastEndp = endp; return endp; } }; @@ -111,11 +109,12 @@ public class SslConnectionTest static final AtomicInteger __startBlocking = new AtomicInteger(); static final AtomicInteger __blockFor = new AtomicInteger(); static final AtomicBoolean __onIncompleteFlush = new AtomicBoolean(); + private static class TestEP extends SocketChannelEndPoint { public TestEP(SelectableChannel channel, ManagedSelector selector, SelectionKey key, Scheduler scheduler) { - super((SocketChannel)channel,selector,key,scheduler); + super((SocketChannel)channel, selector, key, scheduler); } @Override @@ -123,15 +122,14 @@ public class SslConnectionTest { __onIncompleteFlush.set(true); } - @Override public boolean flush(ByteBuffer... buffers) throws IOException { __onIncompleteFlush.set(false); - if (__startBlocking.get()==0 || __startBlocking.decrementAndGet()==0) + if (__startBlocking.get() == 0 || __startBlocking.decrementAndGet() == 0) { - if (__blockFor.get()>0 && __blockFor.getAndDecrement()>0) + if (__blockFor.get() > 0 && __blockFor.getAndDecrement() > 0) { return false; } @@ -154,9 +152,9 @@ public class SslConnectionTest public void startManager() throws Exception { - _testFill=true; - _writeCallback=null; - _lastEndp=null; + _testFill = true; + _writeCallback = null; + _lastEndp = null; _connector = ServerSocketChannel.open(); _connector.socket().bind(null); _threadPool.start(); @@ -188,7 +186,7 @@ public class SslConnectionTest public class TestConnection extends AbstractConnection { - ByteBuffer _in = BufferUtil.allocate(8*1024); + ByteBuffer _in = BufferUtil.allocate(8 * 1024); public TestConnection(EndPoint endp) { @@ -203,7 +201,7 @@ public class SslConnectionTest fillInterested(); else { - getExecutor().execute(() -> getEndPoint().write(_writeCallback,BufferUtil.toBuffer("Hello Client"))); + getExecutor().execute(() -> getEndPoint().write(_writeCallback, BufferUtil.toBuffer("Hello Client"))); } } @@ -219,28 +217,28 @@ public class SslConnectionTest EndPoint endp = getEndPoint(); try { - boolean progress=true; - while(progress) + boolean progress = true; + while (progress) { - progress=false; + progress = false; // Fill the input buffer with everything available - int filled=endp.fill(_in); - while (filled>0) + int filled = endp.fill(_in); + while (filled > 0) { - progress=true; - filled=endp.fill(_in); + progress = true; + filled = endp.fill(_in); } boolean shutdown = _onXWriteThenShutdown && BufferUtil.toString(_in).contains("X"); // Write everything - int l=_in.remaining(); - if (l>0) + int l = _in.remaining(); + if (l > 0) { - FutureCallback blockingWrite= new FutureCallback(); + FutureCallback blockingWrite = new FutureCallback(); - endp.write(blockingWrite,_in); + endp.write(blockingWrite, _in); blockingWrite.get(); if (shutdown) endp.shutdownOutput(); @@ -251,11 +249,11 @@ public class SslConnectionTest endp.shutdownOutput(); } } - catch(InterruptedException|EofException e) + catch (InterruptedException | EofException e) { Log.getRootLogger().ignore(e); } - catch(Exception e) + catch (Exception e) { Log.getRootLogger().warn(e); } @@ -285,7 +283,7 @@ public class SslConnectionTest { server.configureBlocking(false); _manager.accept(server); - + client.getOutputStream().write("Hello".getBytes(StandardCharsets.UTF_8)); byte[] buffer = new byte[1024]; int len = client.getInputStream().read(buffer); @@ -296,7 +294,9 @@ public class SslConnectionTest client.getOutputStream().write("World".getBytes(StandardCharsets.UTF_8)); len = 5; while (len > 0) + { len -= client.getInputStream().read(buffer); + } } } } @@ -354,7 +354,7 @@ public class SslConnectionTest client.startHandshake(); client.getOutputStream().write("World".getBytes(StandardCharsets.UTF_8)); - assertThrows(SSLException.class, ()-> client.getInputStream().read(buffer)); + assertThrows(SSLException.class, () -> client.getInputStream().read(buffer)); } } } @@ -398,7 +398,7 @@ public class SslConnectionTest client.startHandshake(); client.getOutputStream().write("World".getBytes(StandardCharsets.UTF_8)); - assertThrows(SSLException.class, ()-> client.getInputStream().read(buffer)); + assertThrows(SSLException.class, () -> client.getInputStream().read(buffer)); } } } @@ -406,7 +406,7 @@ public class SslConnectionTest @Test public void testWriteOnConnect() throws Exception { - _testFill=false; + _testFill = false; _writeCallback = new FutureCallback(); startSSL(); try (SSLSocket client = newClient()) @@ -458,11 +458,10 @@ public class SslConnectionTest client.getInputStream().read(buffer); throw new IllegalStateException(); } - catch(SocketTimeoutException e) + catch (SocketTimeoutException e) { } - assertTrue(__onIncompleteFlush.get()); ((TestEP)_lastEndp).getWriteFlusher().completeWrite(); @@ -492,7 +491,7 @@ public class SslConnectionTest int len = client.getInputStream().read(buffer); assertEquals("Short", new String(buffer, 0, len, StandardCharsets.UTF_8)); - _onXWriteThenShutdown=true; + _onXWriteThenShutdown = true; __startBlocking.set(2); // block on the close handshake flush __blockFor.set(Integer.MAX_VALUE); // > retry loops in SslConnection + 1 client.getOutputStream().write("This is a much longer example with X".getBytes(StandardCharsets.UTF_8)); @@ -505,7 +504,7 @@ public class SslConnectionTest client.getInputStream().read(buffer); throw new IllegalStateException(); } - catch(SocketTimeoutException e) + catch (SocketTimeoutException e) { } diff --git a/jetty-io/src/test/java/org/eclipse/jetty/io/SslEngineBehaviorTest.java b/jetty-io/src/test/java/org/eclipse/jetty/io/SslEngineBehaviorTest.java index d8bee115735..d4b475b2969 100644 --- a/jetty-io/src/test/java/org/eclipse/jetty/io/SslEngineBehaviorTest.java +++ b/jetty-io/src/test/java/org/eclipse/jetty/io/SslEngineBehaviorTest.java @@ -20,7 +20,6 @@ package org.eclipse.jetty.io; import java.io.File; import java.nio.ByteBuffer; - import javax.net.ssl.SSLEngine; import javax.net.ssl.SSLEngineResult; @@ -76,68 +75,68 @@ public class SslEngineBehaviorTest // start the client client.setUseClientMode(true); client.beginHandshake(); - assertEquals(SSLEngineResult.HandshakeStatus.NEED_WRAP,client.getHandshakeStatus()); + assertEquals(SSLEngineResult.HandshakeStatus.NEED_WRAP, client.getHandshakeStatus()); // what if we try an unwrap? netS2C.flip(); - result=client.unwrap(netS2C,clientIn); + result = client.unwrap(netS2C, clientIn); // unwrap is a noop - assertEquals(SSLEngineResult.Status.OK,result.getStatus()); - assertEquals(0,result.bytesConsumed()); - assertEquals(0,result.bytesProduced()); - assertEquals(SSLEngineResult.HandshakeStatus.NEED_WRAP,result.getHandshakeStatus()); + assertEquals(SSLEngineResult.Status.OK, result.getStatus()); + assertEquals(0, result.bytesConsumed()); + assertEquals(0, result.bytesProduced()); + assertEquals(SSLEngineResult.HandshakeStatus.NEED_WRAP, result.getHandshakeStatus()); netS2C.clear(); // do the needed WRAP of empty buffer - result=client.wrap(BufferUtil.EMPTY_BUFFER,netC2S); + result = client.wrap(BufferUtil.EMPTY_BUFFER, netC2S); // unwrap is a noop - assertEquals(SSLEngineResult.Status.OK,result.getStatus()); - assertEquals(0,result.bytesConsumed()); - assertThat(result.bytesProduced(),greaterThan(0)); - assertEquals(SSLEngineResult.HandshakeStatus.NEED_UNWRAP,result.getHandshakeStatus()); + assertEquals(SSLEngineResult.Status.OK, result.getStatus()); + assertEquals(0, result.bytesConsumed()); + assertThat(result.bytesProduced(), greaterThan(0)); + assertEquals(SSLEngineResult.HandshakeStatus.NEED_UNWRAP, result.getHandshakeStatus()); netC2S.flip(); - assertEquals(netC2S.remaining(),result.bytesProduced()); + assertEquals(netC2S.remaining(), result.bytesProduced()); // start the server server.setUseClientMode(false); server.beginHandshake(); - assertEquals(SSLEngineResult.HandshakeStatus.NEED_UNWRAP,server.getHandshakeStatus()); + assertEquals(SSLEngineResult.HandshakeStatus.NEED_UNWRAP, server.getHandshakeStatus()); // what if we try a needless wrap? serverOut.put(BufferUtil.toBuffer("Hello World")); serverOut.flip(); - result=server.wrap(serverOut,netS2C); + result = server.wrap(serverOut, netS2C); // wrap is a noop - assertEquals(SSLEngineResult.Status.OK,result.getStatus()); - assertEquals(0,result.bytesConsumed()); - assertEquals(0,result.bytesProduced()); - assertEquals(SSLEngineResult.HandshakeStatus.NEED_UNWRAP,result.getHandshakeStatus()); + assertEquals(SSLEngineResult.Status.OK, result.getStatus()); + assertEquals(0, result.bytesConsumed()); + assertEquals(0, result.bytesProduced()); + assertEquals(SSLEngineResult.HandshakeStatus.NEED_UNWRAP, result.getHandshakeStatus()); // Do the needed unwrap, to an empty buffer - result=server.unwrap(netC2S,BufferUtil.EMPTY_BUFFER); - assertEquals(SSLEngineResult.Status.BUFFER_OVERFLOW,result.getStatus()); - assertEquals(0,result.bytesConsumed()); - assertEquals(0,result.bytesProduced()); - assertEquals(SSLEngineResult.HandshakeStatus.NEED_UNWRAP,result.getHandshakeStatus()); + result = server.unwrap(netC2S, BufferUtil.EMPTY_BUFFER); + assertEquals(SSLEngineResult.Status.BUFFER_OVERFLOW, result.getStatus()); + assertEquals(0, result.bytesConsumed()); + assertEquals(0, result.bytesProduced()); + assertEquals(SSLEngineResult.HandshakeStatus.NEED_UNWRAP, result.getHandshakeStatus()); // Do the needed unwrap, to a full buffer serverIn.position(serverIn.limit()); - result=server.unwrap(netC2S,serverIn); - assertEquals(SSLEngineResult.Status.BUFFER_OVERFLOW,result.getStatus()); - assertEquals(0,result.bytesConsumed()); - assertEquals(0,result.bytesProduced()); - assertEquals(SSLEngineResult.HandshakeStatus.NEED_UNWRAP,result.getHandshakeStatus()); + result = server.unwrap(netC2S, serverIn); + assertEquals(SSLEngineResult.Status.BUFFER_OVERFLOW, result.getStatus()); + assertEquals(0, result.bytesConsumed()); + assertEquals(0, result.bytesProduced()); + assertEquals(SSLEngineResult.HandshakeStatus.NEED_UNWRAP, result.getHandshakeStatus()); // Do the needed unwrap, to an empty buffer serverIn.clear(); - result=server.unwrap(netC2S,serverIn); - assertEquals(SSLEngineResult.Status.OK,result.getStatus()); - assertThat(result.bytesConsumed(),greaterThan(0)); - assertEquals(0,result.bytesProduced()); - assertEquals(SSLEngineResult.HandshakeStatus.NEED_TASK,result.getHandshakeStatus()); + result = server.unwrap(netC2S, serverIn); + assertEquals(SSLEngineResult.Status.OK, result.getStatus()); + assertThat(result.bytesConsumed(), greaterThan(0)); + assertEquals(0, result.bytesProduced()); + assertEquals(SSLEngineResult.HandshakeStatus.NEED_TASK, result.getHandshakeStatus()); server.getDelegatedTask().run(); - assertEquals(SSLEngineResult.HandshakeStatus.NEED_WRAP,server.getHandshakeStatus()); + assertEquals(SSLEngineResult.HandshakeStatus.NEED_WRAP, server.getHandshakeStatus()); } } diff --git a/jetty-io/src/test/java/org/eclipse/jetty/io/WriteFlusherTest.java b/jetty-io/src/test/java/org/eclipse/jetty/io/WriteFlusherTest.java index f1d6aeb2b32..7a062d9b72a 100644 --- a/jetty-io/src/test/java/org/eclipse/jetty/io/WriteFlusherTest.java +++ b/jetty-io/src/test/java/org/eclipse/jetty/io/WriteFlusherTest.java @@ -110,7 +110,8 @@ public class WriteFlusherTest assertTrue(callback.isDone()); assertFalse(incompleteFlush.get()); - ExecutionException e = assertThrows(ExecutionException.class, ()->{ + ExecutionException e = assertThrows(ExecutionException.class, () -> + { callback.get(); }); assertThat(e.getCause(), instanceOf(IOException.class)); @@ -143,7 +144,8 @@ public class WriteFlusherTest assertTrue(incompleteFlush.get()); - assertThrows(TimeoutException.class, ()->{ + assertThrows(TimeoutException.class, () -> + { callback.get(100, TimeUnit.MILLISECONDS); }); @@ -228,7 +230,7 @@ public class WriteFlusherTest assertTrue(callback.isDone()); assertFalse(incompleteFlush.get()); - ExecutionException e = assertThrows(ExecutionException.class, ()-> callback.get()); + ExecutionException e = assertThrows(ExecutionException.class, () -> callback.get()); assertThat(e.getCause(), instanceOf(IOException.class)); assertThat(e.getCause().getMessage(), containsString("CLOSED")); @@ -269,7 +271,7 @@ public class WriteFlusherTest assertTrue(callback.isDone()); assertFalse(incompleteFlush.get()); - ExecutionException e = assertThrows(ExecutionException.class, ()-> callback.get()); + ExecutionException e = assertThrows(ExecutionException.class, () -> callback.get()); assertThat(e.getCause(), instanceOf(IOException.class)); assertThat(e.getCause().getMessage(), containsString(reason)); @@ -348,7 +350,6 @@ public class WriteFlusherTest } }; - flusher.write(Callback.NOOP, buffer1, buffer2); assertTrue(incompleteFlush.get()); assertFalse(buffer1.hasRemaining()); @@ -399,7 +400,8 @@ public class WriteFlusherTest new Thread(() -> flusher.write(Callback.NOOP, BufferUtil.toBuffer("foo"))).start(); assertTrue(flushLatch.await(1, TimeUnit.SECONDS)); - assertThrows(WritePendingException.class, ()->{ + assertThrows(WritePendingException.class, () -> + { // The second write throws WritePendingException. flusher.write(Callback.NOOP, BufferUtil.toBuffer("bar")); }); @@ -408,18 +410,19 @@ public class WriteFlusherTest @Test public void testConcurrentWriteAndOnFail() throws Exception { - assertThrows( ExecutionException.class , () -> { - ByteArrayEndPoint endPoint = new ByteArrayEndPoint( new byte[0], 16 ); + assertThrows(ExecutionException.class, () -> + { + ByteArrayEndPoint endPoint = new ByteArrayEndPoint(new byte[0], 16); - WriteFlusher flusher = new WriteFlusher( endPoint ) + WriteFlusher flusher = new WriteFlusher(endPoint) { @Override - protected ByteBuffer[] flush( ByteBuffer[] buffers ) + protected ByteBuffer[] flush(ByteBuffer[] buffers) throws IOException { - ByteBuffer[] result = super.flush( buffers ); - boolean notified = onFail( new Throwable() ); - assertTrue( notified ); + ByteBuffer[] result = super.flush(buffers); + boolean notified = onFail(new Throwable()); + assertTrue(notified); return result; } @@ -430,11 +433,11 @@ public class WriteFlusherTest }; FutureCallback callback = new FutureCallback(); - flusher.write( callback, BufferUtil.toBuffer( "foo" ) ); + flusher.write(callback, BufferUtil.toBuffer("foo")); - assertTrue( flusher.isFailed() ); + assertTrue(flusher.isFailed()); - callback.get( 1, TimeUnit.SECONDS ); + callback.get(1, TimeUnit.SECONDS); }); } diff --git a/jetty-jaas/pom.xml b/jetty-jaas/pom.xml index b4bf6c82e69..6662377bb20 100644 --- a/jetty-jaas/pom.xml +++ b/jetty-jaas/pom.xml @@ -1,5 +1,4 @@ - + org.eclipse.jetty jetty-project diff --git a/jetty-jaas/src/main/java/org/eclipse/jetty/jaas/JAASLoginService.java b/jetty-jaas/src/main/java/org/eclipse/jetty/jaas/JAASLoginService.java index 90cf053cfc7..60676da4f9b 100644 --- a/jetty-jaas/src/main/java/org/eclipse/jetty/jaas/JAASLoginService.java +++ b/jetty-jaas/src/main/java/org/eclipse/jetty/jaas/JAASLoginService.java @@ -24,7 +24,6 @@ import java.util.Arrays; import java.util.Collection; import java.util.LinkedHashSet; import java.util.Set; - import javax.security.auth.Subject; import javax.security.auth.callback.Callback; import javax.security.auth.callback.CallbackHandler; @@ -37,10 +36,10 @@ import javax.security.auth.login.LoginContext; import javax.security.auth.login.LoginException; import javax.servlet.ServletRequest; -import org.eclipse.jetty.jaas.callback.ServletRequestCallback; import org.eclipse.jetty.jaas.callback.DefaultCallbackHandler; import org.eclipse.jetty.jaas.callback.ObjectCallback; import org.eclipse.jetty.jaas.callback.RequestParameterCallback; +import org.eclipse.jetty.jaas.callback.ServletRequestCallback; import org.eclipse.jetty.security.DefaultIdentityService; import org.eclipse.jetty.security.IdentityService; import org.eclipse.jetty.security.LoginService; @@ -52,14 +51,12 @@ import org.eclipse.jetty.util.component.AbstractLifeCycle; import org.eclipse.jetty.util.log.Log; import org.eclipse.jetty.util.log.Logger; - -/** +/** * JAASLoginService * * * Implementation of jetty's LoginService that works with JAAS for * authorization and authentication. - * */ public class JAASLoginService extends AbstractLifeCycle implements LoginService { @@ -76,16 +73,11 @@ public class JAASLoginService extends AbstractLifeCycle implements LoginService protected IdentityService _identityService; protected Configuration _configuration; - - public JAASLoginService() { } - - /** - * * @param name the name of the realm */ public JAASLoginService(String name) @@ -95,8 +87,6 @@ public class JAASLoginService extends AbstractLifeCycle implements LoginService _loginModuleName = name; } - - /** * Get the name of the realm. * @@ -108,19 +98,16 @@ public class JAASLoginService extends AbstractLifeCycle implements LoginService return _realmName; } - - /** * Set the name of the realm * * @param name a String value */ - public void setName (String name) + public void setName(String name) { _realmName = name; } - /** * @return the configuration */ @@ -129,8 +116,6 @@ public class JAASLoginService extends AbstractLifeCycle implements LoginService return _configuration; } - - /** * @param configuration the configuration to set */ @@ -139,10 +124,9 @@ public class JAASLoginService extends AbstractLifeCycle implements LoginService _configuration = configuration; } - - - /** + /** * Get the identityService. + * * @return the identityService */ @Override @@ -151,9 +135,9 @@ public class JAASLoginService extends AbstractLifeCycle implements LoginService return _identityService; } - - /** + /** * Set the identityService. + * * @param identityService the identityService to set */ @Override @@ -162,55 +146,48 @@ public class JAASLoginService extends AbstractLifeCycle implements LoginService _identityService = identityService; } - /** * Set the name to use to index into the config * file of LoginModules. * * @param name a String value */ - public void setLoginModuleName (String name) + public void setLoginModuleName(String name) { _loginModuleName = name; } - - public void setCallbackHandlerClass (String classname) + public void setCallbackHandlerClass(String classname) { _callbackHandlerClass = classname; } - - public void setRoleClassNames (String[] classnames) + public void setRoleClassNames(String[] classnames) { if (classnames == null || classnames.length == 0) { _roleClassNames = DEFAULT_ROLE_CLASS_NAMES; return; } - + _roleClassNames = ArrayUtil.addToArray(classnames, DEFAULT_ROLE_CLASS_NAME, String.class); } - public String[] getRoleClassNames() { return _roleClassNames; } - - @Override protected void doStart() throws Exception { - if (_identityService==null) + if (_identityService == null) _identityService = new DefaultIdentityService(); super.doStart(); } - @Override - public UserIdentity login(final String username,final Object credentials, final ServletRequest request) + public UserIdentity login(final String username, final Object credentials, final ServletRequest request) { try { @@ -222,7 +199,7 @@ public class JAASLoginService extends AbstractLifeCycle implements LoginService @Override public void handle(Callback[] callbacks) throws IOException, UnsupportedCallbackException { - for (Callback callback: callbacks) + for (Callback callback : callbacks) { if (callback instanceof NameCallback) { @@ -239,7 +216,7 @@ public class JAASLoginService extends AbstractLifeCycle implements LoginService else if (callback instanceof RequestParameterCallback) { RequestParameterCallback rpc = (RequestParameterCallback)callback; - if (request!=null) + if (request != null) rpc.setParameterValues(Arrays.asList(request.getParameterValues(rpc.getParameterName()))); } else if (callback instanceof ServletRequestCallback) @@ -259,17 +236,17 @@ public class JAASLoginService extends AbstractLifeCycle implements LoginService if (DefaultCallbackHandler.class.isAssignableFrom(clazz)) { DefaultCallbackHandler dch = (DefaultCallbackHandler)callbackHandler; - if (request instanceof Request) + if (request instanceof Request) dch.setRequest((Request)request); dch.setCredential(credentials); dch.setUserName(username); } } - + //set up the login context Subject subject = new Subject(); - LoginContext loginContext = (_configuration==null?new LoginContext(_loginModuleName, subject, callbackHandler) - :new LoginContext(_loginModuleName, subject, callbackHandler, _configuration)); + LoginContext loginContext = (_configuration == null ? new LoginContext(_loginModuleName, subject, callbackHandler) + : new LoginContext(_loginModuleName, subject, callbackHandler, _configuration)); loginContext.login(); @@ -277,7 +254,7 @@ public class JAASLoginService extends AbstractLifeCycle implements LoginService JAASUserPrincipal userPrincipal = new JAASUserPrincipal(getUserName(callbackHandler), subject, loginContext); subject.getPrincipals().add(userPrincipal); - return _identityService.newUserIdentity(subject,userPrincipal,getGroups(subject)); + return _identityService.newUserIdentity(subject, userPrincipal, getGroups(subject)); } catch (FailedLoginException e) { @@ -291,7 +268,6 @@ public class JAASLoginService extends AbstractLifeCycle implements LoginService return null; } - @Override public boolean validate(UserIdentity user) { @@ -299,15 +275,13 @@ public class JAASLoginService extends AbstractLifeCycle implements LoginService return true; } - private String getUserName(CallbackHandler callbackHandler) throws IOException, UnsupportedCallbackException { NameCallback nameCallback = new NameCallback("foo"); - callbackHandler.handle(new Callback[] {nameCallback}); + callbackHandler.handle(new Callback[]{nameCallback}); return nameCallback.getName(); } - @Override public void logout(UserIdentity user) { @@ -323,31 +297,29 @@ public class JAASLoginService extends AbstractLifeCycle implements LoginService } } - /** * Get all of the groups for the user. - * + * * @param subject the Subject representing the user - * * @return all the names of groups that the user is in, or 0 length array if none */ - protected String[] getGroups (Subject subject) + protected String[] getGroups(Subject subject) { Collection groups = new LinkedHashSet<>(); Set principals = subject.getPrincipals(); for (Principal principal : principals) { Class c = principal.getClass(); - while (c!=null) + while (c != null) { if (roleClassNameMatches(c.getName())) { groups.add(principal.getName()); break; } - + boolean added = false; - for (Class ci:c.getInterfaces()) + for (Class ci : c.getInterfaces()) { if (roleClassNameMatches(ci.getName())) { @@ -356,7 +328,7 @@ public class JAASLoginService extends AbstractLifeCycle implements LoginService break; } } - + if (!added) { c = c.getSuperclass(); @@ -368,12 +340,11 @@ public class JAASLoginService extends AbstractLifeCycle implements LoginService return groups.toArray(new String[groups.size()]); } - - - private boolean roleClassNameMatches (String classname) + + private boolean roleClassNameMatches(String classname) { boolean result = false; - for (String roleClassName:getRoleClassNames()) + for (String roleClassName : getRoleClassNames()) { if (roleClassName.equals(classname)) { @@ -383,5 +354,4 @@ public class JAASLoginService extends AbstractLifeCycle implements LoginService } return result; } - } diff --git a/jetty-jaas/src/main/java/org/eclipse/jetty/jaas/JAASPrincipal.java b/jetty-jaas/src/main/java/org/eclipse/jetty/jaas/JAASPrincipal.java index 0566764292b..8fc5fdcc60f 100644 --- a/jetty-jaas/src/main/java/org/eclipse/jetty/jaas/JAASPrincipal.java +++ b/jetty-jaas/src/main/java/org/eclipse/jetty/jaas/JAASPrincipal.java @@ -21,7 +21,7 @@ package org.eclipse.jetty.jaas; import java.io.Serializable; import java.security.Principal; -/** +/** * JAASPrincipal *

    * Impl class of Principal interface. @@ -29,37 +29,37 @@ import java.security.Principal; public class JAASPrincipal implements Principal, Serializable { private static final long serialVersionUID = -5538962177019315479L; - + private final String _name; - + public JAASPrincipal(String userName) { this._name = userName; } @Override - public boolean equals (Object p) + public boolean equals(Object p) { - if (! (p instanceof JAASPrincipal)) + if (!(p instanceof JAASPrincipal)) return false; return getName().equals(((JAASPrincipal)p).getName()); } @Override - public int hashCode () + public int hashCode() { return getName().hashCode(); } @Override - public String getName () + public String getName() { return this._name; } @Override - public String toString () + public String toString() { return getName(); } diff --git a/jetty-jaas/src/main/java/org/eclipse/jetty/jaas/JAASRole.java b/jetty-jaas/src/main/java/org/eclipse/jetty/jaas/JAASRole.java index f9c3ddcfa09..dddcf622ff2 100644 --- a/jetty-jaas/src/main/java/org/eclipse/jetty/jaas/JAASRole.java +++ b/jetty-jaas/src/main/java/org/eclipse/jetty/jaas/JAASRole.java @@ -24,13 +24,13 @@ public class JAASRole extends JAASPrincipal public JAASRole(String name) { - super (name); + super(name); } @Override - public boolean equals (Object o) + public boolean equals(Object o) { - if (! (o instanceof JAASRole)) + if (!(o instanceof JAASRole)) return false; return getName().equals(((JAASRole)o).getName()); diff --git a/jetty-jaas/src/main/java/org/eclipse/jetty/jaas/JAASUserPrincipal.java b/jetty-jaas/src/main/java/org/eclipse/jetty/jaas/JAASUserPrincipal.java index dba128eea8f..7106edd0239 100644 --- a/jetty-jaas/src/main/java/org/eclipse/jetty/jaas/JAASUserPrincipal.java +++ b/jetty-jaas/src/main/java/org/eclipse/jetty/jaas/JAASUserPrincipal.java @@ -19,15 +19,14 @@ package org.eclipse.jetty.jaas; import java.security.Principal; - import javax.security.auth.Subject; import javax.security.auth.login.LoginContext; -/** +/** * JAASUserPrincipal *

    * Implements the JAAS version of the - * org.eclipse.jetty.http.UserPrincipal interface. + * org.eclipse.jetty.http.UserPrincipal interface. */ public class JAASUserPrincipal implements Principal { @@ -35,7 +34,6 @@ public class JAASUserPrincipal implements Principal private final Subject _subject; private final LoginContext _loginContext; - /* ------------------------------------------------ */ public JAASUserPrincipal(String name, Subject subject, LoginContext loginContext) { this._name = name; @@ -43,26 +41,26 @@ public class JAASUserPrincipal implements Principal this._loginContext = loginContext; } - /* ------------------------------------------------ */ - /** Get the name identifying the user + /** + * Get the name identifying the user */ @Override - public String getName () + public String getName() { return _name; } - - /* ------------------------------------------------ */ - /** Provide access to the Subject + /** + * Provide access to the Subject + * * @return subject */ - public Subject getSubject () + public Subject getSubject() { return this._subject; } - LoginContext getLoginContext () + LoginContext getLoginContext() { return this._loginContext; } @@ -72,5 +70,4 @@ public class JAASUserPrincipal implements Principal { return getName(); } - } diff --git a/jetty-jaas/src/main/java/org/eclipse/jetty/jaas/callback/AbstractCallbackHandler.java b/jetty-jaas/src/main/java/org/eclipse/jetty/jaas/callback/AbstractCallbackHandler.java index f27a6789f63..108698b32df 100644 --- a/jetty-jaas/src/main/java/org/eclipse/jetty/jaas/callback/AbstractCallbackHandler.java +++ b/jetty-jaas/src/main/java/org/eclipse/jetty/jaas/callback/AbstractCallbackHandler.java @@ -19,43 +19,38 @@ package org.eclipse.jetty.jaas.callback; import java.io.IOException; - import javax.security.auth.callback.Callback; import javax.security.auth.callback.CallbackHandler; import javax.security.auth.callback.UnsupportedCallbackException; - public abstract class AbstractCallbackHandler implements CallbackHandler { protected String _userName; protected Object _credential; - public void setUserName (String userName) + public void setUserName(String userName) { _userName = userName; } - public String getUserName () + public String getUserName() { return _userName; } - - public void setCredential (Object credential) + public void setCredential(Object credential) { _credential = credential; } - public Object getCredential () + public Object getCredential() { return _credential; } @Override - public void handle (Callback[] callbacks) + public void handle(Callback[] callbacks) throws IOException, UnsupportedCallbackException { } - - } diff --git a/jetty-jaas/src/main/java/org/eclipse/jetty/jaas/callback/DefaultCallbackHandler.java b/jetty-jaas/src/main/java/org/eclipse/jetty/jaas/callback/DefaultCallbackHandler.java index efec20209ec..8739b5cc4a1 100644 --- a/jetty-jaas/src/main/java/org/eclipse/jetty/jaas/callback/DefaultCallbackHandler.java +++ b/jetty-jaas/src/main/java/org/eclipse/jetty/jaas/callback/DefaultCallbackHandler.java @@ -20,7 +20,6 @@ package org.eclipse.jetty.jaas.callback; import java.io.IOException; import java.util.Arrays; - import javax.security.auth.callback.Callback; import javax.security.auth.callback.NameCallback; import javax.security.auth.callback.PasswordCallback; @@ -29,9 +28,9 @@ import javax.security.auth.callback.UnsupportedCallbackException; import org.eclipse.jetty.server.Request; import org.eclipse.jetty.util.security.Password; -/** +/** * DefaultCallbackHandler - * + * * An implementation of the JAAS CallbackHandler. Users can provide * their own implementation instead and set the name of its class on the JAASLoginService. */ @@ -39,16 +38,16 @@ public class DefaultCallbackHandler extends AbstractCallbackHandler { private Request _request; - public void setRequest (Request request) + public void setRequest(Request request) { _request = request; } @Override - public void handle (Callback[] callbacks) + public void handle(Callback[] callbacks) throws IOException, UnsupportedCallbackException { - for (int i=0; i < callbacks.length; i++) + for (int i = 0; i < callbacks.length; i++) { if (callbacks[i] instanceof NameCallback) { @@ -61,13 +60,13 @@ public class DefaultCallbackHandler extends AbstractCallbackHandler else if (callbacks[i] instanceof PasswordCallback) { if (getCredential() instanceof Password) - ((PasswordCallback)callbacks[i]).setPassword (((Password)getCredential()).toString().toCharArray()); + ((PasswordCallback)callbacks[i]).setPassword(((Password)getCredential()).toString().toCharArray()); else if (getCredential() instanceof String) { - ((PasswordCallback)callbacks[i]).setPassword (((String)getCredential()).toCharArray()); + ((PasswordCallback)callbacks[i]).setPassword(((String)getCredential()).toCharArray()); } else - throw new UnsupportedCallbackException (callbacks[i], "User supplied credentials cannot be converted to char[] for PasswordCallback: try using an ObjectCallback instead"); + throw new UnsupportedCallbackException(callbacks[i], "User supplied credentials cannot be converted to char[] for PasswordCallback: try using an ObjectCallback instead"); } else if (callbacks[i] instanceof RequestParameterCallback) { @@ -81,8 +80,6 @@ public class DefaultCallbackHandler extends AbstractCallbackHandler else throw new UnsupportedCallbackException(callbacks[i]); } - } - } diff --git a/jetty-jaas/src/main/java/org/eclipse/jetty/jaas/callback/ObjectCallback.java b/jetty-jaas/src/main/java/org/eclipse/jetty/jaas/callback/ObjectCallback.java index b0d1d1083a8..80704993b1f 100644 --- a/jetty-jaas/src/main/java/org/eclipse/jetty/jaas/callback/ObjectCallback.java +++ b/jetty-jaas/src/main/java/org/eclipse/jetty/jaas/callback/ObjectCallback.java @@ -20,7 +20,7 @@ package org.eclipse.jetty.jaas.callback; import javax.security.auth.callback.Callback; -/** +/** * ObjectCallback *

    * Can be used as a LoginModule Callback to @@ -31,18 +31,18 @@ import javax.security.auth.callback.Callback; public class ObjectCallback implements Callback { protected Object _object; - + public void setObject(Object o) { _object = o; } - public Object getObject () + public Object getObject() { return _object; } - public void clearObject () + public void clearObject() { _object = null; } diff --git a/jetty-jaas/src/main/java/org/eclipse/jetty/jaas/callback/RequestParameterCallback.java b/jetty-jaas/src/main/java/org/eclipse/jetty/jaas/callback/RequestParameterCallback.java index 14a2f3b6a85..ab2afd77e80 100644 --- a/jetty-jaas/src/main/java/org/eclipse/jetty/jaas/callback/RequestParameterCallback.java +++ b/jetty-jaas/src/main/java/org/eclipse/jetty/jaas/callback/RequestParameterCallback.java @@ -19,7 +19,6 @@ package org.eclipse.jetty.jaas.callback; import java.util.List; - import javax.security.auth.callback.Callback; /** @@ -34,21 +33,22 @@ public class RequestParameterCallback implements Callback private String _paramName; private List _paramValues; - public void setParameterName (String name) + public void setParameterName(String name) { _paramName = name; } - public String getParameterName () + + public String getParameterName() { return _paramName; } - public void setParameterValues (List values) + public void setParameterValues(List values) { _paramValues = values; } - public List getParameterValues () + public List getParameterValues() { return _paramValues; } diff --git a/jetty-jaas/src/main/java/org/eclipse/jetty/jaas/callback/ServletRequestCallback.java b/jetty-jaas/src/main/java/org/eclipse/jetty/jaas/callback/ServletRequestCallback.java index 70f3e6c51c1..bfec2f2126c 100644 --- a/jetty-jaas/src/main/java/org/eclipse/jetty/jaas/callback/ServletRequestCallback.java +++ b/jetty-jaas/src/main/java/org/eclipse/jetty/jaas/callback/ServletRequestCallback.java @@ -16,13 +16,11 @@ // ======================================================================== // - package org.eclipse.jetty.jaas.callback; import javax.security.auth.callback.Callback; import javax.servlet.ServletRequest; - /** * ServletRequestCallback * @@ -31,13 +29,13 @@ import javax.servlet.ServletRequest; public class ServletRequestCallback implements Callback { protected ServletRequest _request; - - public void setRequest (ServletRequest request) + + public void setRequest(ServletRequest request) { _request = request; } - - public ServletRequest getRequest () + + public ServletRequest getRequest() { return _request; } diff --git a/jetty-jaas/src/main/java/org/eclipse/jetty/jaas/spi/AbstractDatabaseLoginModule.java b/jetty-jaas/src/main/java/org/eclipse/jetty/jaas/spi/AbstractDatabaseLoginModule.java index bd61640eb0f..ba6cd500b1c 100644 --- a/jetty-jaas/src/main/java/org/eclipse/jetty/jaas/spi/AbstractDatabaseLoginModule.java +++ b/jetty-jaas/src/main/java/org/eclipse/jetty/jaas/spi/AbstractDatabaseLoginModule.java @@ -24,7 +24,6 @@ import java.sql.ResultSet; import java.util.ArrayList; import java.util.List; import java.util.Map; - import javax.security.auth.Subject; import javax.security.auth.callback.CallbackHandler; @@ -38,7 +37,6 @@ import org.eclipse.jetty.util.security.Credential; * Abstract base class for LoginModules that interact with a * database to retrieve authentication and authorization information. * Used by the JDBCLoginModule and DataSourceLoginModule. - * */ public abstract class AbstractDatabaseLoginModule extends AbstractLoginModule { @@ -57,35 +55,31 @@ public abstract class AbstractDatabaseLoginModule extends AbstractLoginModule * @return a java.sql.Connection from the database * @throws Exception if unable to get the connection */ - public abstract Connection getConnection () throws Exception; - - + public abstract Connection getConnection() throws Exception; + public class JDBCUserInfo extends UserInfo { - public JDBCUserInfo (String userName, Credential credential) + public JDBCUserInfo(String userName, Credential credential) { super(userName, credential); } - - - + @Override - public List doFetchRoles () - throws Exception + public List doFetchRoles() + throws Exception { - return getRoles(getUserName()); + return getRoles(getUserName()); } } - - - /* ------------------------------------------------ */ - /** Load info from database + /** + * Load info from database + * * @param userName user info to load - * @exception Exception if unable to get the user info + * @throws Exception if unable to get the user info */ @Override - public UserInfo getUserInfo (String userName) + public UserInfo getUserInfo(String userName) throws Exception { try (Connection connection = getConnection()) @@ -93,9 +87,9 @@ public abstract class AbstractDatabaseLoginModule extends AbstractLoginModule //query for credential String dbCredential = null; - try (PreparedStatement statement = connection.prepareStatement (userQuery)) + try (PreparedStatement statement = connection.prepareStatement(userQuery)) { - statement.setString (1, userName); + statement.setString(1, userName); try (ResultSet results = statement.executeQuery()) { if (results.next()) @@ -105,53 +99,46 @@ public abstract class AbstractDatabaseLoginModule extends AbstractLoginModule } } - if (dbCredential==null) + if (dbCredential == null) { return null; } - - - return new JDBCUserInfo (userName, Credential.getCredential(dbCredential)); + return new JDBCUserInfo(userName, Credential.getCredential(dbCredential)); } } - - - public List getRoles (String userName) - throws Exception + + public List getRoles(String userName) + throws Exception { List roles = new ArrayList(); - + try (Connection connection = getConnection()) { //query for role names - try (PreparedStatement statement = connection.prepareStatement (rolesQuery)) + try (PreparedStatement statement = connection.prepareStatement(rolesQuery)) { - statement.setString (1, userName); + statement.setString(1, userName); try (ResultSet results = statement.executeQuery()) { while (results.next()) { - String roleName = results.getString (1); - roles.add (roleName); + String roleName = results.getString(1); + roles.add(roleName); } } } - } return roles; } - - - @Override public void initialize(Subject subject, - CallbackHandler callbackHandler, - Map sharedState, - Map options) + CallbackHandler callbackHandler, + Map sharedState, + Map options) { super.initialize(subject, callbackHandler, sharedState, options); @@ -160,17 +147,18 @@ public abstract class AbstractDatabaseLoginModule extends AbstractLoginModule dbUserTableUserField = (String)options.get("userField"); dbUserTableCredentialField = (String)options.get("credentialField"); - userQuery = "select "+dbUserTableCredentialField+" from "+dbUserTable+" where "+dbUserTableUserField+"=?"; - + userQuery = "select " + dbUserTableCredentialField + " from " + dbUserTable + " where " + dbUserTableUserField + "=?"; //get the user roles query out of the options dbUserRoleTable = (String)options.get("userRoleTable"); dbUserRoleTableUserField = (String)options.get("userRoleUserField"); dbUserRoleTableRoleField = (String)options.get("userRoleRoleField"); - rolesQuery = "select "+dbUserRoleTableRoleField+" from "+dbUserRoleTable+" where "+dbUserRoleTableUserField+"=?"; + rolesQuery = "select " + dbUserRoleTableRoleField + " from " + dbUserRoleTable + " where " + dbUserRoleTableUserField + "=?"; - if(LOG.isDebugEnabled())LOG.debug("userQuery = "+userQuery); - if(LOG.isDebugEnabled())LOG.debug("rolesQuery = "+rolesQuery); + if (LOG.isDebugEnabled()) + LOG.debug("userQuery = " + userQuery); + if (LOG.isDebugEnabled()) + LOG.debug("rolesQuery = " + rolesQuery); } } diff --git a/jetty-jaas/src/main/java/org/eclipse/jetty/jaas/spi/AbstractLoginModule.java b/jetty-jaas/src/main/java/org/eclipse/jetty/jaas/spi/AbstractLoginModule.java index 94f1678dfeb..f428515238e 100644 --- a/jetty-jaas/src/main/java/org/eclipse/jetty/jaas/spi/AbstractLoginModule.java +++ b/jetty-jaas/src/main/java/org/eclipse/jetty/jaas/spi/AbstractLoginModule.java @@ -24,7 +24,6 @@ import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.Map; - import javax.security.auth.Subject; import javax.security.auth.callback.Callback; import javax.security.auth.callback.CallbackHandler; @@ -66,13 +65,13 @@ public abstract class AbstractLoginModule implements LoginModule private Principal principal; private List roles; - public JAASUserInfo (UserInfo u) + public JAASUserInfo(UserInfo u) { this.user = u; this.principal = new JAASPrincipal(u.getUserName()); } - public String getUserName () + public String getUserName() { return this.user.getUserName(); } @@ -82,30 +81,31 @@ public abstract class AbstractLoginModule implements LoginModule return this.principal; } - - public void setJAASInfo (Subject subject) + public void setJAASInfo(Subject subject) { subject.getPrincipals().add(this.principal); - if (this.user.getCredential() != null) { + if (this.user.getCredential() != null) + { subject.getPrivateCredentials().add(this.user.getCredential()); } subject.getPrincipals().addAll(roles); } - public void unsetJAASInfo (Subject subject) + public void unsetJAASInfo(Subject subject) { subject.getPrincipals().remove(this.principal); - if (this.user.getCredential() != null) { + if (this.user.getCredential() != null) + { subject.getPrivateCredentials().remove(this.user.getCredential()); } subject.getPrincipals().removeAll(this.roles); } - public boolean checkCredential (Object suppliedCredential) + public boolean checkCredential(Object suppliedCredential) { return this.user.checkCredential(suppliedCredential); } - + public void fetchRoles() throws Exception { this.user.fetchRoles(); @@ -114,23 +114,21 @@ public abstract class AbstractLoginModule implements LoginModule { Iterator itor = this.user.getRoleNames().iterator(); while (itor.hasNext()) + { this.roles.add(new JAASRole((String)itor.next())); + } } } } - - - public abstract UserInfo getUserInfo (String username) throws Exception; - - - - public Subject getSubject () + public abstract UserInfo getUserInfo(String username) throws Exception; + + public Subject getSubject() { return this.subject; } - public void setSubject (Subject s) + public void setSubject(Subject s) { this.subject = s; } @@ -140,7 +138,7 @@ public abstract class AbstractLoginModule implements LoginModule return this.currentUser; } - public void setCurrentUser (JAASUserInfo u) + public void setCurrentUser(JAASUserInfo u) { this.currentUser = u; } @@ -160,23 +158,24 @@ public abstract class AbstractLoginModule implements LoginModule return this.authState; } - public boolean isCommitted () + public boolean isCommitted() { return this.commitState; } - public void setAuthenticated (boolean authState) + public void setAuthenticated(boolean authState) { this.authState = authState; } - public void setCommitted (boolean commitState) + public void setCommitted(boolean commitState) { this.commitState = commitState; } + /** - * @see javax.security.auth.spi.LoginModule#abort() * @throws LoginException if unable to abort + * @see javax.security.auth.spi.LoginModule#abort() */ @Override public boolean abort() throws LoginException @@ -186,9 +185,9 @@ public abstract class AbstractLoginModule implements LoginModule } /** - * @see javax.security.auth.spi.LoginModule#commit() * @return true if committed, false if not (likely not authenticated) * @throws LoginException if unable to commit + * @see javax.security.auth.spi.LoginModule#commit() */ @Override public boolean commit() throws LoginException @@ -205,8 +204,7 @@ public abstract class AbstractLoginModule implements LoginModule return true; } - - public Callback[] configureCallbacks () + public Callback[] configureCallbacks() { Callback[] callbacks = new Callback[3]; callbacks[0] = new NameCallback("Enter user name"); @@ -214,31 +212,27 @@ public abstract class AbstractLoginModule implements LoginModule callbacks[2] = new PasswordCallback("Enter password", false); //only used if framework does not support the ObjectCallback return callbacks; } - - - public boolean isIgnored () + + public boolean isIgnored() { return false; } - - - /** - * @see javax.security.auth.spi.LoginModule#login() * @return true if is authenticated, false otherwise * @throws LoginException if unable to login + * @see javax.security.auth.spi.LoginModule#login() */ @Override public boolean login() throws LoginException { try - { + { if (isIgnored()) return false; - + if (callbackHandler == null) - throw new LoginException ("No callback handler"); + throw new LoginException("No callback handler"); Callback[] callbacks = configureCallbacks(); callbackHandler.handle(callbacks); @@ -266,7 +260,7 @@ public abstract class AbstractLoginModule implements LoginModule currentUser = new JAASUserInfo(userInfo); setAuthenticated(currentUser.checkCredential(webCredential)); - + if (isAuthenticated()) { currentUser.fetchRoles(); @@ -277,24 +271,24 @@ public abstract class AbstractLoginModule implements LoginModule } catch (IOException e) { - throw new LoginException (e.toString()); + throw new LoginException(e.toString()); } catch (UnsupportedCallbackException e) { - throw new LoginException (e.toString()); + throw new LoginException(e.toString()); } catch (Exception e) { if (e instanceof LoginException) throw (LoginException)e; - throw new LoginException (e.toString()); + throw new LoginException(e.toString()); } } /** - * @see javax.security.auth.spi.LoginModule#logout() * @return true always * @throws LoginException if unable to logout + * @see javax.security.auth.spi.LoginModule#logout() */ @Override public boolean logout() throws LoginException @@ -305,18 +299,17 @@ public abstract class AbstractLoginModule implements LoginModule } /** - * @see javax.security.auth.spi.LoginModule#initialize(javax.security.auth.Subject, javax.security.auth.callback.CallbackHandler, java.util.Map, java.util.Map) * @param subject the subject * @param callbackHandler the callback handler * @param sharedState the shared state map * @param options the option map + * @see javax.security.auth.spi.LoginModule#initialize(javax.security.auth.Subject, javax.security.auth.callback.CallbackHandler, java.util.Map, java.util.Map) */ @Override public void initialize(Subject subject, CallbackHandler callbackHandler, - Map sharedState, Map options) + Map sharedState, Map options) { this.callbackHandler = callbackHandler; this.subject = subject; } - } diff --git a/jetty-jaas/src/main/java/org/eclipse/jetty/jaas/spi/DataSourceLoginModule.java b/jetty-jaas/src/main/java/org/eclipse/jetty/jaas/spi/DataSourceLoginModule.java index 7e1eef2d86b..1ba08cd580d 100644 --- a/jetty-jaas/src/main/java/org/eclipse/jetty/jaas/spi/DataSourceLoginModule.java +++ b/jetty-jaas/src/main/java/org/eclipse/jetty/jaas/spi/DataSourceLoginModule.java @@ -20,7 +20,6 @@ package org.eclipse.jetty.jaas.spi; import java.sql.Connection; import java.util.Map; - import javax.naming.InitialContext; import javax.naming.NamingException; import javax.security.auth.Subject; @@ -41,12 +40,11 @@ public class DataSourceLoginModule extends AbstractDatabaseLoginModule private String dbJNDIName; private DataSource dataSource; - /* ------------------------------------------------ */ - /** + /** * Init LoginModule. *

    * Called once by JAAS after new instance created. - * + * * @param subject the subject * @param callbackHandler the callback handler * @param sharedState the shared state map @@ -55,8 +53,8 @@ public class DataSourceLoginModule extends AbstractDatabaseLoginModule @Override public void initialize(Subject subject, CallbackHandler callbackHandler, - Map sharedState, - Map options) + Map sharedState, + Map options) { try { @@ -66,23 +64,24 @@ public class DataSourceLoginModule extends AbstractDatabaseLoginModule dbJNDIName = (String)options.get("dbJNDIName"); InitialContext ic = new InitialContext(); - dataSource = (DataSource)ic.lookup("java:comp/env/"+dbJNDIName); + dataSource = (DataSource)ic.lookup("java:comp/env/" + dbJNDIName); } catch (NamingException e) { - throw new IllegalStateException (e.toString()); + throw new IllegalStateException(e.toString()); } } /** * Get a connection from the DataSource - * @see AbstractDatabaseLoginModule#getConnection() + * * @return the connection for the datasource * @throws Exception if unable to get the connection + * @see AbstractDatabaseLoginModule#getConnection() */ @Override - public Connection getConnection () - throws Exception + public Connection getConnection() + throws Exception { return dataSource.getConnection(); } diff --git a/jetty-jaas/src/main/java/org/eclipse/jetty/jaas/spi/JDBCLoginModule.java b/jetty-jaas/src/main/java/org/eclipse/jetty/jaas/spi/JDBCLoginModule.java index 773fe859fa5..571e3cad6c2 100644 --- a/jetty-jaas/src/main/java/org/eclipse/jetty/jaas/spi/JDBCLoginModule.java +++ b/jetty-jaas/src/main/java/org/eclipse/jetty/jaas/spi/JDBCLoginModule.java @@ -21,7 +21,6 @@ package org.eclipse.jetty.jaas.spi; import java.sql.Connection; import java.sql.DriverManager; import java.util.Map; - import javax.security.auth.Subject; import javax.security.auth.callback.CallbackHandler; @@ -29,7 +28,7 @@ import org.eclipse.jetty.util.Loader; import org.eclipse.jetty.util.log.Log; import org.eclipse.jetty.util.log.Logger; -/** +/** * JDBCLoginModule *

    * JAAS LoginModule to retrieve user information from @@ -49,34 +48,31 @@ public class JDBCLoginModule extends AbstractDatabaseLoginModule /** * Get a connection from the DriverManager - * @see AbstractDatabaseLoginModule#getConnection() + * * @return the connection for this datasource * @throws Exception if unable to get the connection + * @see AbstractDatabaseLoginModule#getConnection() */ @Override - public Connection getConnection () - throws Exception + public Connection getConnection() + throws Exception { - if (!((dbDriver != null) - && - (dbUrl != null))) - throw new IllegalStateException ("Database connection information not configured"); + if (!((dbDriver != null) && (dbUrl != null))) + throw new IllegalStateException("Database connection information not configured"); - if(LOG.isDebugEnabled())LOG.debug("Connecting using dbDriver="+dbDriver+"+ dbUserName="+dbUserName+", dbPassword="+dbUrl); + if (LOG.isDebugEnabled()) + LOG.debug("Connecting using dbDriver=" + dbDriver + "+ dbUserName=" + dbUserName + ", dbPassword=" + dbUrl); - return DriverManager.getConnection (dbUrl, - dbUserName, - dbPassword); + return DriverManager.getConnection(dbUrl, + dbUserName, + dbPassword); } - - - /* ------------------------------------------------ */ - /** + /** * Init LoginModule. *

    * Called once by JAAS after new instance created. - * + * * @param subject the subject * @param callbackHandler the callback handler * @param sharedState the shared state map @@ -85,8 +81,8 @@ public class JDBCLoginModule extends AbstractDatabaseLoginModule @Override public void initialize(Subject subject, CallbackHandler callbackHandler, - Map sharedState, - Map options) + Map sharedState, + Map options) { try { @@ -109,7 +105,7 @@ public class JDBCLoginModule extends AbstractDatabaseLoginModule } catch (Exception e) { - throw new IllegalStateException (e.toString()); + throw new IllegalStateException(e.toString()); } } } diff --git a/jetty-jaas/src/main/java/org/eclipse/jetty/jaas/spi/LdapLoginModule.java b/jetty-jaas/src/main/java/org/eclipse/jetty/jaas/spi/LdapLoginModule.java index 21dd9012461..6a7e936acca 100644 --- a/jetty-jaas/src/main/java/org/eclipse/jetty/jaas/spi/LdapLoginModule.java +++ b/jetty-jaas/src/main/java/org/eclipse/jetty/jaas/spi/LdapLoginModule.java @@ -179,7 +179,6 @@ public class LdapLoginModule extends AbstractLoginModule private DirContext _rootContext; - public class LDAPUserInfo extends UserInfo { Attributes attributes; @@ -200,10 +199,8 @@ public class LdapLoginModule extends AbstractLoginModule { return getUserRoles(_rootContext, getUserName(), attributes); } - } - /** * get the available information about the user *

    @@ -268,9 +265,7 @@ public class LdapLoginModule extends AbstractLoginModule *

    * NOTE: this is not an user authenticated operation * - * @param username * @return the {@link Attributes} from the user - * @throws LoginException */ private Attributes getUserAttributes(String username) throws LoginException { @@ -298,7 +293,8 @@ public class LdapLoginModule extends AbstractLoginModule } } - if(LOG.isDebugEnabled()) LOG.debug("user cred is: " + ldapCredential); + if (LOG.isDebugEnabled()) + LOG.debug("user cred is: " + ldapCredential); return ldapCredential; } @@ -307,11 +303,6 @@ public class LdapLoginModule extends AbstractLoginModule * attempts to get the users roles from the root context *

    * NOTE: this is not an user authenticated operation - * - * @param dirContext - * @param username - * @return - * @throws LoginException */ private List getUserRoles(DirContext dirContext, String username, Attributes attributes) throws LoginException, NamingException { @@ -323,7 +314,7 @@ public class LdapLoginModule extends AbstractLoginModule { rdnValue = (String)attribute.get(); // switch to the value stored in the _userRdnAttribute if we can } - catch (NamingException e) + catch (NamingException ignored) { } } @@ -331,8 +322,8 @@ public class LdapLoginModule extends AbstractLoginModule String filter = "({0}={1})"; Object[] filterArguments = new Object[]{ - _userRdnAttribute, - rdnValue + _userRdnAttribute, + rdnValue }; SearchResult searchResult = findUser(dirContext, filter, filterArguments); @@ -358,7 +349,8 @@ public class LdapLoginModule extends AbstractLoginModule Object[] filterArguments = {_roleObjectClass, _roleMemberAttribute, userDn}; NamingEnumeration results = dirContext.search(_roleBaseDn, filter, filterArguments, ctls); - if(LOG.isDebugEnabled()) LOG.debug("Found user roles?: " + results.hasMoreElements()); + if (LOG.isDebugEnabled()) + LOG.debug("Found user roles?: " + results.hasMoreElements()); while (results.hasMoreElements()) { @@ -388,7 +380,6 @@ public class LdapLoginModule extends AbstractLoginModule return roleList; } - /** * since ldap uses a context bind for valid authentication checking, we override login() *

    @@ -460,15 +451,15 @@ public class LdapLoginModule extends AbstractLoginModule { if (_debug) { - LOG.info( e ); + LOG.info(e); } throw new LoginException("IO Error performing login."); } - catch ( AuthenticationException e ) + catch (AuthenticationException e) { if (_debug) { - LOG.info( e ); + LOG.info(e); } return false; } @@ -480,7 +471,7 @@ public class LdapLoginModule extends AbstractLoginModule { if (_debug) LOG.info(e); - throw new LoginException ("Error obtaining user info"); + throw new LoginException("Error obtaining user info"); } } @@ -506,7 +497,7 @@ public class LdapLoginModule extends AbstractLoginModule * @param username the user name * @param password the password * @return true always - * @throws LoginException if unable to bind the login + * @throws LoginException if unable to bind the login */ public boolean bindingLogin(String username, Object password) throws LoginException { @@ -547,7 +538,7 @@ public class LdapLoginModule extends AbstractLoginModule } catch (NamingException e) { - throw new FailedLoginException (e.getMessage()); + throw new FailedLoginException(e.getMessage()); } } @@ -559,9 +550,9 @@ public class LdapLoginModule extends AbstractLoginModule LOG.debug("Searching for user " + username + " with filter: \'" + filter + "\'" + " from base dn: " + _userBaseDn); Object[] filterArguments = new Object[]{ - _userObjectClass, - _userIdAttribute, - username + _userObjectClass, + _userIdAttribute, + username }; return findUser(_rootContext, filter, filterArguments); @@ -578,9 +569,9 @@ public class LdapLoginModule extends AbstractLoginModule { results = _rootContext.search(_userBaseDn, filter, filterArguments, ctls); } - catch (NamingException ne) + catch (NamingException ex) { - throw new FailedLoginException(ne.getMessage()); + throw new FailedLoginException(ex.getMessage()); } if (LOG.isDebugEnabled()) @@ -596,16 +587,15 @@ public class LdapLoginModule extends AbstractLoginModule return searchResult; } - /** * Init LoginModule. *

    * Called once by JAAS after new instance is created. * - * @param subject the subect + * @param subject the subect * @param callbackHandler the callback handler - * @param sharedState the shared state map - * @param options the option map + * @param sharedState the shared state map + * @param options the option map */ @Override public void initialize(Subject subject, diff --git a/jetty-jaas/src/main/java/org/eclipse/jetty/jaas/spi/PropertyFileLoginModule.java b/jetty-jaas/src/main/java/org/eclipse/jetty/jaas/spi/PropertyFileLoginModule.java index d865ee32ca2..bb99c620441 100644 --- a/jetty-jaas/src/main/java/org/eclipse/jetty/jaas/spi/PropertyFileLoginModule.java +++ b/jetty-jaas/src/main/java/org/eclipse/jetty/jaas/spi/PropertyFileLoginModule.java @@ -24,7 +24,6 @@ import java.util.List; import java.util.Map; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; - import javax.security.auth.Subject; import javax.security.auth.callback.CallbackHandler; @@ -48,23 +47,20 @@ public class PropertyFileLoginModule extends AbstractLoginModule private int _refreshInterval = 0; private String _filename = DEFAULT_FILENAME; - - /** * Read contents of the configured property file. * - * @see javax.security.auth.spi.LoginModule#initialize(javax.security.auth.Subject, javax.security.auth.callback.CallbackHandler, java.util.Map, - * java.util.Map) - * * @param subject the subject * @param callbackHandler the callback handler * @param sharedState the shared state map * @param options the options map + * @see javax.security.auth.spi.LoginModule#initialize(javax.security.auth.Subject, javax.security.auth.callback.CallbackHandler, java.util.Map, + * java.util.Map) */ @Override public void initialize(Subject subject, CallbackHandler callbackHandler, Map sharedState, Map options) { - super.initialize(subject,callbackHandler,sharedState,options); + super.initialize(subject, callbackHandler, sharedState, options); setupPropertyUserStore(options); } @@ -88,7 +84,7 @@ public class PropertyFileLoginModule extends AbstractLoginModule } catch (Exception e) { - LOG.warn("Exception while starting propertyUserStore: ",e); + LOG.warn("Exception while starting propertyUserStore: ", e); } } } @@ -97,14 +93,12 @@ public class PropertyFileLoginModule extends AbstractLoginModule private void parseConfig(Map options) { String tmp = (String)options.get("file"); - _filename = (tmp == null? DEFAULT_FILENAME : tmp); + _filename = (tmp == null ? DEFAULT_FILENAME : tmp); tmp = (String)options.get("refreshInterval"); - _refreshInterval = (tmp == null?_refreshInterval:Integer.parseInt(tmp)); + _refreshInterval = (tmp == null ? _refreshInterval : Integer.parseInt(tmp)); } /** - * - * * @param userName the user name * @throws Exception if unable to get the user information */ @@ -114,10 +108,10 @@ public class PropertyFileLoginModule extends AbstractLoginModule PropertyUserStore propertyUserStore = _propertyUserStores.get(_filename); if (propertyUserStore == null) throw new IllegalStateException("PropertyUserStore should never be null here!"); - - LOG.debug("Checking PropertyUserStore "+_filename+" for "+userName); + + LOG.debug("Checking PropertyUserStore " + _filename + " for " + userName); UserIdentity userIdentity = propertyUserStore.getUserIdentity(userName); - if (userIdentity==null) + if (userIdentity == null) return null; //TODO in future versions change the impl of PropertyUserStore so its not @@ -126,14 +120,13 @@ public class PropertyFileLoginModule extends AbstractLoginModule List roles = new ArrayList(); - for ( Principal principal : principals ) + for (Principal principal : principals) { - roles.add( principal.getName() ); + roles.add(principal.getName()); } Credential credential = (Credential)userIdentity.getSubject().getPrivateCredentials().iterator().next(); - LOG.debug("Found: " + userName + " in PropertyUserStore "+_filename); + LOG.debug("Found: " + userName + " in PropertyUserStore " + _filename); return new UserInfo(userName, credential, roles); } - } diff --git a/jetty-jaas/src/main/java/org/eclipse/jetty/jaas/spi/UserInfo.java b/jetty-jaas/src/main/java/org/eclipse/jetty/jaas/spi/UserInfo.java index 88e8c6aa69a..18866601d52 100644 --- a/jetty-jaas/src/main/java/org/eclipse/jetty/jaas/spi/UserInfo.java +++ b/jetty-jaas/src/main/java/org/eclipse/jetty/jaas/spi/UserInfo.java @@ -29,24 +29,23 @@ import org.eclipse.jetty.util.security.Credential; * * This is the information read from the external source * about a user. - * + * * Can be cached. */ public class UserInfo { - + private String _userName; private Credential _credential; protected List _roleNames = new ArrayList<>(); protected boolean _rolesLoaded = false; - - + /** * @param userName the user name * @param credential the credential * @param roleNames a {@link List} of role name */ - public UserInfo (String userName, Credential credential, List roleNames) + public UserInfo(String userName, Credential credential, List roleNames) { _userName = userName; _credential = credential; @@ -56,32 +55,29 @@ public class UserInfo _rolesLoaded = true; } } - - + /** * @param userName the user name * @param credential the credential */ - public UserInfo (String userName, Credential credential) + public UserInfo(String userName, Credential credential) { - this (userName, credential, null); + this(userName, credential, null); } - - - + /** * Should be overridden by subclasses to obtain * role info - * + * * @return List of role associated to the user * @throws Exception if the roles cannot be retrieved */ public List doFetchRoles() - throws Exception + throws Exception { return Collections.emptyList(); } - + public void fetchRoles() throws Exception { synchronized (_roleNames) @@ -93,25 +89,24 @@ public class UserInfo } } } - + public String getUserName() { return this._userName; } - - public List getRoleNames () - { + + public List getRoleNames() + { return Collections.unmodifiableList(_roleNames); } - - public boolean checkCredential (Object suppliedCredential) + + public boolean checkCredential(Object suppliedCredential) { return _credential.check(suppliedCredential); } - - protected Credential getCredential () + + protected Credential getCredential() { return _credential; } - } diff --git a/jetty-jaas/src/test/java/org/eclipse/jetty/jaas/JAASLdapLoginServiceTest.java b/jetty-jaas/src/test/java/org/eclipse/jetty/jaas/JAASLdapLoginServiceTest.java index c78be1082b2..fd77a0398fe 100644 --- a/jetty-jaas/src/test/java/org/eclipse/jetty/jaas/JAASLdapLoginServiceTest.java +++ b/jetty-jaas/src/test/java/org/eclipse/jetty/jaas/JAASLdapLoginServiceTest.java @@ -16,9 +16,14 @@ // ======================================================================== // - package org.eclipse.jetty.jaas; +import java.util.HashMap; +import java.util.Map; +import javax.security.auth.login.AppConfigurationEntry; +import javax.security.auth.login.AppConfigurationEntry.LoginModuleControlFlag; +import javax.security.auth.login.Configuration; + import org.apache.directory.server.annotations.CreateLdapServer; import org.apache.directory.server.annotations.CreateTransport; import org.apache.directory.server.core.annotations.ApplyLdifs; @@ -33,24 +38,20 @@ import org.eclipse.jetty.server.UserIdentity; import org.junit.Test; import org.junit.runner.RunWith; -import javax.security.auth.login.AppConfigurationEntry; -import javax.security.auth.login.AppConfigurationEntry.LoginModuleControlFlag; -import javax.security.auth.login.Configuration; -import java.util.HashMap; -import java.util.Map; - -import static org.junit.Assert.*; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertTrue; /** * JAASLdapLoginServiceTest - * - * */ -@RunWith( FrameworkRunner.class) -@CreateLdapServer( transports = { @CreateTransport(protocol = "LDAP" ) } ) +@RunWith(FrameworkRunner.class) +@CreateLdapServer(transports = {@CreateTransport(protocol = "LDAP")}) @CreateDS(allowAnonAccess = false, partitions = { @CreatePartition(name = "Users Partition", suffix = "ou=people,dc=jetty,dc=org"), - @CreatePartition(name = "Groups Partition", suffix = "ou=groups,dc=jetty,dc=org")}) + @CreatePartition(name = "Groups Partition", suffix = "ou=groups,dc=jetty,dc=org") +}) @ApplyLdifs({ // Entry 1 "dn: ou=people,dc=jetty,dc=org", @@ -121,26 +122,29 @@ public class JAASLdapLoginServiceTest { private static LdapServer _ldapServer; - private JAASLoginService jaasLoginService(String name) { - JAASLoginService ls = new JAASLoginService("foo"); - ls.setCallbackHandlerClass("org.eclipse.jetty.jaas.callback.DefaultCallbackHandler"); - ls.setIdentityService(new DefaultIdentityService()); - ls.setConfiguration(new TestConfiguration(true)); - return ls; + private JAASLoginService jaasLoginService(String name) + { + JAASLoginService ls = new JAASLoginService("foo"); + ls.setCallbackHandlerClass("org.eclipse.jetty.jaas.callback.DefaultCallbackHandler"); + ls.setIdentityService(new DefaultIdentityService()); + ls.setConfiguration(new TestConfiguration(true)); + return ls; } private UserIdentity doLogin(String username, String password) throws Exception { JAASLoginService ls = jaasLoginService("foo"); Request request = new Request(null, null); - return ls.login( username, password, request); + return ls.login(username, password, request); } - public static LdapServer getLdapServer() { + public static LdapServer getLdapServer() + { return _ldapServer; } - public static void setLdapServer(LdapServer ldapServer) { + public static void setLdapServer(LdapServer ldapServer) + { _ldapServer = ldapServer; } @@ -148,7 +152,7 @@ public class JAASLdapLoginServiceTest { private boolean forceBindingLogin; - public TestConfiguration( boolean forceBindingLogin ) + public TestConfiguration(boolean forceBindingLogin) { this.forceBindingLogin = forceBindingLogin; } @@ -156,24 +160,22 @@ public class JAASLdapLoginServiceTest @Override public AppConfigurationEntry[] getAppConfigurationEntry(String name) { - Map options = new HashMap<>( ); - options.put( "hostname", "localhost" ); - options.put( "port", Integer.toString(_ldapServer.getTransports()[0].getPort())); - options.put( "contextFactory", "com.sun.jndi.ldap.LdapCtxFactory" ); - options.put( "bindDn", "uid=admin,ou=system"); - options.put( "bindPassword", "secret"); - options.put( "userBaseDn", "ou=people,dc=jetty,dc=org" ); - options.put( "roleBaseDn","ou=groups,dc=jetty,dc=org"); - options.put( "roleNameAttribute", "cn" ); - options.put( "forceBindingLogin", Boolean.toString( forceBindingLogin ) ); - AppConfigurationEntry entry = new AppConfigurationEntry( LdapLoginModule.class.getCanonicalName(), LoginModuleControlFlag.REQUIRED, options); + Map options = new HashMap<>(); + options.put("hostname", "localhost"); + options.put("port", Integer.toString(_ldapServer.getTransports()[0].getPort())); + options.put("contextFactory", "com.sun.jndi.ldap.LdapCtxFactory"); + options.put("bindDn", "uid=admin,ou=system"); + options.put("bindPassword", "secret"); + options.put("userBaseDn", "ou=people,dc=jetty,dc=org"); + options.put("roleBaseDn", "ou=groups,dc=jetty,dc=org"); + options.put("roleNameAttribute", "cn"); + options.put("forceBindingLogin", Boolean.toString(forceBindingLogin)); + AppConfigurationEntry entry = new AppConfigurationEntry(LdapLoginModule.class.getCanonicalName(), LoginModuleControlFlag.REQUIRED, options); - return new AppConfigurationEntry[] {entry}; + return new AppConfigurationEntry[]{entry}; } - } - @Test public void testLdapUserIdentity() throws Exception { @@ -182,17 +184,17 @@ public class JAASLdapLoginServiceTest ls.setIdentityService(new DefaultIdentityService()); ls.setConfiguration(new TestConfiguration(false)); Request request = new Request(null, null); - UserIdentity userIdentity = ls.login( "someone", "complicatedpassword", request); - assertNotNull( userIdentity ); - assertTrue( userIdentity.isUserInRole( "developers", null) ); - assertTrue( userIdentity.isUserInRole( "admin", null) ); - assertFalse( userIdentity.isUserInRole( "blabla", null) ); + UserIdentity userIdentity = ls.login("someone", "complicatedpassword", request); + assertNotNull(userIdentity); + assertTrue(userIdentity.isUserInRole("developers", null)); + assertTrue(userIdentity.isUserInRole("admin", null)); + assertFalse(userIdentity.isUserInRole("blabla", null)); - userIdentity = ls.login( "someoneelse", "verycomplicatedpassword", request); - assertNotNull( userIdentity ); - assertFalse( userIdentity.isUserInRole( "developers", null) ); - assertTrue( userIdentity.isUserInRole( "admin", null) ); - assertFalse( userIdentity.isUserInRole( "blabla", null) ); + userIdentity = ls.login("someoneelse", "verycomplicatedpassword", request); + assertNotNull(userIdentity); + assertFalse(userIdentity.isUserInRole("developers", null)); + assertTrue(userIdentity.isUserInRole("admin", null)); + assertFalse(userIdentity.isUserInRole("blabla", null)); } @Test @@ -203,38 +205,37 @@ public class JAASLdapLoginServiceTest ls.setIdentityService(new DefaultIdentityService()); ls.setConfiguration(new TestConfiguration(true)); Request request = new Request(null, null); - UserIdentity userIdentity = ls.login( "someone", "complicatedpassword", request); - assertNotNull( userIdentity ); - assertTrue( userIdentity.isUserInRole( "developers", null) ); - assertTrue( userIdentity.isUserInRole( "admin", null) ); - assertFalse( userIdentity.isUserInRole( "blabla", null) ); - - userIdentity = ls.login( "someone", "wrongpassword", request); - assertNull( userIdentity ); + UserIdentity userIdentity = ls.login("someone", "complicatedpassword", request); + assertNotNull(userIdentity); + assertTrue(userIdentity.isUserInRole("developers", null)); + assertTrue(userIdentity.isUserInRole("admin", null)); + assertFalse(userIdentity.isUserInRole("blabla", null)); + userIdentity = ls.login("someone", "wrongpassword", request); + assertNull(userIdentity); } @Test public void testLdapBindingSubdirUniqueUserName() throws Exception { UserIdentity userIdentity = doLogin("uniqueuser", "hello123"); - assertNotNull( userIdentity ); - assertTrue( userIdentity.isUserInRole( "developers", null) ); - assertTrue( userIdentity.isUserInRole( "admin", null) ); - assertFalse( userIdentity.isUserInRole( "blabla", null) ); + assertNotNull(userIdentity); + assertTrue(userIdentity.isUserInRole("developers", null)); + assertTrue(userIdentity.isUserInRole("admin", null)); + assertFalse(userIdentity.isUserInRole("blabla", null)); } @Test public void testLdapBindingAmbiguousUserName() throws Exception { - UserIdentity userIdentity = doLogin( "ambiguousone", "foobar"); - assertNull( userIdentity ); + UserIdentity userIdentity = doLogin("ambiguousone", "foobar"); + assertNull(userIdentity); } @Test public void testLdapBindingSubdirAmbiguousUserName() throws Exception { - UserIdentity userIdentity = doLogin( "ambiguousone", "barfoo"); - assertNull( userIdentity ); + UserIdentity userIdentity = doLogin("ambiguousone", "barfoo"); + assertNull(userIdentity); } } diff --git a/jetty-jaas/src/test/java/org/eclipse/jetty/jaas/JAASLoginServiceTest.java b/jetty-jaas/src/test/java/org/eclipse/jetty/jaas/JAASLoginServiceTest.java index 876f323742d..b4e82633eea 100644 --- a/jetty-jaas/src/test/java/org/eclipse/jetty/jaas/JAASLoginServiceTest.java +++ b/jetty-jaas/src/test/java/org/eclipse/jetty/jaas/JAASLoginServiceTest.java @@ -16,15 +16,10 @@ // ======================================================================== // - package org.eclipse.jetty.jaas; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertTrue; - import java.security.Principal; import java.util.Collections; - import javax.security.auth.Subject; import javax.security.auth.login.AppConfigurationEntry; import javax.security.auth.login.AppConfigurationEntry.LoginModuleControlFlag; @@ -34,6 +29,9 @@ import org.eclipse.jetty.security.DefaultIdentityService; import org.eclipse.jetty.server.Request; import org.junit.jupiter.api.Test; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + /** * JAASLoginServiceTest */ @@ -46,87 +44,83 @@ public class JAASLoginServiceTest @Override public AppConfigurationEntry[] getAppConfigurationEntry(String name) { - return new AppConfigurationEntry[] {_entry}; + return new AppConfigurationEntry[]{_entry}; } - } - - + interface SomeRole { - + } public class TestRole implements Principal, SomeRole { String _name; - public TestRole (String name) + public TestRole(String name) { _name = name; } public String getName() { - return _name; + return _name; } } - - + public class AnotherTestRole extends TestRole { public AnotherTestRole(String name) { super(name); - } + } } - + public class NotTestRole implements Principal { String _name; - - public NotTestRole (String n) + + public NotTestRole(String n) { _name = n; } - + public String getName() { - return _name; + return _name; } } - + @Test - public void testServletRequestCallback () throws Exception + public void testServletRequestCallback() throws Exception { //Test with the DefaultCallbackHandler JAASLoginService ls = new JAASLoginService("foo"); ls.setCallbackHandlerClass("org.eclipse.jetty.jaas.callback.DefaultCallbackHandler"); ls.setIdentityService(new DefaultIdentityService()); ls.setConfiguration(new TestConfiguration()); - Request request = new Request(null, null); + Request request = new Request(null, null); ls.login("aaardvaark", "aaa", request); - + //Test with the fallback CallbackHandler ls = new JAASLoginService("foo"); ls.setIdentityService(new DefaultIdentityService()); - ls.setConfiguration(new TestConfiguration()); + ls.setConfiguration(new TestConfiguration()); ls.login("aaardvaark", "aaa", request); - } @Test - public void testLoginServiceRoles () throws Exception + public void testLoginServiceRoles() throws Exception { JAASLoginService ls = new JAASLoginService("foo"); - + //test that we always add in the DEFAULT ROLE CLASSNAME - ls.setRoleClassNames(new String[] {"arole", "brole"}); + ls.setRoleClassNames(new String[]{"arole", "brole"}); String[] roles = ls.getRoleClassNames(); assertEquals(3, roles.length); assertEquals(JAASLoginService.DEFAULT_ROLE_CLASS_NAME, roles[2]); - - ls.setRoleClassNames(new String[] {}); + + ls.setRoleClassNames(new String[]{}); assertEquals(1, ls.getRoleClassNames().length); assertEquals(JAASLoginService.DEFAULT_ROLE_CLASS_NAME, ls.getRoleClassNames()[0]); @@ -135,20 +129,22 @@ public class JAASLoginServiceTest assertEquals(JAASLoginService.DEFAULT_ROLE_CLASS_NAME, ls.getRoleClassNames()[0]); //test a custom role class where some of the roles are subclasses of it - ls.setRoleClassNames(new String[] {TestRole.class.getName()}); + ls.setRoleClassNames(new String[]{TestRole.class.getName()}); Subject subject = new Subject(); subject.getPrincipals().add(new NotTestRole("w")); subject.getPrincipals().add(new TestRole("x")); subject.getPrincipals().add(new TestRole("y")); subject.getPrincipals().add(new AnotherTestRole("z")); - + String[] groups = ls.getGroups(subject); assertEquals(3, groups.length); - for (String g:groups) + for (String g : groups) + { assertTrue(g.equals("x") || g.equals("y") || g.equals("z")); - + } + //test a custom role class - ls.setRoleClassNames(new String[] {AnotherTestRole.class.getName()}); + ls.setRoleClassNames(new String[]{AnotherTestRole.class.getName()}); Subject subject2 = new Subject(); subject2.getPrincipals().add(new NotTestRole("w")); subject2.getPrincipals().add(new TestRole("x")); @@ -156,25 +152,26 @@ public class JAASLoginServiceTest subject2.getPrincipals().add(new AnotherTestRole("z")); assertEquals(1, ls.getGroups(subject2).length); assertEquals("z", ls.getGroups(subject2)[0]); - + //test a custom role class that implements an interface - ls.setRoleClassNames(new String[] {SomeRole.class.getName()}); + ls.setRoleClassNames(new String[]{SomeRole.class.getName()}); Subject subject3 = new Subject(); subject3.getPrincipals().add(new NotTestRole("w")); subject3.getPrincipals().add(new TestRole("x")); subject3.getPrincipals().add(new TestRole("y")); subject3.getPrincipals().add(new AnotherTestRole("z")); assertEquals(3, ls.getGroups(subject3).length); - for (String g:groups) + for (String g : groups) + { assertTrue(g.equals("x") || g.equals("y") || g.equals("z")); - + } + //test a class that doesn't match - ls.setRoleClassNames(new String[] {NotTestRole.class.getName()}); + ls.setRoleClassNames(new String[]{NotTestRole.class.getName()}); Subject subject4 = new Subject(); subject4.getPrincipals().add(new TestRole("x")); subject4.getPrincipals().add(new TestRole("y")); subject4.getPrincipals().add(new AnotherTestRole("z")); - assertEquals(0, ls.getGroups(subject4).length); + assertEquals(0, ls.getGroups(subject4).length); } - } diff --git a/jetty-jaas/src/test/java/org/eclipse/jetty/jaas/TestLoginModule.java b/jetty-jaas/src/test/java/org/eclipse/jetty/jaas/TestLoginModule.java index 89cbc636ef3..c09e39f1ac3 100644 --- a/jetty-jaas/src/test/java/org/eclipse/jetty/jaas/TestLoginModule.java +++ b/jetty-jaas/src/test/java/org/eclipse/jetty/jaas/TestLoginModule.java @@ -16,11 +16,8 @@ // ======================================================================== // - package org.eclipse.jetty.jaas; -import static org.junit.jupiter.api.Assertions.assertNotNull; - import javax.security.auth.callback.Callback; import javax.security.auth.login.LoginException; @@ -30,6 +27,7 @@ import org.eclipse.jetty.jaas.spi.UserInfo; import org.eclipse.jetty.util.ArrayUtil; import org.eclipse.jetty.util.security.Password; +import static org.junit.jupiter.api.Assertions.assertNotNull; public class TestLoginModule extends AbstractLoginModule { @@ -47,7 +45,6 @@ public class TestLoginModule extends AbstractLoginModule return ArrayUtil.addToArray(super.configureCallbacks(), _callback, Callback.class); } - @Override public boolean login() throws LoginException { @@ -55,5 +52,4 @@ public class TestLoginModule extends AbstractLoginModule assertNotNull(_callback.getRequest()); return result; } - } diff --git a/jetty-jaspi/src/main/java/org/eclipse/jetty/security/jaspi/JaspiAuthenticator.java b/jetty-jaspi/src/main/java/org/eclipse/jetty/security/jaspi/JaspiAuthenticator.java index b300415c431..3ee6dc1836a 100644 --- a/jetty-jaspi/src/main/java/org/eclipse/jetty/security/jaspi/JaspiAuthenticator.java +++ b/jetty-jaspi/src/main/java/org/eclipse/jetty/security/jaspi/JaspiAuthenticator.java @@ -22,7 +22,6 @@ import java.io.IOException; import java.security.Principal; import java.util.Map; import java.util.Set; - import javax.security.auth.Subject; import javax.security.auth.message.AuthException; import javax.security.auth.message.AuthStatus; @@ -54,7 +53,7 @@ import org.eclipse.jetty.util.log.Logger; public class JaspiAuthenticator extends LoginAuthenticator { private static final Logger LOG = Log.getLogger(JaspiAuthenticator.class.getName()); - + private final ServerAuthConfig _authConfig; private final Map _authProperties; @@ -67,14 +66,14 @@ public class JaspiAuthenticator extends LoginAuthenticator private final IdentityService _identityService; - - public JaspiAuthenticator(ServerAuthConfig authConfig, Map authProperties, ServletCallbackHandler callbackHandler, Subject serviceSubject, boolean allowLazyAuthentication, IdentityService identityService) { // TODO maybe pass this in via setConfiguration ? - if (callbackHandler == null) throw new NullPointerException("No CallbackHandler"); - if (authConfig == null) throw new NullPointerException("No AuthConfig"); + if (callbackHandler == null) + throw new NullPointerException("No CallbackHandler"); + if (authConfig == null) + throw new NullPointerException("No AuthConfig"); this._authConfig = authConfig; this._authProperties = authProperties; this._callbackHandler = callbackHandler; @@ -102,7 +101,7 @@ public class JaspiAuthenticator extends LoginAuthenticator request.setAttribute("org.eclipse.jetty.security.jaspi.info", info); Authentication a = validateRequest(info); - + //if its not mandatory to authenticate, and the authenticator returned UNAUTHENTICATED, we treat it as authentication deferred if (_allowLazyAuthentication && !info.isAuthMandatory() && a == Authentication.UNAUTHENTICATED) a = new DeferredAuthentication(this); @@ -113,18 +112,18 @@ public class JaspiAuthenticator extends LoginAuthenticator @Override public boolean secureResponse(ServletRequest req, ServletResponse res, boolean mandatory, User validatedUser) throws ServerAuthException { - JaspiMessageInfo info = (JaspiMessageInfo) req.getAttribute("org.eclipse.jetty.security.jaspi.info"); - if (info == null) throw new NullPointerException("MessageInfo from request missing: " + req); + JaspiMessageInfo info = (JaspiMessageInfo)req.getAttribute("org.eclipse.jetty.security.jaspi.info"); + if (info == null) + throw new NullPointerException("MessageInfo from request missing: " + req); return secureResponse(info, validatedUser); } - - /** + /** * @see org.eclipse.jetty.security.authentication.LoginAuthenticator#login(java.lang.String, java.lang.Object, javax.servlet.ServletRequest) */ @Override public UserIdentity login(String username, Object password, ServletRequest request) - { + { UserIdentity user = _loginService.login(username, password, request); if (user != null) { @@ -139,8 +138,6 @@ public class JaspiAuthenticator extends LoginAuthenticator return user; } - - public Authentication validateRequest(JaspiMessageInfo messageInfo) throws ServerAuthException { try @@ -151,8 +148,10 @@ public class JaspiAuthenticator extends LoginAuthenticator AuthStatus authStatus = authContext.validateRequest(messageInfo, clientSubject, _serviceSubject); - if (authStatus == AuthStatus.SEND_CONTINUE) return Authentication.SEND_CONTINUE; - if (authStatus == AuthStatus.SEND_FAILURE) return Authentication.SEND_FAILURE; + if (authStatus == AuthStatus.SEND_CONTINUE) + return Authentication.SEND_CONTINUE; + if (authStatus == AuthStatus.SEND_FAILURE) + return Authentication.SEND_FAILURE; if (authStatus == AuthStatus.SUCCESS) { @@ -165,7 +164,10 @@ public class JaspiAuthenticator extends LoginAuthenticator else { CallerPrincipalCallback principalCallback = _callbackHandler.getThreadCallerPrincipalCallback(); - if (principalCallback == null) { return Authentication.UNAUTHENTICATED; } + if (principalCallback == null) + { + return Authentication.UNAUTHENTICATED; + } Principal principal = principalCallback.getPrincipal(); if (principal == null) { @@ -179,18 +181,21 @@ public class JaspiAuthenticator extends LoginAuthenticator break; } } - if (principal == null) { return Authentication.UNAUTHENTICATED; } + if (principal == null) + { + return Authentication.UNAUTHENTICATED; + } } GroupPrincipalCallback groupPrincipalCallback = _callbackHandler.getThreadGroupPrincipalCallback(); String[] groups = groupPrincipalCallback == null ? null : groupPrincipalCallback.getGroups(); userIdentity = _identityService.newUserIdentity(clientSubject, principal, groups); } - + HttpSession session = ((HttpServletRequest)messageInfo.getRequestMessage()).getSession(false); - Authentication cached = (session == null?null:(SessionAuthentication)session.getAttribute(SessionAuthentication.__J_AUTHENTICATED)); + Authentication cached = (session == null ? null : (SessionAuthentication)session.getAttribute(SessionAuthentication.__J_AUTHENTICATED)); if (cached != null) return cached; - + return new UserAuthentication(getAuthMethod(), userIdentity); } if (authStatus == AuthStatus.SEND_SUCCESS) @@ -200,14 +205,14 @@ public class JaspiAuthenticator extends LoginAuthenticator } if (authStatus == AuthStatus.FAILURE) { - HttpServletResponse response = (HttpServletResponse) messageInfo.getResponseMessage(); + HttpServletResponse response = (HttpServletResponse)messageInfo.getResponseMessage(); response.sendError(HttpServletResponse.SC_FORBIDDEN); return Authentication.SEND_FAILURE; } // should not happen throw new IllegalStateException("No AuthStatus returned"); } - catch (IOException|AuthException e) + catch (IOException | AuthException e) { throw new ServerAuthException(e); } @@ -229,5 +234,4 @@ public class JaspiAuthenticator extends LoginAuthenticator throw new ServerAuthException(e); } } - } diff --git a/jetty-jaspi/src/main/java/org/eclipse/jetty/security/jaspi/JaspiAuthenticatorFactory.java b/jetty-jaspi/src/main/java/org/eclipse/jetty/security/jaspi/JaspiAuthenticatorFactory.java index f8f0776d17a..eba7fcf57e9 100644 --- a/jetty-jaspi/src/main/java/org/eclipse/jetty/security/jaspi/JaspiAuthenticatorFactory.java +++ b/jetty-jaspi/src/main/java/org/eclipse/jetty/security/jaspi/JaspiAuthenticatorFactory.java @@ -45,12 +45,10 @@ public class JaspiAuthenticatorFactory extends DefaultAuthenticatorFactory private static final Logger LOG = Log.getLogger(JaspiAuthenticatorFactory.class); private static String MESSAGE_LAYER = "HTTP"; - + private Subject _serviceSubject; private String _serverName; - - /* ------------------------------------------------------------ */ /** * @return the serviceSubject */ @@ -59,7 +57,6 @@ public class JaspiAuthenticatorFactory extends DefaultAuthenticatorFactory return _serviceSubject; } - /* ------------------------------------------------------------ */ /** * @param serviceSubject the serviceSubject to set */ @@ -68,7 +65,6 @@ public class JaspiAuthenticatorFactory extends DefaultAuthenticatorFactory _serviceSubject = serviceSubject; } - /* ------------------------------------------------------------ */ /** * @return the serverName */ @@ -77,7 +73,6 @@ public class JaspiAuthenticatorFactory extends DefaultAuthenticatorFactory return _serverName; } - /* ------------------------------------------------------------ */ /** * @param serverName the serverName to set */ @@ -86,86 +81,91 @@ public class JaspiAuthenticatorFactory extends DefaultAuthenticatorFactory _serverName = serverName; } - /* ------------------------------------------------------------ */ @Override public Authenticator getAuthenticator(Server server, ServletContext context, AuthConfiguration configuration, IdentityService identityService, LoginService loginService) { - Authenticator authenticator=null; - try + Authenticator authenticator = null; + try { AuthConfigFactory authConfigFactory = AuthConfigFactory.getFactory(); - RegistrationListener listener = (layer, appContext) -> {}; + RegistrationListener listener = (layer, appContext) -> + { + }; - Subject serviceSubject=findServiceSubject(server); - String serverName=findServerName(server); + Subject serviceSubject = findServiceSubject(server); + String serverName = findServerName(server); - String contextPath=context.getContextPath(); - if (contextPath==null || contextPath.length()==0) - contextPath="/"; + String contextPath = context.getContextPath(); + if (contextPath == null || contextPath.length() == 0) + contextPath = "/"; String appContext = serverName + " " + contextPath; - AuthConfigProvider authConfigProvider = authConfigFactory.getConfigProvider(MESSAGE_LAYER,appContext,listener); - + AuthConfigProvider authConfigProvider = authConfigFactory.getConfigProvider(MESSAGE_LAYER, appContext, listener); + if (authConfigProvider != null) { ServletCallbackHandler servletCallbackHandler = new ServletCallbackHandler(loginService); - ServerAuthConfig serverAuthConfig = authConfigProvider.getServerAuthConfig(MESSAGE_LAYER,appContext,servletCallbackHandler); + ServerAuthConfig serverAuthConfig = authConfigProvider.getServerAuthConfig(MESSAGE_LAYER, appContext, servletCallbackHandler); if (serverAuthConfig != null) { Map map = new HashMap(); for (String key : configuration.getInitParameterNames()) - map.put(key,configuration.getInitParameter(key)); - authenticator= new JaspiAuthenticator(serverAuthConfig,map,servletCallbackHandler, - serviceSubject,true, identityService); + { + map.put(key, configuration.getInitParameter(key)); + } + authenticator = new JaspiAuthenticator(serverAuthConfig, map, servletCallbackHandler, + serviceSubject, true, identityService); } } - } - catch (AuthException e) + } + catch (AuthException e) { LOG.warn(e); } return authenticator; } - /* ------------------------------------------------------------ */ - /** Find a service Subject. - * If {@link #setServiceSubject(Subject)} has not been used to + /** + * Find a service Subject. + * If {@link #setServiceSubject(Subject)} has not been used to * set a subject, then the {@link Server#getBeans(Class)} method is * used to look for a Subject. + * * @param server the server to pull the Subject from * @return the subject */ protected Subject findServiceSubject(Server server) { - if (_serviceSubject!=null) + if (_serviceSubject != null) return _serviceSubject; List subjects = (List)server.getBeans(Subject.class); - if (subjects.size()>0) + if (subjects.size() > 0) return subjects.get(0); return null; } - /* ------------------------------------------------------------ */ - /** Find a servername. + /** + * Find a servername. * If {@link #setServerName(String)} has not been called, then * use the name of the a principal in the service subject. * If not found, return "server". + * * @param server the server to find the name of * @return the server name from the service Subject (or default value if not found in subject or principals) */ protected String findServerName(Server server) { - if (_serverName!=null) + if (_serverName != null) return _serverName; Subject subject = findServiceSubject(server); - if (subject!=null) + if (subject != null) { Set principals = subject.getPrincipals(); - if (principals!=null && !principals.isEmpty()) + if (principals != null && !principals.isEmpty()) return principals.iterator().next().getName(); } - + return "server"; } } diff --git a/jetty-jaspi/src/main/java/org/eclipse/jetty/security/jaspi/JaspiMessageInfo.java b/jetty-jaspi/src/main/java/org/eclipse/jetty/security/jaspi/JaspiMessageInfo.java index 120fc777233..7f429a9719d 100644 --- a/jetty-jaspi/src/main/java/org/eclipse/jetty/security/jaspi/JaspiMessageInfo.java +++ b/jetty-jaspi/src/main/java/org/eclipse/jetty/security/jaspi/JaspiMessageInfo.java @@ -22,7 +22,6 @@ import java.util.Collection; import java.util.HashMap; import java.util.Map; import java.util.Set; - import javax.security.auth.message.MessageInfo; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; @@ -81,11 +80,11 @@ public class JaspiMessageInfo implements MessageInfo return map.getAuthMethod(); } - public boolean isAuthMandatory() { + public boolean isAuthMandatory() + { return map.isAuthMandatory(); } - //TODO this has bugs in the view implementations. Changing them will not affect the hardcoded values. private static class MIMap implements Map { @@ -101,9 +100,9 @@ public class JaspiMessageInfo implements MessageInfo @Override public int size() { - return (isMandatory? 1:0) + - (authMethod == null? 0: 1) + - (delegate == null? 0: delegate.size()); + return (isMandatory ? 1 : 0) + + (authMethod == null ? 0 : 1) + + (delegate == null ? 0 : delegate.size()); } @Override @@ -115,25 +114,32 @@ public class JaspiMessageInfo implements MessageInfo @Override public boolean containsKey(Object key) { - if (MANDATORY_KEY.equals(key)) return isMandatory; - if (AUTH_METHOD_KEY.equals(key)) return authMethod != null; + if (MANDATORY_KEY.equals(key)) + return isMandatory; + if (AUTH_METHOD_KEY.equals(key)) + return authMethod != null; return delegate != null && delegate.containsKey(key); } @Override public boolean containsValue(Object value) { - if (isMandatory && "true".equals(value)) return true; - if (authMethod == value || (authMethod != null && authMethod.equals(value))) return true; + if (isMandatory && "true".equals(value)) + return true; + if (authMethod == value || (authMethod != null && authMethod.equals(value))) + return true; return delegate != null && delegate.containsValue(value); } @Override public Object get(Object key) { - if (MANDATORY_KEY.equals(key)) return isMandatory? "true": null; - if (AUTH_METHOD_KEY.equals(key)) return authMethod; - if (delegate == null) return null; + if (MANDATORY_KEY.equals(key)) + return isMandatory ? "true" : null; + if (AUTH_METHOD_KEY.equals(key)) + return authMethod; + if (delegate == null) + return null; return delegate.get(key); } @@ -147,8 +153,9 @@ public class JaspiMessageInfo implements MessageInfo if (AUTH_METHOD_KEY.equals(key)) { String authMethod = this.authMethod; - this.authMethod = (String) value; - if (delegate != null) delegate.put(AUTH_METHOD_KEY, value); + this.authMethod = (String)value; + if (delegate != null) + delegate.put(AUTH_METHOD_KEY, value); return authMethod; } @@ -166,10 +173,12 @@ public class JaspiMessageInfo implements MessageInfo { String authMethod = this.authMethod; this.authMethod = null; - if (delegate != null) delegate.remove(AUTH_METHOD_KEY); + if (delegate != null) + delegate.remove(AUTH_METHOD_KEY); return authMethod; } - if (delegate == null) return null; + if (delegate == null) + return null; return delegate.remove(key); } @@ -178,9 +187,9 @@ public class JaspiMessageInfo implements MessageInfo { if (map != null) { - for (Object o: map.entrySet()) + for (Object o : map.entrySet()) { - Map.Entry entry = (Entry) o; + Map.Entry entry = (Entry)o; put(entry.getKey(), entry.getValue()); } } @@ -213,12 +222,15 @@ public class JaspiMessageInfo implements MessageInfo private Map getDelegate(boolean create) { - if (!create || delegate != null) return delegate; + if (!create || delegate != null) + return delegate; if (create) { delegate = new HashMap(); - if (isMandatory) delegate.put(MANDATORY_KEY, "true"); - if (authMethod != null) delegate.put(AUTH_METHOD_KEY, authMethod); + if (isMandatory) + delegate.put(MANDATORY_KEY, "true"); + if (authMethod != null) + delegate.put(AUTH_METHOD_KEY, authMethod); } return delegate; } diff --git a/jetty-jaspi/src/main/java/org/eclipse/jetty/security/jaspi/ServletCallbackHandler.java b/jetty-jaspi/src/main/java/org/eclipse/jetty/security/jaspi/ServletCallbackHandler.java index 942332792ed..f342c6618ed 100644 --- a/jetty-jaspi/src/main/java/org/eclipse/jetty/security/jaspi/ServletCallbackHandler.java +++ b/jetty-jaspi/src/main/java/org/eclipse/jetty/security/jaspi/ServletCallbackHandler.java @@ -19,7 +19,6 @@ package org.eclipse.jetty.security.jaspi; import java.io.IOException; - import javax.security.auth.Subject; import javax.security.auth.callback.Callback; import javax.security.auth.callback.CallbackHandler; @@ -61,20 +60,20 @@ public class ServletCallbackHandler implements CallbackHandler // jaspi to server communication if (callback instanceof CallerPrincipalCallback) { - _callerPrincipals.set((CallerPrincipalCallback) callback); + _callerPrincipals.set((CallerPrincipalCallback)callback); } else if (callback instanceof GroupPrincipalCallback) { - _groupPrincipals.set((GroupPrincipalCallback) callback); + _groupPrincipals.set((GroupPrincipalCallback)callback); } else if (callback instanceof PasswordValidationCallback) { - PasswordValidationCallback passwordValidationCallback = (PasswordValidationCallback) callback; + PasswordValidationCallback passwordValidationCallback = (PasswordValidationCallback)callback; Subject subject = passwordValidationCallback.getSubject(); - UserIdentity user = _loginService.login(passwordValidationCallback.getUsername(),passwordValidationCallback.getPassword(), null); - - if (user!=null) + UserIdentity user = _loginService.login(passwordValidationCallback.getUsername(), passwordValidationCallback.getPassword(), null); + + if (user != null) { passwordValidationCallback.setResult(true); passwordValidationCallback.getSubject().getPrincipals().addAll(user.getSubject().getPrincipals()); @@ -83,15 +82,15 @@ public class ServletCallbackHandler implements CallbackHandler } else if (callback instanceof CredentialValidationCallback) { - CredentialValidationCallback credentialValidationCallback = (CredentialValidationCallback) callback; + CredentialValidationCallback credentialValidationCallback = (CredentialValidationCallback)callback; Subject subject = credentialValidationCallback.getSubject(); LoginCallback loginCallback = new LoginCallbackImpl(subject, - credentialValidationCallback.getUsername(), - credentialValidationCallback.getCredential()); + credentialValidationCallback.getUsername(), + credentialValidationCallback.getCredential()); - UserIdentity user = _loginService.login(credentialValidationCallback.getUsername(),credentialValidationCallback.getCredential(), null); + UserIdentity user = _loginService.login(credentialValidationCallback.getUsername(), credentialValidationCallback.getCredential(), null); - if (user!=null) + if (user != null) { loginCallback.setUserPrincipal(user.getUserPrincipal()); credentialValidationCallback.getSubject().getPrivateCredentials().add(loginCallback); @@ -101,18 +100,21 @@ public class ServletCallbackHandler implements CallbackHandler } } // server to jaspi communication - // TODO implement these else if (callback instanceof CertStoreCallback) { + // TODO implement this } else if (callback instanceof PrivateKeyCallback) { + // TODO implement this } else if (callback instanceof SecretKeyCallback) { + // TODO implement this } else if (callback instanceof TrustStoreCallback) { + // TODO implement this } else { diff --git a/jetty-jaspi/src/main/java/org/eclipse/jetty/security/jaspi/SimpleAuthConfig.java b/jetty-jaspi/src/main/java/org/eclipse/jetty/security/jaspi/SimpleAuthConfig.java index 34e931cb29d..27d623f6ede 100644 --- a/jetty-jaspi/src/main/java/org/eclipse/jetty/security/jaspi/SimpleAuthConfig.java +++ b/jetty-jaspi/src/main/java/org/eclipse/jetty/security/jaspi/SimpleAuthConfig.java @@ -19,7 +19,6 @@ package org.eclipse.jetty.security.jaspi; import java.util.Map; - import javax.security.auth.Subject; import javax.security.auth.message.AuthException; import javax.security.auth.message.MessageInfo; @@ -73,7 +72,7 @@ public class SimpleAuthConfig implements ServerAuthConfig } @Override - public void refresh() + public void refresh() { } } diff --git a/jetty-jaspi/src/main/java/org/eclipse/jetty/security/jaspi/callback/CredentialValidationCallback.java b/jetty-jaspi/src/main/java/org/eclipse/jetty/security/jaspi/callback/CredentialValidationCallback.java index c70a5e11631..e2e1a318901 100644 --- a/jetty-jaspi/src/main/java/org/eclipse/jetty/security/jaspi/callback/CredentialValidationCallback.java +++ b/jetty-jaspi/src/main/java/org/eclipse/jetty/security/jaspi/callback/CredentialValidationCallback.java @@ -16,7 +16,6 @@ // ======================================================================== // - package org.eclipse.jetty.security.jaspi.callback; import javax.security.auth.Subject; @@ -36,44 +35,41 @@ public class CredentialValidationCallback implements Callback private boolean _result; private Subject _subject; private String _userName; - - - public CredentialValidationCallback (Subject subject, String userName, Credential credential) + + public CredentialValidationCallback(Subject subject, String userName, Credential credential) { _subject = subject; _userName = userName; _credential = credential; } - - public Credential getCredential () + + public Credential getCredential() { return _credential; } - - public void clearCredential () + + public void clearCredential() { _credential = null; - } - + } + public boolean getResult() { return _result; } - + public javax.security.auth.Subject getSubject() { return _subject; } - + public java.lang.String getUsername() { - return _userName; + return _userName; } - + public void setResult(boolean result) { _result = result; } - - } diff --git a/jetty-jaspi/src/main/java/org/eclipse/jetty/security/jaspi/modules/BaseAuthModule.java b/jetty-jaspi/src/main/java/org/eclipse/jetty/security/jaspi/modules/BaseAuthModule.java index 81b03f31688..3a7bf1487a5 100644 --- a/jetty-jaspi/src/main/java/org/eclipse/jetty/security/jaspi/modules/BaseAuthModule.java +++ b/jetty-jaspi/src/main/java/org/eclipse/jetty/security/jaspi/modules/BaseAuthModule.java @@ -46,7 +46,7 @@ import org.eclipse.jetty.util.security.Password; public class BaseAuthModule implements ServerAuthModule, ServerAuthContext { - private static final Class[] SUPPORTED_MESSAGE_TYPES = new Class[] { HttpServletRequest.class, HttpServletResponse.class }; + private static final Class[] SUPPORTED_MESSAGE_TYPES = new Class[]{HttpServletRequest.class, HttpServletResponse.class}; protected static final String LOGIN_SERVICE_KEY = "org.eclipse.jetty.security.jaspi.modules.LoginService"; @@ -109,30 +109,31 @@ public class BaseAuthModule implements ServerAuthModule, ServerAuthContext */ protected boolean isMandatory(MessageInfo messageInfo) { - String mandatory = (String) messageInfo.getMap().get(JaspiMessageInfo.MANDATORY_KEY); - if (mandatory == null) return false; + String mandatory = (String)messageInfo.getMap().get(JaspiMessageInfo.MANDATORY_KEY); + if (mandatory == null) + return false; return Boolean.parseBoolean(mandatory); } - protected boolean login(Subject clientSubject, String credentials, - String authMethod, MessageInfo messageInfo) - throws IOException, UnsupportedCallbackException + protected boolean login(Subject clientSubject, String credentials, + String authMethod, MessageInfo messageInfo) + throws IOException, UnsupportedCallbackException { - credentials = credentials.substring(credentials.indexOf(' ')+1); + credentials = credentials.substring(credentials.indexOf(' ') + 1); credentials = new String(Base64.getDecoder().decode(credentials), StandardCharsets.ISO_8859_1); int i = credentials.indexOf(':'); - String userName = credentials.substring(0,i); - String password = credentials.substring(i+1); + String userName = credentials.substring(0, i); + String password = credentials.substring(i + 1); return login(clientSubject, userName, new Password(password), authMethod, messageInfo); } - protected boolean login(Subject clientSubject, String username, - Credential credential, String authMethod, - MessageInfo messageInfo) - throws IOException, UnsupportedCallbackException + protected boolean login(Subject clientSubject, String username, + Credential credential, String authMethod, + MessageInfo messageInfo) + throws IOException, UnsupportedCallbackException { CredentialValidationCallback credValidationCallback = new CredentialValidationCallback(clientSubject, username, credential); - callbackHandler.handle(new Callback[] { credValidationCallback }); + callbackHandler.handle(new Callback[]{credValidationCallback}); if (credValidationCallback.getResult()) { Set loginCallbacks = clientSubject.getPrivateCredentials(LoginCallbackImpl.class); @@ -141,11 +142,10 @@ public class BaseAuthModule implements ServerAuthModule, ServerAuthContext LoginCallbackImpl loginCallback = loginCallbacks.iterator().next(); CallerPrincipalCallback callerPrincipalCallback = new CallerPrincipalCallback(clientSubject, loginCallback.getUserPrincipal()); GroupPrincipalCallback groupPrincipalCallback = new GroupPrincipalCallback(clientSubject, loginCallback.getRoles()); - callbackHandler.handle(new Callback[] { callerPrincipalCallback, groupPrincipalCallback }); + callbackHandler.handle(new Callback[]{callerPrincipalCallback, groupPrincipalCallback}); } messageInfo.getMap().put(JaspiMessageInfo.AUTH_METHOD_KEY, authMethod); } return credValidationCallback.getResult(); - } } diff --git a/jetty-jaspi/src/main/java/org/eclipse/jetty/security/jaspi/modules/BasicAuthModule.java b/jetty-jaspi/src/main/java/org/eclipse/jetty/security/jaspi/modules/BasicAuthModule.java index 4af1959e934..16ed2106783 100644 --- a/jetty-jaspi/src/main/java/org/eclipse/jetty/security/jaspi/modules/BasicAuthModule.java +++ b/jetty-jaspi/src/main/java/org/eclipse/jetty/security/jaspi/modules/BasicAuthModule.java @@ -40,7 +40,6 @@ public class BasicAuthModule extends BaseAuthModule { private static final Logger LOG = Log.getLogger(BasicAuthModule.class); - private String realmName; private static final String REALM_KEY = "org.eclipse.jetty.security.jaspi.modules.RealmName"; @@ -56,33 +55,39 @@ public class BasicAuthModule extends BaseAuthModule } @Override - public void initialize(MessagePolicy requestPolicy, MessagePolicy responsePolicy, - CallbackHandler handler, Map options) - throws AuthException + public void initialize(MessagePolicy requestPolicy, MessagePolicy responsePolicy, + CallbackHandler handler, Map options) + throws AuthException { super.initialize(requestPolicy, responsePolicy, handler, options); - realmName = (String) options.get(REALM_KEY); + realmName = (String)options.get(REALM_KEY); } @Override - public AuthStatus validateRequest(MessageInfo messageInfo, Subject clientSubject, - Subject serviceSubject) - throws AuthException + public AuthStatus validateRequest(MessageInfo messageInfo, Subject clientSubject, + Subject serviceSubject) + throws AuthException { - HttpServletRequest request = (HttpServletRequest) messageInfo.getRequestMessage(); - HttpServletResponse response = (HttpServletResponse) messageInfo.getResponseMessage(); + HttpServletRequest request = (HttpServletRequest)messageInfo.getRequestMessage(); + HttpServletResponse response = (HttpServletResponse)messageInfo.getResponseMessage(); String credentials = request.getHeader(HttpHeader.AUTHORIZATION.asString()); try { if (credentials != null) { - if (LOG.isDebugEnabled()) LOG.debug("Credentials: " + credentials); - if (login(clientSubject, credentials, Constraint.__BASIC_AUTH, messageInfo)) { return AuthStatus.SUCCESS; } - + if (LOG.isDebugEnabled()) + LOG.debug("Credentials: " + credentials); + if (login(clientSubject, credentials, Constraint.__BASIC_AUTH, messageInfo)) + { + return AuthStatus.SUCCESS; + } } - if (!isMandatory(messageInfo)) { return AuthStatus.SUCCESS; } + if (!isMandatory(messageInfo)) + { + return AuthStatus.SUCCESS; + } response.setHeader(HttpHeader.WWW_AUTHENTICATE.asString(), "basic realm=\"" + realmName + '"'); response.sendError(HttpServletResponse.SC_UNAUTHORIZED); return AuthStatus.SEND_CONTINUE; @@ -95,6 +100,5 @@ public class BasicAuthModule extends BaseAuthModule { throw new AuthException(e.getMessage()); } - } } diff --git a/jetty-jaspi/src/main/java/org/eclipse/jetty/security/jaspi/modules/UserInfo.java b/jetty-jaspi/src/main/java/org/eclipse/jetty/security/jaspi/modules/UserInfo.java index 1ebd0cae20d..d7c7ea99bfe 100644 --- a/jetty-jaspi/src/main/java/org/eclipse/jetty/security/jaspi/modules/UserInfo.java +++ b/jetty-jaspi/src/main/java/org/eclipse/jetty/security/jaspi/modules/UserInfo.java @@ -44,7 +44,7 @@ public class UserInfo public void clearPassword() { - Arrays.fill(password, (char) 0); + Arrays.fill(password, (char)0); password = null; } } diff --git a/jetty-jaspi/src/test/java/org/eclipse/jetty/security/jaspi/HttpHeaderAuthModule.java b/jetty-jaspi/src/test/java/org/eclipse/jetty/security/jaspi/HttpHeaderAuthModule.java index f238239bcd1..533c9837340 100644 --- a/jetty-jaspi/src/test/java/org/eclipse/jetty/security/jaspi/HttpHeaderAuthModule.java +++ b/jetty-jaspi/src/test/java/org/eclipse/jetty/security/jaspi/HttpHeaderAuthModule.java @@ -19,7 +19,6 @@ package org.eclipse.jetty.security.jaspi; import java.util.Map; - import javax.security.auth.Subject; import javax.security.auth.callback.Callback; import javax.security.auth.callback.CallbackHandler; @@ -43,7 +42,7 @@ public class HttpHeaderAuthModule implements ServerAuthModule * Supported message types. For our case we only need to deal with HTTP servlet request and responses. On Java EE 7 this will handle WebSockets as well. */ private static final Class[] SUPPORTED_MESSAGE_TYPES = new Class[] - { HttpServletRequest.class, HttpServletResponse.class }; + {HttpServletRequest.class, HttpServletResponse.class}; /** * Callback handler that is passed in initialize by the container. This processes the callbacks which are objects that populate the "subject". @@ -67,15 +66,11 @@ public class HttpHeaderAuthModule implements ServerAuthModule /** * Initializes the module. Allows you to pass in options. - * - * @param requestPolicy - * request policy, ignored - * @param responsePolicy - * response policy, ignored - * @param h - * callback handler - * @param options - * options + * + * @param requestPolicy request policy, ignored + * @param responsePolicy response policy, ignored + * @param h callback handler + * @param options options */ @Override public void initialize(final MessagePolicy requestPolicy, MessagePolicy responsePolicy, CallbackHandler h, Map options) throws AuthException @@ -112,8 +107,11 @@ public class HttpHeaderAuthModule implements ServerAuthModule // Store the user name that was in the header and also set a group. handler.handle(new Callback[] - { new CallerPrincipalCallback(client,userName), new GroupPrincipalCallback(client,new String[] - { "users" }) }); + { + new CallerPrincipalCallback(client, userName), + new GroupPrincipalCallback(client, new String[] + {"users"}) + }); return AuthStatus.SUCCESS; } catch (final Exception e) @@ -121,5 +119,4 @@ public class HttpHeaderAuthModule implements ServerAuthModule throw new AuthException(e.getMessage()); } } - } diff --git a/jetty-jaspi/src/test/java/org/eclipse/jetty/security/jaspi/JaspiTest.java b/jetty-jaspi/src/test/java/org/eclipse/jetty/security/jaspi/JaspiTest.java index 13309d2a73c..5b0890de3af 100644 --- a/jetty-jaspi/src/test/java/org/eclipse/jetty/security/jaspi/JaspiTest.java +++ b/jetty-jaspi/src/test/java/org/eclipse/jetty/security/jaspi/JaspiTest.java @@ -51,35 +51,34 @@ public class JaspiTest { Server _server; LocalConnector _connector; + public class TestLoginService extends AbstractLoginService { protected Map _users = new HashMap<>(); protected Map _roles = new HashMap(); - - public TestLoginService(String name) { setName(name); } - public void putUser (String username, Credential credential, String[] roles) + public void putUser(String username, Credential credential, String[] roles) { - UserPrincipal userPrincipal = new UserPrincipal(username,credential); + UserPrincipal userPrincipal = new UserPrincipal(username, credential); _users.put(username, userPrincipal); _roles.put(username, roles); } - - /** + + /** * @see org.eclipse.jetty.security.AbstractLoginService#loadRoleInfo(org.eclipse.jetty.security.AbstractLoginService.UserPrincipal) */ @Override protected String[] loadRoleInfo(UserPrincipal user) { - return _roles.get(user.getName()); + return _roles.get(user.getName()); } - /** + /** * @see org.eclipse.jetty.security.AbstractLoginService#loadUserInfo(java.lang.String) */ @Override @@ -88,111 +87,111 @@ public class JaspiTest return _users.get(username); } } - + @BeforeEach public void before() throws Exception { - System.setProperty("org.apache.geronimo.jaspic.configurationFile","src/test/resources/jaspi.xml"); + System.setProperty("org.apache.geronimo.jaspic.configurationFile", "src/test/resources/jaspi.xml"); _server = new Server(); _connector = new LocalConnector(_server); _server.addConnector(_connector); - + ContextHandlerCollection contexts = new ContextHandlerCollection(); _server.setHandler(contexts); - + TestLoginService loginService = new TestLoginService("TestRealm"); - loginService.putUser("user",new Password("password"),new String[]{"users"}); - loginService.putUser("admin",new Password("secret"),new String[]{"users","admins"}); + loginService.putUser("user", new Password("password"), new String[]{"users"}); + loginService.putUser("admin", new Password("secret"), new String[]{"users", "admins"}); _server.addBean(loginService); - + ContextHandler context = new ContextHandler(); contexts.addHandler(context); context.setContextPath("/ctx"); - + JaspiAuthenticatorFactory jaspiAuthFactory = new JaspiAuthenticatorFactory(); - + ConstraintSecurityHandler security = new ConstraintSecurityHandler(); context.setHandler(security); security.setAuthenticatorFactory(jaspiAuthFactory); // security.setAuthenticator(new BasicAuthenticator()); - - Constraint constraint = new Constraint("All","users"); + + Constraint constraint = new Constraint("All", "users"); constraint.setAuthenticate(true); ConstraintMapping mapping = new ConstraintMapping(); mapping.setPathSpec("/jaspi/*"); mapping.setConstraint(constraint); security.addConstraintMapping(mapping); - + TestHandler handler = new TestHandler(); security.setHandler(handler); - + ContextHandler other = new ContextHandler(); contexts.addHandler(other); other.setContextPath("/other"); ConstraintSecurityHandler securityOther = new ConstraintSecurityHandler(); other.setHandler(securityOther); securityOther.setAuthenticatorFactory(jaspiAuthFactory); - securityOther.addConstraintMapping(mapping); + securityOther.addConstraintMapping(mapping); securityOther.setHandler(new TestHandler()); - + _server.start(); } - + @AfterEach public void after() throws Exception { _server.stop(); } - + @Test public void testNoConstraint() throws Exception { String response = _connector.getResponse("GET /ctx/test HTTP/1.0\n\n"); - assertThat(response,startsWith("HTTP/1.1 200 OK")); + assertThat(response, startsWith("HTTP/1.1 200 OK")); } - + @Test public void testConstraintNoAuth() throws Exception { String response = _connector.getResponse("GET /ctx/jaspi/test HTTP/1.0\n\n"); - assertThat(response,startsWith("HTTP/1.1 401 Unauthorized")); - assertThat(response,Matchers.containsString("WWW-Authenticate: basic realm=\"TestRealm\"")); + assertThat(response, startsWith("HTTP/1.1 401 Unauthorized")); + assertThat(response, Matchers.containsString("WWW-Authenticate: basic realm=\"TestRealm\"")); } - + @Test public void testConstraintWrongAuth() throws Exception { String response = _connector.getResponse("GET /ctx/jaspi/test HTTP/1.0\n" + "Authorization: Basic " + Base64.getEncoder().encodeToString("user:wrong".getBytes(ISO_8859_1)) + "\n\n"); - assertThat(response,startsWith("HTTP/1.1 401 Unauthorized")); - assertThat(response,Matchers.containsString("WWW-Authenticate: basic realm=\"TestRealm\"")); + assertThat(response, startsWith("HTTP/1.1 401 Unauthorized")); + assertThat(response, Matchers.containsString("WWW-Authenticate: basic realm=\"TestRealm\"")); } - + @Test public void testConstraintAuth() throws Exception { String response = _connector.getResponse("GET /ctx/jaspi/test HTTP/1.0\n" + "Authorization: Basic " + Base64.getEncoder().encodeToString("user:password".getBytes(ISO_8859_1)) + "\n\n"); - assertThat(response,startsWith("HTTP/1.1 200 OK")); + assertThat(response, startsWith("HTTP/1.1 200 OK")); } - + @Test public void testOtherNoAuth() throws Exception { String response = _connector.getResponse("GET /other/test HTTP/1.0\n\n"); - assertThat(response,startsWith("HTTP/1.1 403 Forbidden")); + assertThat(response, startsWith("HTTP/1.1 403 Forbidden")); } - + @Test public void testOtherAuth() throws Exception { - String response = _connector.getResponse("GET /other/test HTTP/1.0\n"+ - "X-Forwarded-User: user\n\n"); - assertThat(response,startsWith("HTTP/1.1 200 OK")); + String response = _connector.getResponse("GET /other/test HTTP/1.0\n" + + "X-Forwarded-User: user\n\n"); + assertThat(response, startsWith("HTTP/1.1 200 OK")); } - + public class TestHandler extends AbstractHandler { @@ -203,7 +202,7 @@ public class JaspiTest response.setStatus(200); response.setContentType("text/plain"); response.getWriter().println("All OK"); - response.getWriter().println("requestURI="+request.getRequestURI()); + response.getWriter().println("requestURI=" + request.getRequestURI()); } } } diff --git a/jetty-jmx/pom.xml b/jetty-jmx/pom.xml index ff96655eaae..639ef6aaa5f 100644 --- a/jetty-jmx/pom.xml +++ b/jetty-jmx/pom.xml @@ -18,9 +18,7 @@ maven-surefire-plugin - @{argLine} ${jetty.surefire.argLine} - --add-opens org.eclipse.jetty.jmx/org.eclipse.jetty.jmx=ALL-UNNAMED - --add-opens org.eclipse.jetty.jmx/org.eclipse.jetty.util.log.jmx=ALL-UNNAMED + @{argLine} ${jetty.surefire.argLine} --add-opens org.eclipse.jetty.jmx/org.eclipse.jetty.jmx=ALL-UNNAMED --add-opens org.eclipse.jetty.jmx/org.eclipse.jetty.util.log.jmx=ALL-UNNAMED diff --git a/jetty-jmx/src/main/java/org/eclipse/jetty/jmx/ConnectorServer.java b/jetty-jmx/src/main/java/org/eclipse/jetty/jmx/ConnectorServer.java index 3363c342b83..2d8b10f29eb 100644 --- a/jetty-jmx/src/main/java/org/eclipse/jetty/jmx/ConnectorServer.java +++ b/jetty-jmx/src/main/java/org/eclipse/jetty/jmx/ConnectorServer.java @@ -33,7 +33,6 @@ import java.util.HashMap; import java.util.Map; import java.util.Objects; import java.util.function.IntConsumer; - import javax.management.MBeanServer; import javax.management.ObjectName; import javax.management.remote.JMXConnectorServer; @@ -53,10 +52,10 @@ import org.eclipse.jetty.util.thread.ShutdownThread; *

    LifeCycle wrapper for JMXConnectorServer.

    *

    This class provides the following facilities:

    *
      - *
    • participates in the {@code Server} lifecycle
    • - *
    • starts the RMI registry if not there already
    • - *
    • allows to bind the RMI registry and the RMI server to the loopback interface
    • - *
    • makes it easy to use TLS for the JMX communication
    • + *
    • participates in the {@code Server} lifecycle
    • + *
    • starts the RMI registry if not there already
    • + *
    • allows to bind the RMI registry and the RMI server to the loopback interface
    • + *
    • makes it easy to use TLS for the JMX communication
    • *
    */ public class ConnectorServer extends AbstractLifeCycle @@ -77,7 +76,7 @@ public class ConnectorServer extends AbstractLifeCycle * Constructs a ConnectorServer * * @param serviceURL the address of the new ConnectorServer - * @param name object name string to be assigned to ConnectorServer bean + * @param name object name string to be assigned to ConnectorServer bean */ public ConnectorServer(JMXServiceURL serviceURL, String name) { @@ -87,12 +86,12 @@ public class ConnectorServer extends AbstractLifeCycle /** * Constructs a ConnectorServer * - * @param svcUrl the address of the new ConnectorServer + * @param svcUrl the address of the new ConnectorServer * @param environment a set of attributes to control the new ConnectorServer's behavior. - * This parameter can be null. Keys in this map must - * be Strings. The appropriate type of each associated value depends on - * the attribute. The contents of environment are not changed by this call. - * @param name object name string to be assigned to ConnectorServer bean + * This parameter can be null. Keys in this map must + * be Strings. The appropriate type of each associated value depends on + * the attribute. The contents of environment are not changed by this call. + * @param name object name string to be assigned to ConnectorServer bean */ public ConnectorServer(JMXServiceURL svcUrl, Map environment, String name) { diff --git a/jetty-jmx/src/main/java/org/eclipse/jetty/jmx/MBeanContainer.java b/jetty-jmx/src/main/java/org/eclipse/jetty/jmx/MBeanContainer.java index 8b75436f0c1..2ce8320c156 100644 --- a/jetty-jmx/src/main/java/org/eclipse/jetty/jmx/MBeanContainer.java +++ b/jetty-jmx/src/main/java/org/eclipse/jetty/jmx/MBeanContainer.java @@ -78,9 +78,9 @@ public class MBeanContainer implements Container.InheritedListener, Dumpable, De /** * Constructs MBeanContainer * - * @param server instance of MBeanServer for use by container + * @param server instance of MBeanServer for use by container * @param cacheOtherClassLoaders If true, MBeans from other classloaders (eg WebAppClassLoader) will be cached. - * The cache is never flushed, so this should be false if some classloaders do not live forever. + * The cache is never flushed, so this should be false if some classloaders do not live forever. */ public MBeanContainer(MBeanServer server, boolean cacheOtherClassLoaders) { @@ -161,9 +161,13 @@ public class MBeanContainer implements Container.InheritedListener, Dumpable, De { MBeanInfo info = ((ObjectMBean)mbean).getMBeanInfo(); for (Object a : info.getAttributes()) + { LOG.debug(" {}", a); + } for (Object a : info.getOperations()) + { LOG.debug(" {}", a); + } } } return mbean; @@ -196,8 +200,8 @@ public class MBeanContainer implements Container.InheritedListener, Dumpable, De return new MetaData(klass, null, null, Collections.emptyList()); List interfaces = Arrays.stream(klass.getInterfaces()) - .map(intf -> findMetaData(container, intf)) - .collect(Collectors.toList()); + .map(intf -> findMetaData(container, intf)) + .collect(Collectors.toList()); MetaData metaData = new MetaData(klass, findConstructor(klass), findMetaData(container, klass.getSuperclass()), interfaces); if (container != null) @@ -227,8 +231,8 @@ public class MBeanContainer implements Container.InheritedListener, Dumpable, De { Class mbeanClass = Loader.loadClass(klass, mName); Constructor constructor = ModelMBean.class.isAssignableFrom(mbeanClass) - ? mbeanClass.getConstructor() - : mbeanClass.getConstructor(Object.class); + ? mbeanClass.getConstructor() + : mbeanClass.getConstructor(Object.class); if (LOG.isDebugEnabled()) LOG.debug("Found MBean wrapper: {} for {}", mName, klass.getName()); return constructor; @@ -315,7 +319,9 @@ public class MBeanContainer implements Container.InheritedListener, Dumpable, De { Class klass = obj.getClass(); while (klass.isArray()) + { klass = klass.getComponentType(); + } // If no explicit domain, create one. String domain = _domain; @@ -414,8 +420,8 @@ public class MBeanContainer implements Container.InheritedListener, Dumpable, De { _metaData.clear(); _mbeans.values().stream() - .filter(Objects::nonNull) - .forEach(this::unregister); + .filter(Objects::nonNull) + .forEach(this::unregister); _mbeans.clear(); _beans.clear(); } diff --git a/jetty-jmx/src/main/java/org/eclipse/jetty/jmx/MetaData.java b/jetty-jmx/src/main/java/org/eclipse/jetty/jmx/MetaData.java index d073153d353..9519932eeb9 100644 --- a/jetty-jmx/src/main/java/org/eclipse/jetty/jmx/MetaData.java +++ b/jetty-jmx/src/main/java/org/eclipse/jetty/jmx/MetaData.java @@ -30,7 +30,6 @@ import java.util.List; import java.util.Locale; import java.util.Map; import java.util.stream.Collectors; - import javax.management.Attribute; import javax.management.AttributeNotFoundException; import javax.management.MBeanAttributeInfo; @@ -253,8 +252,8 @@ class MetaData private static String signature(Method method) { String signature = Arrays.stream(method.getParameterTypes()) - .map(Class::getName) - .collect(Collectors.joining(",")); + .map(Class::getName) + .collect(Collectors.joining(",")); return String.format("%s(%s)", method.getName(), signature); } @@ -281,22 +280,30 @@ class MetaData { // Start with interfaces, overwrite with superClass, then overwrite with local attributes. for (MetaData intf : _interfaces) + { intf.collectMBeanAttributeInfos(attributeInfos); + } if (_parent != null) { MBeanAttributeInfo[] parentAttributes = _parent.getMBeanInfo().getAttributes(); for (MBeanAttributeInfo parentAttribute : parentAttributes) + { attributeInfos.put(parentAttribute.getName(), parentAttribute); + } } for (Map.Entry entry : _attributes.entrySet()) + { attributeInfos.put(entry.getKey(), entry.getValue()._info); + } } private void collectMBeanOperationInfos(Map operationInfos) { // Start with interfaces, overwrite with superClass, then overwrite with local operations. for (MetaData intf : _interfaces) + { intf.collectMBeanOperationInfos(operationInfos); + } if (_parent != null) { MBeanOperationInfo[] parentOperations = _parent.getMBeanInfo().getOperations(); @@ -307,7 +314,9 @@ class MetaData } } for (Map.Entry entry : _operations.entrySet()) + { operationInfos.put(entry.getKey(), entry.getValue()._info); + } } private static MBeanException toMBeanException(InvocationTargetException x) @@ -323,7 +332,7 @@ class MetaData public String toString() { return String.format("%s@%x[%s, attrs=%s, opers=%s]", getClass().getSimpleName(), hashCode(), - _klass.getName(), _attributes.keySet(), _operations.keySet()); + _klass.getName(), _attributes.keySet(), _operations.keySet()); } private static class AttributeInfo @@ -351,13 +360,15 @@ class MetaData Class returnType = getter.getReturnType(); _convert = isManagedObject(returnType); - String signature = _convert ? - returnType.isArray() ? ObjectName[].class.getName() : ObjectName.class.getName() : - returnType.getName(); + String signature = _convert + ? returnType.isArray() + ? ObjectName[].class.getName() + : ObjectName.class.getName() + : returnType.getName(); String description = attribute.value(); _info = new MBeanAttributeInfo(name, signature, description, true, - _setter != null, getter.getName().startsWith("is")); + _setter != null, getter.getName().startsWith("is")); } Object getAttribute(ObjectMBean mbean) throws ReflectionException, MBeanException @@ -377,7 +388,9 @@ class MetaData int length = Array.getLength(result); ObjectName[] names = new ObjectName[length]; for (int i = 0; i < length; ++i) + { names[i] = mbean.findObjectName(Array.get(result, i)); + } return names; } catch (InvocationTargetException x) @@ -415,7 +428,9 @@ class MetaData ObjectName[] names = (ObjectName[])value; Object result = new Object[names.length]; for (int i = 0; i < names.length; ++i) + { Array.set(result, i, mbean.findBean(names[i])); + } _setter.invoke(target, result); } catch (InvocationTargetException x) @@ -461,7 +476,7 @@ class MetaData public String toString() { return String.format("%s@%x[%s,proxied=%b,convert=%b,info=%s]", getClass().getSimpleName(), hashCode(), - _name, _proxied, _convert, _info); + _name, _proxied, _convert, _info); } } @@ -483,9 +498,11 @@ class MetaData Class returnType = method.getReturnType(); _convert = isManagedObject(returnType); - String returnSignature = _convert ? - returnType.isArray() ? ObjectName[].class.getName() : ObjectName.class.getName() : - returnType.getName(); + String returnSignature = _convert + ? returnType.isArray() + ? ObjectName[].class.getName() + : ObjectName.class.getName() + : returnType.getName(); String impactName = operation.impact(); int impact = MBeanOperationInfo.UNKNOWN; @@ -520,7 +537,9 @@ class MetaData int length = Array.getLength(result); ObjectName[] names = new ObjectName[length]; for (int i = 0; i < length; ++i) + { names[i] = mbean.findObjectName(Array.get(result, i)); + } return names; } catch (InvocationTargetException x) @@ -560,7 +579,7 @@ class MetaData public String toString() { return String.format("%s@%x[%s,proxied=%b,convert=%b]", getClass().getSimpleName(), hashCode(), - _name, _proxied, _convert); + _name, _proxied, _convert); } } } diff --git a/jetty-jmx/src/main/java/org/eclipse/jetty/util/log/jmx/LogMBean.java b/jetty-jmx/src/main/java/org/eclipse/jetty/util/log/jmx/LogMBean.java index 6f7b4c1f840..d3f447bad6c 100644 --- a/jetty-jmx/src/main/java/org/eclipse/jetty/util/log/jmx/LogMBean.java +++ b/jetty-jmx/src/main/java/org/eclipse/jetty/util/log/jmx/LogMBean.java @@ -28,8 +28,8 @@ import org.eclipse.jetty.util.annotation.ManagedOperation; import org.eclipse.jetty.util.annotation.Name; import org.eclipse.jetty.util.log.Log; -/* ------------------------------------------------------------ */ /** + * */ @ManagedObject("Jetty Logging") public class LogMBean extends ObjectMBean @@ -39,21 +39,21 @@ public class LogMBean extends ObjectMBean super(managedObject); } - @ManagedAttribute(value="list of instantiated loggers") + @ManagedAttribute(value = "list of instantiated loggers") public List getLoggers() { List keySet = new ArrayList(Log.getLoggers().keySet()); return keySet; } - @ManagedOperation(value="true if debug enabled for the given logger") + @ManagedOperation(value = "true if debug enabled for the given logger") public boolean isDebugEnabled(@Name("logger") String logger) { return Log.getLogger(logger).isDebugEnabled(); } - - @ManagedOperation(value="Set debug enabled for given logger") - public void setDebugEnabled(@Name("logger")String logger, @Name("enabled") Boolean enabled) + + @ManagedOperation(value = "Set debug enabled for given logger") + public void setDebugEnabled(@Name("logger") String logger, @Name("enabled") Boolean enabled) { Log.getLogger(logger).setDebugEnabled(enabled); } diff --git a/jetty-jmx/src/test/java/com/acme/Base.java b/jetty-jmx/src/test/java/com/acme/Base.java index 049ca5fdeeb..5d6820e9169 100644 --- a/jetty-jmx/src/test/java/com/acme/Base.java +++ b/jetty-jmx/src/test/java/com/acme/Base.java @@ -26,7 +26,6 @@ public class Base extends AbstractLifeCycle int value; String[] messages; - /* ------------------------------------------------------------ */ /** * @return Returns the messages. */ @@ -35,17 +34,14 @@ public class Base extends AbstractLifeCycle return messages; } - /* ------------------------------------------------------------ */ /** - * @param messages - * The messages to set. + * @param messages The messages to set. */ public void setMessages(String[] messages) { this.messages = messages; } - /* ------------------------------------------------------------ */ /** * @return Returns the name. */ @@ -54,17 +50,14 @@ public class Base extends AbstractLifeCycle return name; } - /* ------------------------------------------------------------ */ /** - * @param name - * The name to set. + * @param name The name to set. */ public void setName(String name) { this.name = name; } - /* ------------------------------------------------------------ */ /** * @return Returns the value. */ @@ -73,26 +66,21 @@ public class Base extends AbstractLifeCycle return value; } - /* ------------------------------------------------------------ */ /** - * @param value - * The value to set. + * @param value The value to set. */ public void setValue(int value) { this.value = value; } - /* ------------------------------------------------------------ */ public void doSomething(int arg) { System.err.println("doSomething " + arg); } - /* ------------------------------------------------------------ */ public String findSomething(int arg) { return ("found " + arg); } - } diff --git a/jetty-jmx/src/test/java/com/acme/Derived.java b/jetty-jmx/src/test/java/com/acme/Derived.java index 793ddf5441a..7016baf4e37 100644 --- a/jetty-jmx/src/test/java/com/acme/Derived.java +++ b/jetty-jmx/src/test/java/com/acme/Derived.java @@ -78,5 +78,4 @@ public class Derived extends Base implements Signature { return superManagedInstance; } - } diff --git a/jetty-jmx/src/test/java/com/acme/Managed.java b/jetty-jmx/src/test/java/com/acme/Managed.java index c7e12a4aa95..0da7a21b31f 100644 --- a/jetty-jmx/src/test/java/com/acme/Managed.java +++ b/jetty-jmx/src/test/java/com/acme/Managed.java @@ -41,5 +41,4 @@ public class Managed { return "bad"; } - } diff --git a/jetty-jmx/src/test/java/com/acme/SuperManaged.java b/jetty-jmx/src/test/java/com/acme/SuperManaged.java index 83322b9a2ab..b417abf02ac 100644 --- a/jetty-jmx/src/test/java/com/acme/SuperManaged.java +++ b/jetty-jmx/src/test/java/com/acme/SuperManaged.java @@ -25,5 +25,4 @@ public class SuperManaged extends Managed { return "super"; } - } diff --git a/jetty-jmx/src/test/java/com/acme/jmx/DerivedMBean.java b/jetty-jmx/src/test/java/com/acme/jmx/DerivedMBean.java index 834de9e506e..5b91b4c37d1 100644 --- a/jetty-jmx/src/test/java/com/acme/jmx/DerivedMBean.java +++ b/jetty-jmx/src/test/java/com/acme/jmx/DerivedMBean.java @@ -18,6 +18,7 @@ package com.acme.jmx; +import com.acme.Derived; import org.eclipse.jetty.jmx.ObjectMBean; import org.eclipse.jetty.util.annotation.ManagedAttribute; import org.eclipse.jetty.util.annotation.ManagedObject; @@ -25,8 +26,6 @@ import org.eclipse.jetty.util.annotation.ManagedOperation; import org.eclipse.jetty.util.log.Log; import org.eclipse.jetty.util.log.Logger; -import com.acme.Derived; - @ManagedObject("Derived MBean Wrapper") public class DerivedMBean extends ObjectMBean { @@ -48,5 +47,4 @@ public class DerivedMBean extends ObjectMBean { return "goop"; } - } diff --git a/jetty-jmx/src/test/java/com/acme/jmx/ManagedMBean.java b/jetty-jmx/src/test/java/com/acme/jmx/ManagedMBean.java index 585c73c7e10..3325f6c1094 100644 --- a/jetty-jmx/src/test/java/com/acme/jmx/ManagedMBean.java +++ b/jetty-jmx/src/test/java/com/acme/jmx/ManagedMBean.java @@ -18,13 +18,12 @@ package com.acme.jmx; +import com.acme.Managed; import org.eclipse.jetty.jmx.ObjectMBean; import org.eclipse.jetty.util.annotation.ManagedAttribute; import org.eclipse.jetty.util.annotation.ManagedObject; import org.eclipse.jetty.util.annotation.ManagedOperation; -import com.acme.Managed; - @ManagedObject("Managed MBean Wrapper") public class ManagedMBean extends ObjectMBean { diff --git a/jetty-jmx/src/test/java/org/eclipse/jetty/jmx/ConnectorServerTest.java b/jetty-jmx/src/test/java/org/eclipse/jetty/jmx/ConnectorServerTest.java index 661f34f696b..701027a12bd 100644 --- a/jetty-jmx/src/test/java/org/eclipse/jetty/jmx/ConnectorServerTest.java +++ b/jetty-jmx/src/test/java/org/eclipse/jetty/jmx/ConnectorServerTest.java @@ -24,7 +24,6 @@ import java.net.ServerSocket; import java.net.Socket; import java.util.HashMap; import java.util.Map; - import javax.management.remote.JMXConnector; import javax.management.remote.JMXConnectorFactory; import javax.management.remote.JMXServiceURL; @@ -83,7 +82,8 @@ public class ConnectorServerTest // Verify that I can connect to the RMI registry using a non-loopback address. new Socket(InetAddress.getLocalHost(), 1099).close(); - assertThrows(ConnectException.class, ()->{ + assertThrows(ConnectException.class, () -> + { // Verify that I cannot connect to the RMI registry using the loopback address. new Socket(InetAddress.getLoopbackAddress(), 1099).close(); }); @@ -100,7 +100,8 @@ public class ConnectorServerTest // Verify that I can connect to the RMI registry using a non-loopback address. new Socket(InetAddress.getLocalHost(), registryPort).close(); - assertThrows(ConnectException.class, ()->{ + assertThrows(ConnectException.class, () -> + { // Verify that I cannot connect to the RMI registry using the loopback address. new Socket(InetAddress.getLoopbackAddress(), registryPort).close(); }); @@ -130,7 +131,8 @@ public class ConnectorServerTest InetAddress localHost = InetAddress.getLocalHost(); if (!localHost.isLoopbackAddress()) { - assertThrows(ConnectException.class, ()->{ + assertThrows(ConnectException.class, () -> + { // Verify that I cannot connect to the RMIRegistry using a non-loopback address. new Socket(localHost, 1099); }); @@ -148,7 +150,8 @@ public class ConnectorServerTest // Verify that I can connect to the RMI server using a non-loopback address. new Socket(InetAddress.getLocalHost(), connectorServer.getAddress().getPort()).close(); - assertThrows(ConnectException.class, ()->{ + assertThrows(ConnectException.class, () -> + { // Verify that I cannot connect to the RMI server using the loopback address. new Socket(InetAddress.getLoopbackAddress(), connectorServer.getAddress().getPort()).close(); }); @@ -176,7 +179,8 @@ public class ConnectorServerTest InetAddress localHost = InetAddress.getLocalHost(); if (!localHost.isLoopbackAddress()) { - assertThrows(ConnectException.class, ()->{ + assertThrows(ConnectException.class, () -> + { // Verify that I cannot connect to the RMIRegistry using a non-loopback address. new Socket(localHost, address.getPort()); }); diff --git a/jetty-jmx/src/test/java/org/eclipse/jetty/jmx/MBeanContainerLifeCycleTest.java b/jetty-jmx/src/test/java/org/eclipse/jetty/jmx/MBeanContainerLifeCycleTest.java index c8fc3383798..94dd6fb6d38 100644 --- a/jetty-jmx/src/test/java/org/eclipse/jetty/jmx/MBeanContainerLifeCycleTest.java +++ b/jetty-jmx/src/test/java/org/eclipse/jetty/jmx/MBeanContainerLifeCycleTest.java @@ -18,21 +18,19 @@ package org.eclipse.jetty.jmx; -import static org.junit.jupiter.api.Assertions.assertEquals; - import java.lang.management.ManagementFactory; import java.util.Set; - import javax.management.MBeanServer; import javax.management.ObjectName; import org.eclipse.jetty.util.component.ContainerLifeCycle; import org.eclipse.jetty.util.thread.QueuedThreadPool; - import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; +import static org.junit.jupiter.api.Assertions.assertEquals; + public class MBeanContainerLifeCycleTest { private ContainerLifeCycle container; diff --git a/jetty-jmx/src/test/java/org/eclipse/jetty/jmx/MBeanContainerTest.java b/jetty-jmx/src/test/java/org/eclipse/jetty/jmx/MBeanContainerTest.java index 52c4624adc6..2b87fa53cfb 100644 --- a/jetty-jmx/src/test/java/org/eclipse/jetty/jmx/MBeanContainerTest.java +++ b/jetty-jmx/src/test/java/org/eclipse/jetty/jmx/MBeanContainerTest.java @@ -19,7 +19,6 @@ package org.eclipse.jetty.jmx; import java.lang.management.ManagementFactory; - import javax.management.MBeanServer; import javax.management.ObjectName; diff --git a/jetty-jmx/src/test/java/org/eclipse/jetty/jmx/ObjectMBeanTest.java b/jetty-jmx/src/test/java/org/eclipse/jetty/jmx/ObjectMBeanTest.java index 0e844c10399..51f6cce9c7a 100644 --- a/jetty-jmx/src/test/java/org/eclipse/jetty/jmx/ObjectMBeanTest.java +++ b/jetty-jmx/src/test/java/org/eclipse/jetty/jmx/ObjectMBeanTest.java @@ -19,7 +19,6 @@ package org.eclipse.jetty.jmx; import java.lang.management.ManagementFactory; - import javax.management.Attribute; import javax.management.MBeanInfo; import javax.management.MBeanOperationInfo; diff --git a/jetty-jmx/src/test/java/org/eclipse/jetty/jmx/ObjectMBeanUtilTest.java b/jetty-jmx/src/test/java/org/eclipse/jetty/jmx/ObjectMBeanUtilTest.java index b35480324d9..7a906b6a03e 100644 --- a/jetty-jmx/src/test/java/org/eclipse/jetty/jmx/ObjectMBeanUtilTest.java +++ b/jetty-jmx/src/test/java/org/eclipse/jetty/jmx/ObjectMBeanUtilTest.java @@ -21,7 +21,6 @@ package org.eclipse.jetty.jmx; import java.lang.management.ManagementFactory; import java.util.ArrayList; import java.util.Arrays; - import javax.management.Attribute; import javax.management.AttributeList; import javax.management.AttributeNotFoundException; @@ -165,7 +164,9 @@ public class ObjectMBeanUtilTest mBeanDerivedManagedContainer.beanAdded(null, derived0); Derived[] deriveds = new Derived[3]; for (int i = 0; i < 3; i++) + { deriveds[i] = new Derived(); + } derivedManaged.setAddresses(deriveds); mBeanDerivedManaged.getMBeanInfo(); ArrayList aliasNames = new ArrayList<>(Arrays.asList(deriveds)); @@ -222,7 +223,9 @@ public class ObjectMBeanUtilTest // DerivedMBean contains a managed method with the name good, // we must call this method without any arguments. ReflectionException e = assertThrows(ReflectionException.class, () -> - objectMBean.invoke("good", new Object[0], new String[]{"int aone"})); + objectMBean.invoke("good", new Object[0], new String[]{ + "int aone" + })); assertNotNull(e, "A ReflectionException must have occurred by now as we cannot call a method with wrong signature"); } diff --git a/jetty-jmx/src/test/java/org/eclipse/jetty/util/log/jmx/LogMBeanTest.java b/jetty-jmx/src/test/java/org/eclipse/jetty/util/log/jmx/LogMBeanTest.java index 2c322e40aaf..d3a5afaac9e 100644 --- a/jetty-jmx/src/test/java/org/eclipse/jetty/util/log/jmx/LogMBeanTest.java +++ b/jetty-jmx/src/test/java/org/eclipse/jetty/util/log/jmx/LogMBeanTest.java @@ -51,7 +51,7 @@ public class LogMBeanTest assertThat("Managed is not registered with loggers", MANAGED_CLASS, not(is(in(logMBean.getLoggers())))); // when - logMBean.setDebugEnabled(MANAGED_CLASS,true); + logMBean.setDebugEnabled(MANAGED_CLASS, true); // then assertThat("Managed must be registered with loggers", MANAGED_CLASS, is(in(logMBean.getLoggers()))); diff --git a/jetty-jndi/pom.xml b/jetty-jndi/pom.xml index fdf59c5640e..2442dd6f097 100644 --- a/jetty-jndi/pom.xml +++ b/jetty-jndi/pom.xml @@ -1,5 +1,4 @@ - + org.eclipse.jetty jetty-project @@ -24,7 +23,7 @@ true - javax.mail.*;resolution:=optional,* + javax.mail.*;resolution:=optional,* diff --git a/jetty-jndi/src/main/java/org/eclipse/jetty/jndi/BindingEnumeration.java b/jetty-jndi/src/main/java/org/eclipse/jetty/jndi/BindingEnumeration.java index d7ee1c6df90..41fe5550538 100644 --- a/jetty-jndi/src/main/java/org/eclipse/jetty/jndi/BindingEnumeration.java +++ b/jetty-jndi/src/main/java/org/eclipse/jetty/jndi/BindingEnumeration.java @@ -16,23 +16,21 @@ // ======================================================================== // - package org.eclipse.jetty.jndi; import java.util.Iterator; - import javax.naming.Binding; import javax.naming.NamingEnumeration; import javax.naming.NamingException; -/** +/** * BindingEnumeration */ public class BindingEnumeration implements NamingEnumeration { Iterator _delegate; - public BindingEnumeration (Iterator e) + public BindingEnumeration(Iterator e) { _delegate = e; } @@ -44,7 +42,7 @@ public class BindingEnumeration implements NamingEnumeration } @Override - public boolean hasMore () + public boolean hasMore() throws NamingException { return _delegate.hasNext(); @@ -55,7 +53,7 @@ public class BindingEnumeration implements NamingEnumeration throws NamingException { Binding b = (Binding)_delegate.next(); - return new Binding (b.getName(), b.getClassName(), b.getObject(), true); + return new Binding(b.getName(), b.getClassName(), b.getObject(), true); } @Override @@ -68,6 +66,6 @@ public class BindingEnumeration implements NamingEnumeration public Binding nextElement() { Binding b = (Binding)_delegate.next(); - return new Binding (b.getName(), b.getClassName(), b.getObject(),true); + return new Binding(b.getName(), b.getClassName(), b.getObject(), true); } } diff --git a/jetty-jndi/src/main/java/org/eclipse/jetty/jndi/ContextFactory.java b/jetty-jndi/src/main/java/org/eclipse/jetty/jndi/ContextFactory.java index c480b10152f..5d8c6b93831 100644 --- a/jetty-jndi/src/main/java/org/eclipse/jetty/jndi/ContextFactory.java +++ b/jetty-jndi/src/main/java/org/eclipse/jetty/jndi/ContextFactory.java @@ -35,8 +35,6 @@ import org.eclipse.jetty.util.component.Dumpable; import org.eclipse.jetty.util.log.Log; import org.eclipse.jetty.util.log.Logger; - - /** * ContextFactory *

    @@ -55,7 +53,7 @@ import org.eclipse.jetty.util.log.Logger; * we try looking at the thread context classloader if it is set, and walk its * hierarchy, creating a context if none is found. If the thread context classloader * is not set, then we use the classloader associated with the current Context. - *

    + *

    * If there is no current context, or no classloader, we return null. */ public class ContextFactory implements ObjectFactory @@ -72,9 +70,9 @@ public class ContextFactory implements ObjectFactory * instead of looking up the map. */ private static final ThreadLocal __threadContext = new ThreadLocal(); - + /** - * Threadlocal for setting a classloader which must be used + * Threadlocal for setting a classloader which must be used * when finding the comp context. */ private static final ThreadLocal __threadClassLoader = new ThreadLocal(); @@ -83,29 +81,30 @@ public class ContextFactory implements ObjectFactory * Find or create a context which pertains to a classloader. *

    * If the thread context classloader is set, we try to find an already-created naming context - * for it. If one does not exist, we walk its classloader hierarchy until one is found, or we + * for it. If one does not exist, we walk its classloader hierarchy until one is found, or we * run out of parent classloaders. In the latter case, we will create a new naming context associated * with the original thread context classloader. *

    - * If the thread context classloader is not set, we obtain the classloader from the current - * jetty Context, and look for an already-created naming context. + * If the thread context classloader is not set, we obtain the classloader from the current + * jetty Context, and look for an already-created naming context. *

    - * If there is no current jetty Context, or it has no associated classloader, we + * If there is no current jetty Context, or it has no associated classloader, we * return null. + * * @see javax.naming.spi.ObjectFactory#getObjectInstance(java.lang.Object, javax.naming.Name, javax.naming.Context, java.util.Hashtable) */ @Override - public Object getObjectInstance (Object obj, - Name name, - Context nameCtx, - Hashtable env) + public Object getObjectInstance(Object obj, + Name name, + Context nameCtx, + Hashtable env) throws Exception { //First, see if we have had a context injected into us to use. Context ctx = (Context)__threadContext.get(); if (ctx != null) { - if(LOG.isDebugEnabled()) + if (LOG.isDebugEnabled()) LOG.debug("Using the Context that is bound on the thread"); return ctx; } @@ -117,15 +116,15 @@ public class ContextFactory implements ObjectFactory { if (LOG.isDebugEnabled()) LOG.debug("Using threadlocal classloader"); - synchronized(__contextMap) + synchronized (__contextMap) { ctx = getContextForClassLoader(loader); if (ctx == null) { ctx = newNamingContext(obj, loader, env, name, nameCtx); - __contextMap.put (loader, ctx); - if(LOG.isDebugEnabled()) - LOG.debug("Made context {} for classloader {}",name.get(0),loader); + __contextMap.put(loader, ctx); + if (LOG.isDebugEnabled()) + LOG.debug("Made context {} for classloader {}", name.get(0), loader); } return ctx; } @@ -133,12 +132,12 @@ public class ContextFactory implements ObjectFactory //If the thread context classloader is set, then try its hierarchy to find a matching context ClassLoader tccl = Thread.currentThread().getContextClassLoader(); - loader = tccl; + loader = tccl; if (loader != null) { if (LOG.isDebugEnabled()) LOG.debug("Trying thread context classloader"); - synchronized(__contextMap) + synchronized (__contextMap) { while (ctx == null && loader != null) { @@ -150,31 +149,30 @@ public class ContextFactory implements ObjectFactory if (ctx == null) { ctx = newNamingContext(obj, tccl, env, name, nameCtx); - __contextMap.put (tccl, ctx); - if(LOG.isDebugEnabled()) + __contextMap.put(tccl, ctx); + if (LOG.isDebugEnabled()) LOG.debug("Made context {} for classloader {}", name.get(0), tccl); } return ctx; } } - //If trying thread context classloader hierarchy failed, try the //classloader associated with the current context if (ContextHandler.getCurrentContext() != null) { if (LOG.isDebugEnabled() && loader != null) LOG.debug("Trying classloader of current org.eclipse.jetty.server.handler.ContextHandler"); - synchronized(__contextMap) + synchronized (__contextMap) { loader = ContextHandler.getCurrentContext().getContextHandler().getClassLoader(); - ctx = (Context)__contextMap.get(loader); + ctx = (Context)__contextMap.get(loader); if (ctx == null && loader != null) { ctx = newNamingContext(obj, loader, env, name, nameCtx); - __contextMap.put (loader, ctx); - if(LOG.isDebugEnabled()) + __contextMap.put(loader, ctx); + if (LOG.isDebugEnabled()) LOG.debug("Made context {} for classloader {} ", name.get(0), loader); } @@ -184,9 +182,9 @@ public class ContextFactory implements ObjectFactory return null; } - /** * Create a new NamingContext. + * * @param obj the object to create * @param loader the classloader for the naming context * @param env the jndi env for the entry @@ -196,24 +194,25 @@ public class ContextFactory implements ObjectFactory * @throws Exception if unable to create a new naming context */ public NamingContext newNamingContext(Object obj, ClassLoader loader, Hashtable env, Name name, Context parentCtx) - throws Exception + throws Exception { Reference ref = (Reference)obj; StringRefAddr parserAddr = (StringRefAddr)ref.get("parser"); - String parserClassName = (parserAddr==null?null:(String)parserAddr.getContent()); + String parserClassName = (parserAddr == null ? null : (String)parserAddr.getContent()); NameParser parser = - (NameParser)(parserClassName==null? - null:loader.loadClass(parserClassName).getDeclaredConstructor().newInstance()); + (NameParser)(parserClassName == null + ? null + : loader.loadClass(parserClassName).getDeclaredConstructor().newInstance()); - return new NamingContext (env, - name.get(0), - (NamingContext)parentCtx, - parser); + return new NamingContext(env, + name.get(0), + (NamingContext)parentCtx, + parser); } - /** * Find the naming Context for the given classloader + * * @param loader the classloader for the context * @return the context for the classloader */ @@ -221,13 +220,14 @@ public class ContextFactory implements ObjectFactory { if (loader == null) return null; - + return (Context)__contextMap.get(loader); } /** * Associate the given Context with the current thread. * disassociate method should be called to reset the context. + * * @param ctx the context to associate to the current thread. * @return the previous context associated on the thread (can be null) */ @@ -242,15 +242,15 @@ public class ContextFactory implements ObjectFactory { __threadContext.set(null); } - + public static ClassLoader associateClassLoader(final ClassLoader loader) { ClassLoader prev = (ClassLoader)__threadClassLoader.get(); __threadClassLoader.set(loader); return prev; } - - public static void disassociateClassLoader () + + public static void disassociateClassLoader() { __threadClassLoader.set(null); } @@ -259,7 +259,7 @@ public class ContextFactory implements ObjectFactory { synchronized (__contextMap) { - Dumpable.dumpObjects(out, indent, String.format("o.e.j.jndi.ContextFactory@",__contextMap.hashCode()), __contextMap); + Dumpable.dumpObjects(out, indent, String.format("o.e.j.jndi.ContextFactory@", __contextMap.hashCode()), __contextMap); } } } diff --git a/jetty-jndi/src/main/java/org/eclipse/jetty/jndi/DataSourceCloser.java b/jetty-jndi/src/main/java/org/eclipse/jetty/jndi/DataSourceCloser.java index da6819fde8e..aba28bc3914 100644 --- a/jetty-jndi/src/main/java/org/eclipse/jetty/jndi/DataSourceCloser.java +++ b/jetty-jndi/src/main/java/org/eclipse/jetty/jndi/DataSourceCloser.java @@ -21,7 +21,6 @@ package org.eclipse.jetty.jndi; import java.lang.reflect.Method; import java.sql.Connection; import java.sql.Statement; - import javax.sql.DataSource; import org.eclipse.jetty.util.component.ContainerLifeCycle; @@ -34,7 +33,6 @@ import org.eclipse.jetty.util.log.Logger; * Some {@link DataSource}'s need to be close (eg. Atomikos). This bean is a {@link Destroyable} and * may be added to any {@link ContainerLifeCycle} so that {@link #destroy()} * will be called. The {@link #destroy()} method calls any no-arg method called "close" on the passed DataSource. - * */ public class DataSourceCloser implements Destroyable { @@ -45,18 +43,18 @@ public class DataSourceCloser implements Destroyable public DataSourceCloser(DataSource datasource) { - if (datasource==null) + if (datasource == null) throw new IllegalArgumentException(); - _datasource=datasource; - _shutdown=null; + _datasource = datasource; + _shutdown = null; } - public DataSourceCloser(DataSource datasource,String shutdownSQL) + public DataSourceCloser(DataSource datasource, String shutdownSQL) { - if (datasource==null) + if (datasource == null) throw new IllegalArgumentException(); - _datasource=datasource; - _shutdown=shutdownSQL; + _datasource = datasource; + _shutdown = shutdownSQL; } @Override @@ -64,11 +62,11 @@ public class DataSourceCloser implements Destroyable { try { - if (_shutdown!=null) + if (_shutdown != null) { - LOG.info("Shutdown datasource {}",_datasource); + LOG.info("Shutdown datasource {}", _datasource); try (Connection connection = _datasource.getConnection(); - Statement stmt = connection.createStatement()) + Statement stmt = connection.createStatement()) { stmt.executeUpdate(_shutdown); } @@ -82,7 +80,7 @@ public class DataSourceCloser implements Destroyable try { Method close = _datasource.getClass().getMethod("close", new Class[]{}); - LOG.info("Close datasource {}",_datasource); + LOG.info("Close datasource {}", _datasource); close.invoke(_datasource, new Object[]{}); } catch (Exception e) diff --git a/jetty-jndi/src/main/java/org/eclipse/jetty/jndi/InitialContextFactory.java b/jetty-jndi/src/main/java/org/eclipse/jetty/jndi/InitialContextFactory.java index 25355060333..3e232dda38a 100644 --- a/jetty-jndi/src/main/java/org/eclipse/jetty/jndi/InitialContextFactory.java +++ b/jetty-jndi/src/main/java/org/eclipse/jetty/jndi/InitialContextFactory.java @@ -30,15 +30,12 @@ import org.eclipse.jetty.jndi.local.localContextRoot; import org.eclipse.jetty.util.log.Log; import org.eclipse.jetty.util.log.Logger; - -/*------------------------------------------------*/ /** * InitialContextFactory.java * * Factory for the default InitialContext. * Created: Tue Jul 1 19:08:08 2003 * - * * @version 1.0 */ public class InitialContextFactory implements javax.naming.spi.InitialContextFactory @@ -48,41 +45,42 @@ public class InitialContextFactory implements javax.naming.spi.InitialContextFac public static class DefaultParser implements NameParser { static Properties syntax = new Properties(); + static { syntax.put("jndi.syntax.direction", "left_to_right"); syntax.put("jndi.syntax.separator", "/"); syntax.put("jndi.syntax.ignorecase", "false"); } + @Override - public Name parse (String name) + public Name parse(String name) throws NamingException { - return new CompoundName (name, syntax); + return new CompoundName(name, syntax); } - }; + } + ; - - /*------------------------------------------------*/ /** * Get Context that has access to default Namespace. * This method won't be called if a name URL beginning * with java: is passed to an InitialContext. * - * @see org.eclipse.jetty.jndi.java.javaURLContextFactory * @param env a Hashtable value * @return a Context value + * @see org.eclipse.jetty.jndi.java.javaURLContextFactory */ @Override public Context getInitialContext(Hashtable env) { - if(LOG.isDebugEnabled()) + if (LOG.isDebugEnabled()) LOG.debug("InitialContextFactory.getInitialContext()"); Context ctx = new localContextRoot(env); - if(LOG.isDebugEnabled()) - LOG.debug("Created initial context delegate for local namespace:"+ctx); + if (LOG.isDebugEnabled()) + LOG.debug("Created initial context delegate for local namespace:" + ctx); return ctx; } diff --git a/jetty-jndi/src/main/java/org/eclipse/jetty/jndi/NameEnumeration.java b/jetty-jndi/src/main/java/org/eclipse/jetty/jndi/NameEnumeration.java index ac2b758e7bb..ffba9bcd981 100644 --- a/jetty-jndi/src/main/java/org/eclipse/jetty/jndi/NameEnumeration.java +++ b/jetty-jndi/src/main/java/org/eclipse/jetty/jndi/NameEnumeration.java @@ -19,20 +19,19 @@ package org.eclipse.jetty.jndi; import java.util.Iterator; - import javax.naming.Binding; import javax.naming.NameClassPair; import javax.naming.NamingEnumeration; import javax.naming.NamingException; -/** +/** * NameEnumeration */ public class NameEnumeration implements NamingEnumeration { Iterator _delegate; - public NameEnumeration (Iterator e) + public NameEnumeration(Iterator e) { _delegate = e; } @@ -44,7 +43,7 @@ public class NameEnumeration implements NamingEnumeration } @Override - public boolean hasMore () + public boolean hasMore() throws NamingException { return _delegate.hasNext(); @@ -55,7 +54,7 @@ public class NameEnumeration implements NamingEnumeration throws NamingException { Binding b = _delegate.next(); - return new NameClassPair(b.getName(),b.getClassName(),true); + return new NameClassPair(b.getName(), b.getClassName(), true); } @Override @@ -68,6 +67,6 @@ public class NameEnumeration implements NamingEnumeration public NameClassPair nextElement() { Binding b = _delegate.next(); - return new NameClassPair(b.getName(),b.getClassName(),true); + return new NameClassPair(b.getName(), b.getClassName(), true); } } diff --git a/jetty-jndi/src/main/java/org/eclipse/jetty/jndi/NamingContext.java b/jetty-jndi/src/main/java/org/eclipse/jetty/jndi/NamingContext.java index d0f7271f297..94ebf286c9c 100644 --- a/jetty-jndi/src/main/java/org/eclipse/jetty/jndi/NamingContext.java +++ b/jetty-jndi/src/main/java/org/eclipse/jetty/jndi/NamingContext.java @@ -49,7 +49,7 @@ import org.eclipse.jetty.util.component.Dumpable; import org.eclipse.jetty.util.log.Log; import org.eclipse.jetty.util.log.Logger; -/** +/** * NamingContext *

    * Implementation of Context interface. @@ -61,7 +61,7 @@ import org.eclipse.jetty.util.log.Logger; public class NamingContext implements Context, Dumpable { private static final Logger LOG = Log.getLogger(NamingContext.class); - private final static List __empty = Collections.emptyList(); + private static final List __empty = Collections.emptyList(); public static final String DEEP_BINDING = "org.eclipse.jetty.jndi.deepBinding"; public static final String LOCK_PROPERTY = "org.eclipse.jetty.jndi.lock"; public static final String UNLOCK_PROPERTY = "org.eclipse.jetty.jndi.unlock"; @@ -72,7 +72,7 @@ public class NamingContext implements Context, Dumpable * of the {@link Context} javadoc), so multiple threads acting on the same * Context env need to self - mutually exclude. */ - protected final Hashtable _env = new Hashtable<>(); + protected final Hashtable _env = new Hashtable<>(); /* * This contexts bindings are stored as a ConcurrentHashMap. @@ -81,7 +81,7 @@ public class NamingContext implements Context, Dumpable * we do not mutually exclude when initializing, so instead we do make the bindings * thread safe (unlike the env where we expect users to respect the Concurrent Access requirements). */ - protected final ConcurrentMap _bindings; + protected final ConcurrentMap _bindings; protected NamingContext _parent = null; protected String _name = null; @@ -89,7 +89,6 @@ public class NamingContext implements Context, Dumpable private Collection _listeners; private Object _lock; - /*------------------------------------------------*/ /** * Naming Context Listener. */ @@ -98,6 +97,7 @@ public class NamingContext implements Context, Dumpable /** * Called by {@link NamingContext#addBinding(Name, Object)} when adding * a binding. + * * @param ctx The context to add to. * @param binding The binding to add. * @return The binding to bind, or null if the binding should be ignored. @@ -111,7 +111,6 @@ public class NamingContext implements Context, Dumpable void unbind(NamingContext ctx, Binding binding); } - /*------------------------------------------------*/ /** * Constructor * @@ -120,7 +119,7 @@ public class NamingContext implements Context, Dumpable * @param parent immediate ancestor Context (can be null) * @param parser NameParser for this Context */ - public NamingContext(Hashtable env, + public NamingContext(Hashtable env, String name, NamingContext parent, NameParser parser) @@ -128,19 +127,19 @@ public class NamingContext implements Context, Dumpable this(env, name, parent, parser, null); } - protected NamingContext(Hashtable env, - String name, - NamingContext parent, - NameParser parser, - ConcurrentMap bindings) + protected NamingContext(Hashtable env, + String name, + NamingContext parent, + NameParser parser, + ConcurrentMap bindings) { if (env != null) _env.putAll(env); _name = name; _parent = parent; _parser = parser; - _bindings = bindings==null ? new ConcurrentHashMap<>() : bindings; - if(LOG.isDebugEnabled()) + _bindings = bindings == null ? new ConcurrentHashMap<>() : bindings; + if (LOG.isDebugEnabled()) LOG.debug("new {}", this); } @@ -156,27 +155,25 @@ public class NamingContext implements Context, Dumpable { // look for deep binding support in _env Object support = _env.get(DEEP_BINDING); - if (support!=null) + if (support != null) return Boolean.parseBoolean(String.valueOf(support)); - if (_parent!=null) + if (_parent != null) return _parent.isDeepBindingSupported(); // probably a root context - return Boolean.parseBoolean(System.getProperty(DEEP_BINDING,"false")); + return Boolean.parseBoolean(System.getProperty(DEEP_BINDING, "false")); } - /*------------------------------------------------*/ /** * Getter for _name * * @return name of this Context (relative, not absolute) */ - public String getName () + public String getName() { return _name; } - /*------------------------------------------------*/ /** * Getter for _parent * @@ -187,13 +184,12 @@ public class NamingContext implements Context, Dumpable return _parent; } - /*------------------------------------------------*/ - public void setNameParser (NameParser parser) + public void setNameParser(NameParser parser) { _parser = parser; } - public final void setEnv (Hashtable env) + public final void setEnv(Hashtable env) { Object lock = _env.get(LOCK_PROPERTY); try @@ -205,7 +201,7 @@ public class NamingContext implements Context, Dumpable } finally { - if (lock!=null) + if (lock != null) _env.put(LOCK_PROPERTY, lock); } } @@ -225,8 +221,8 @@ public class NamingContext implements Context, Dumpable } catch (Exception e) { - LOG.warn("",e); - throw new NamingException (e.getMessage()); + LOG.warn("", e); + throw new NamingException(e.getMessage()); } } return ctx; @@ -239,7 +235,7 @@ public class NamingContext implements Context, Dumpable if (firstComponent.equals("")) return this; - Binding binding = getBinding (firstComponent); + Binding binding = getBinding(firstComponent); if (binding == null) { NameNotFoundException nnfe = new NameNotFoundException(firstComponent + " is not bound"); @@ -255,36 +251,33 @@ public class NamingContext implements Context, Dumpable return (Context)ctx; } - - /*------------------------------------------------*/ /** * Bind a name to an object * * @param name Name of the object * @param obj object to bind - * @exception NamingException if an error occurs + * @throws NamingException if an error occurs */ @Override public void bind(Name name, Object obj) throws NamingException { if (isLocked()) - throw new NamingException ("This context is immutable"); + throw new NamingException("This context is immutable"); Name cname = toCanonicalName(name); if (cname == null) - throw new NamingException ("Name is null"); + throw new NamingException("Name is null"); if (cname.size() == 0) - throw new NamingException ("Name is empty"); - + throw new NamingException("Name is empty"); //if no subcontexts, just bind it if (cname.size() == 1) { //get the object to be bound - Object objToBind = NamingManager.getStateToBind(obj, name,this, _env); + Object objToBind = NamingManager.getStateToBind(obj, name, this, _env); // Check for Referenceable if (objToBind instanceof Referenceable) { @@ -292,12 +285,12 @@ public class NamingContext implements Context, Dumpable } //anything else we should be able to bind directly - addBinding (cname, objToBind); + addBinding(cname, objToBind); } else { - if(LOG.isDebugEnabled()) - LOG.debug("Checking for existing binding for name="+cname+" for first element of name="+cname.get(0)); + if (LOG.isDebugEnabled()) + LOG.debug("Checking for existing binding for name=" + cname + " for first element of name=" + cname.get(0)); //walk down the subcontext hierarchy //need to ignore trailing empty "" name components @@ -309,14 +302,14 @@ public class NamingContext implements Context, Dumpable ctx = this; else { - Binding binding = getBinding (firstComponent); + Binding binding = getBinding(firstComponent); if (binding == null) { if (isDeepBindingSupported()) { Name subname = _parser.parse(firstComponent); - Context subctx = new NamingContext(_env,firstComponent,this,_parser, null); - addBinding(subname,subctx); + Context subctx = new NamingContext(_env, firstComponent, this, _parser, null); + addBinding(subname, subctx); binding = getBinding(subname); } else @@ -325,145 +318,132 @@ public class NamingContext implements Context, Dumpable } } - ctx = dereference(binding.getObject(),firstComponent); + ctx = dereference(binding.getObject(), firstComponent); } if (ctx instanceof Context) { - ((Context)ctx).bind (cname.getSuffix(1), obj); + ((Context)ctx).bind(cname.getSuffix(1), obj); } else - throw new NotContextException ("Object bound at "+firstComponent +" is not a Context"); + throw new NotContextException("Object bound at " + firstComponent + " is not a Context"); } } - - - /*------------------------------------------------*/ /** * Bind a name (as a String) to an object * * @param name a String value * @param obj an Object value - * @exception NamingException if an error occurs + * @throws NamingException if an error occurs */ @Override public void bind(String name, Object obj) throws NamingException { - bind (_parser.parse(name), obj); + bind(_parser.parse(name), obj); } - - /*------------------------------------------------*/ /** * Create a context as a child of this one * * @param name a Name value * @return a Context value - * @exception NamingException if an error occurs + * @throws NamingException if an error occurs */ @Override - public Context createSubcontext (Name name) + public Context createSubcontext(Name name) throws NamingException { if (isLocked()) { - NamingException ne = new NamingException ("This context is immutable"); + NamingException ne = new NamingException("This context is immutable"); ne.setRemainingName(name); throw ne; } - Name cname = toCanonicalName (name); + Name cname = toCanonicalName(name); if (cname == null) - throw new NamingException ("Name is null"); + throw new NamingException("Name is null"); if (cname.size() == 0) - throw new NamingException ("Name is empty"); + throw new NamingException("Name is empty"); if (cname.size() == 1) { //not permitted to bind if something already bound at that name - Binding binding = getBinding (cname); + Binding binding = getBinding(cname); if (binding != null) - throw new NameAlreadyBoundException (cname.toString()); + throw new NameAlreadyBoundException(cname.toString()); - Context ctx = new NamingContext (_env, cname.get(0), this, _parser); - addBinding (cname, ctx); + Context ctx = new NamingContext(_env, cname.get(0), this, _parser); + addBinding(cname, ctx); return ctx; } - return getContext(cname).createSubcontext (cname.getSuffix(1)); + return getContext(cname).createSubcontext(cname.getSuffix(1)); } - /*------------------------------------------------*/ /** * Create a Context as a child of this one * * @param name a String value * @return a Context value - * @exception NamingException if an error occurs + * @throws NamingException if an error occurs */ @Override - public Context createSubcontext (String name) + public Context createSubcontext(String name) throws NamingException { return createSubcontext(_parser.parse(name)); } - /*------------------------------------------------*/ /** - * - * * @param name name of subcontext to remove - * @exception NamingException if an error occurs + * @throws NamingException if an error occurs */ @Override - public void destroySubcontext (String name) + public void destroySubcontext(String name) throws NamingException { removeBinding(_parser.parse(name)); } - /*------------------------------------------------*/ /** - * - * * @param name name of subcontext to remove - * @exception NamingException if an error occurs + * @throws NamingException if an error occurs */ @Override - public void destroySubcontext (Name name) + public void destroySubcontext(Name name) throws NamingException { - removeBinding(name); + removeBinding(name); } - /*------------------------------------------------*/ /** * Lookup a binding by name * * @param name name of bound object - * @exception NamingException if an error occurs + * @throws NamingException if an error occurs */ @Override public Object lookup(Name name) throws NamingException { - if(LOG.isDebugEnabled()) - LOG.debug("Looking up name=\""+name+"\""); + if (LOG.isDebugEnabled()) + LOG.debug("Looking up name=\"" + name + "\""); Name cname = toCanonicalName(name); if ((cname == null) || (cname.size() == 0)) { - if(LOG.isDebugEnabled()) + if (LOG.isDebugEnabled()) LOG.debug("Null or empty name, returning shallowCopy of this context"); return shallowCopy(_env); } if (cname.size() == 1) { - Binding binding = getBinding (cname); + Binding binding = getBinding(cname); if (binding == null) { NameNotFoundException nnfe = new NameNotFoundException(); @@ -479,12 +459,12 @@ public class NamingContext implements Context, Dumpable //if link name starts with ./ it is relative to current context String linkName = ((LinkRef)o).getLinkName(); if (linkName.startsWith("./")) - return this.lookup (linkName.substring(2)); + return this.lookup(linkName.substring(2)); else { //link name is absolute InitialContext ictx = new InitialContext(); - return ictx.lookup (linkName); + return ictx.lookup(linkName); } } else if (o instanceof Reference) @@ -500,42 +480,40 @@ public class NamingContext implements Context, Dumpable } catch (Exception e) { - LOG.warn("",e); - throw new NamingException (e.getMessage()); + LOG.warn("", e); + throw new NamingException(e.getMessage()); } } else return o; } - return getContext(cname).lookup (cname.getSuffix(1)); + return getContext(cname).lookup(cname.getSuffix(1)); } - /*------------------------------------------------*/ /** * Lookup binding of an object by name * * @param name name of bound object * @return object bound to name - * @exception NamingException if an error occurs + * @throws NamingException if an error occurs */ @Override - public Object lookup (String name) + public Object lookup(String name) throws NamingException { - return lookup (_parser.parse(name)); + return lookup(_parser.parse(name)); } - /*------------------------------------------------*/ /** * Lookup link bound to name * * @param name name of link binding * @return LinkRef or plain object bound at name - * @exception NamingException if an error occurs + * @throws NamingException if an error occurs */ @Override - public Object lookupLink (Name name) + public Object lookupLink(Name name) throws NamingException { Name cname = toCanonicalName(name); @@ -546,49 +524,47 @@ public class NamingContext implements Context, Dumpable } if (cname.size() == 0) - throw new NamingException ("Name is empty"); + throw new NamingException("Name is empty"); if (cname.size() == 1) { - Binding binding = getBinding (cname); + Binding binding = getBinding(cname); if (binding == null) throw new NameNotFoundException(); return dereference(binding.getObject(), cname.getPrefix(1).toString()); } - return getContext(cname).lookup (cname.getSuffix(1)); + return getContext(cname).lookup(cname.getSuffix(1)); } - /*------------------------------------------------*/ /** * Lookup link bound to name * * @param name name of link binding * @return LinkRef or plain object bound at name - * @exception NamingException if an error occurs + * @throws NamingException if an error occurs */ @Override - public Object lookupLink (String name) + public Object lookupLink(String name) throws NamingException { - return lookupLink (_parser.parse(name)); + return lookupLink(_parser.parse(name)); } - /*------------------------------------------------*/ /** * List all names bound at Context named by Name * * @param name a Name value * @return a NamingEnumeration value - * @exception NamingException if an error occurs + * @throws NamingException if an error occurs */ @Override public NamingEnumeration list(Name name) throws NamingException { - if(LOG.isDebugEnabled()) - LOG.debug("list() on Context="+getName()+" for name="+name); + if (LOG.isDebugEnabled()) + LOG.debug("list() on Context=" + getName() + " for name=" + name); Name cname = toCanonicalName(name); if (cname == null) @@ -598,20 +574,19 @@ public class NamingContext implements Context, Dumpable if (cname.size() == 0) { - return new NameEnumeration (_bindings.values().iterator()); + return new NameEnumeration(_bindings.values().iterator()); } //multipart name - return getContext(cname).list (cname.getSuffix(1)); + return getContext(cname).list(cname.getSuffix(1)); } - /*------------------------------------------------*/ /** * List all names bound at Context named by Name * * @param name a Name value * @return a NamingEnumeration value - * @exception NamingException if an error occurs + * @throws NamingException if an error occurs */ @Override public NamingEnumeration list(String name) @@ -620,19 +595,18 @@ public class NamingContext implements Context, Dumpable return list(_parser.parse(name)); } - /*------------------------------------------------*/ /** * List all Bindings present at Context named by Name * * @param name a Name value * @return a NamingEnumeration value - * @exception NamingException if an error occurs + * @throws NamingException if an error occurs */ @Override public NamingEnumeration listBindings(Name name) throws NamingException { - Name cname = toCanonicalName (name); + Name cname = toCanonicalName(name); if (cname == null) { @@ -641,37 +615,32 @@ public class NamingContext implements Context, Dumpable if (cname.size() == 0) { - return new BindingEnumeration (_bindings.values().iterator()); + return new BindingEnumeration(_bindings.values().iterator()); } - return getContext(cname).listBindings (cname.getSuffix(1)); + return getContext(cname).listBindings(cname.getSuffix(1)); } - - - /*------------------------------------------------*/ /** * List all Bindings at Name * * @param name a String value * @return a NamingEnumeration value - * @exception NamingException if an error occurs + * @throws NamingException if an error occurs */ @Override public NamingEnumeration listBindings(String name) throws NamingException { - return listBindings (_parser.parse(name)); + return listBindings(_parser.parse(name)); } - - /*------------------------------------------------*/ /** * Overwrite or create a binding * * @param name a Name value * @param obj an Object value - * @exception NamingException if an error occurs + * @throws NamingException if an error occurs */ @Override public void rebind(Name name, @@ -679,16 +648,15 @@ public class NamingContext implements Context, Dumpable throws NamingException { if (isLocked()) - throw new NamingException ("This context is immutable"); + throw new NamingException("This context is immutable"); Name cname = toCanonicalName(name); if (cname == null) - throw new NamingException ("Name is null"); + throw new NamingException("Name is null"); if (cname.size() == 0) - throw new NamingException ("Name is empty"); - + throw new NamingException("Name is empty"); //if no subcontexts, just bind it if (cname.size() == 1) @@ -701,89 +669,83 @@ public class NamingContext implements Context, Dumpable objToBind = ((Referenceable)objToBind).getReference(); } removeBinding(cname); - addBinding (cname, objToBind); + addBinding(cname, objToBind); } else { - getContext(cname).rebind (cname.getSuffix(1), obj); + getContext(cname).rebind(cname.getSuffix(1), obj); } } - - /*------------------------------------------------*/ /** * Overwrite or create a binding from Name to Object * * @param name a String value * @param obj an Object value - * @exception NamingException if an error occurs + * @throws NamingException if an error occurs */ @Override - public void rebind (String name, - Object obj) + public void rebind(String name, + Object obj) throws NamingException { - rebind (_parser.parse(name), obj); + rebind(_parser.parse(name), obj); } - /*------------------------------------------------*/ /** * Not supported. * * @param name a String value - * @exception NamingException if an error occurs + * @throws NamingException if an error occurs */ @Override - public void unbind (String name) + public void unbind(String name) throws NamingException { unbind(_parser.parse(name)); } - /*------------------------------------------------*/ /** * Not supported. * * @param name a String value - * @exception NamingException if an error occurs + * @throws NamingException if an error occurs */ @Override - public void unbind (Name name) + public void unbind(Name name) throws NamingException { if (name.size() == 0) return; - if (isLocked()) - throw new NamingException ("This context is immutable"); + throw new NamingException("This context is immutable"); Name cname = toCanonicalName(name); if (cname == null) - throw new NamingException ("Name is null"); + throw new NamingException("Name is null"); if (cname.size() == 0) - throw new NamingException ("Name is empty"); + throw new NamingException("Name is empty"); //if no subcontexts, just unbind it if (cname.size() == 1) { - removeBinding (cname); + removeBinding(cname); } else { - getContext(cname).unbind (cname.getSuffix(1)); + getContext(cname).unbind(cname.getSuffix(1)); } } - /*------------------------------------------------*/ /** * Not supported * * @param oldName a Name value * @param newName a Name value - * @exception NamingException if an error occurs + * @throws NamingException if an error occurs */ @Override public void rename(Name oldName, @@ -793,33 +755,29 @@ public class NamingContext implements Context, Dumpable throw new OperationNotSupportedException(); } - - /*------------------------------------------------*/ /** * Not supported * * @param oldName a Name value * @param newName a Name value - * @exception NamingException if an error occurs - */ - @Override - public void rename(String oldName, - String newName) - throws NamingException - { - throw new OperationNotSupportedException(); - } + * @throws NamingException if an error occurs + */ + @Override + public void rename(String oldName, + String newName) + throws NamingException + { + throw new OperationNotSupportedException(); + } - - - /*------------------------------------------------*/ - /** Join two names together. These are treated as + /** + * Join two names together. These are treated as * CompoundNames. * * @param name a Name value * @param prefix a Name value * @return a Name value - * @exception NamingException if an error occurs + * @throws NamingException if an error occurs */ @Override public Name composeName(Name name, @@ -827,56 +785,50 @@ public class NamingContext implements Context, Dumpable throws NamingException { if (name == null) - throw new NamingException ("Name cannot be null"); + throw new NamingException("Name cannot be null"); if (prefix == null) - throw new NamingException ("Prefix cannot be null"); + throw new NamingException("Prefix cannot be null"); Name compoundName = (CompoundName)prefix.clone(); - compoundName.addAll (name); + compoundName.addAll(name); return compoundName; } - - - /*------------------------------------------------*/ - /** Join two names together. These are treated as + /** + * Join two names together. These are treated as * CompoundNames. * * @param name a Name value * @param prefix a Name value * @return a Name value - * @exception NamingException if an error occurs + * @throws NamingException if an error occurs */ @Override - public String composeName (String name, - String prefix) + public String composeName(String name, + String prefix) throws NamingException { if (name == null) - throw new NamingException ("Name cannot be null"); + throw new NamingException("Name cannot be null"); if (prefix == null) - throw new NamingException ("Prefix cannot be null"); + throw new NamingException("Prefix cannot be null"); Name compoundName = _parser.parse(prefix); - compoundName.add (name); + compoundName.add(name); return compoundName.toString(); } - - /*------------------------------------------------*/ /** * Do nothing * - * @exception NamingException if an error occurs + * @throws NamingException if an error occurs */ @Override - public void close () + public void close() throws NamingException { } - - /*------------------------------------------------*/ /** * Return a NameParser for this Context. * @@ -884,12 +836,11 @@ public class NamingContext implements Context, Dumpable * @return a NameParser value */ @Override - public NameParser getNameParser (Name name) + public NameParser getNameParser(Name name) { return _parser; } - /*------------------------------------------------*/ /** * Return a NameParser for this Context. * @@ -897,12 +848,11 @@ public class NamingContext implements Context, Dumpable * @return a NameParser value */ @Override - public NameParser getNameParser (String name) + public NameParser getNameParser(String name) { return _parser; } - /*------------------------------------------------*/ /** * Get the full name of this Context node * by visiting it's ancestors back to root. @@ -911,10 +861,10 @@ public class NamingContext implements Context, Dumpable * the URL prefix will be missing * * @return the full name of this Context - * @exception NamingException if an error occurs + * @throws NamingException if an error occurs */ @Override - public String getNameInNamespace () + public String getNameInNamespace() throws NamingException { Name name = _parser.parse(""); @@ -930,21 +880,20 @@ public class NamingContext implements Context, Dumpable return name.toString(); } - /*------------------------------------------------*/ /** * Add an environment setting to this Context * * @param propName name of the property to add * @param propVal value of the property to add * @return propVal or previous value of the property - * @exception NamingException if an error occurs + * @throws NamingException if an error occurs */ @Override public Object addToEnvironment(String propName, Object propVal) throws NamingException { - switch(propName) + switch (propName) { case LOCK_PROPERTY: if (_lock == null) @@ -963,38 +912,34 @@ public class NamingContext implements Context, Dumpable } } - /*------------------------------------------------*/ /** * Remove a property from this Context's environment. * * @param propName name of property to remove * @return value of property or null if it didn't exist - * @exception NamingException if an error occurs + * @throws NamingException if an error occurs */ @Override public Object removeFromEnvironment(String propName) throws NamingException { if (isLocked()) - throw new NamingException ("This context is immutable"); + throw new NamingException("This context is immutable"); - return _env.remove (propName); + return _env.remove(propName); } - - /*------------------------------------------------*/ /** * Get the environment of this Context. * * @return a copy of the environment of this Context. */ @Override - public Hashtable getEnvironment () + public Hashtable getEnvironment() { return _env; } - /*------------------------------------------------*/ /** * Add a name to object binding to this Context. * @@ -1002,28 +947,28 @@ public class NamingContext implements Context, Dumpable * @param obj an Object value * @throws NameAlreadyBoundException if name already bound */ - public void addBinding (Name name, Object obj) throws NameAlreadyBoundException + public void addBinding(Name name, Object obj) throws NameAlreadyBoundException { String key = name.toString(); - Binding binding=new Binding (key, obj); + Binding binding = new Binding(key, obj); Collection list = findListeners(); for (Listener listener : list) { - binding=listener.bind(this,binding); - if (binding==null) + binding = listener.bind(this, binding); + if (binding == null) break; } - if(LOG.isDebugEnabled()) - LOG.debug("Adding binding with key="+key+" obj="+obj+" for context="+_name+" as "+binding); + if (LOG.isDebugEnabled()) + LOG.debug("Adding binding with key=" + key + " obj=" + obj + " for context=" + _name + " as " + binding); - if (binding!=null) + if (binding != null) { - if (_bindings.putIfAbsent(key, binding)!=null) + if (_bindings.putIfAbsent(key, binding) != null) { - if(isDeepBindingSupported()) + if (isDeepBindingSupported()) { // quietly return (no exception) // this is jndi spec breaking, but is added to support broken @@ -1035,46 +980,44 @@ public class NamingContext implements Context, Dumpable } } - /*------------------------------------------------*/ /** * Get a name to object binding from this Context * * @param name a Name value * @return a Binding value */ - public Binding getBinding (Name name) + public Binding getBinding(Name name) { return _bindings.get(name.toString()); } - /*------------------------------------------------*/ /** * Get a name to object binding from this Context * * @param name as a String * @return null or the Binding */ - public Binding getBinding (String name) + public Binding getBinding(String name) { return _bindings.get(name); } - /*------------------------------------------------*/ - public void removeBinding (Name name) + public void removeBinding(Name name) { String key = name.toString(); if (LOG.isDebugEnabled()) - LOG.debug("Removing binding with key="+key); + LOG.debug("Removing binding with key=" + key); Binding binding = _bindings.remove(key); - if (binding!=null) + if (binding != null) { Collection list = findListeners(); for (Listener listener : list) - listener.unbind(this,binding); + { + listener.unbind(this, binding); + } } } - /*------------------------------------------------*/ /** * Remove leading or trailing empty components from * name. Eg "/comp/env/" -> "comp/env" @@ -1082,7 +1025,7 @@ public class NamingContext implements Context, Dumpable * @param name the name to normalize * @return normalized name */ - public Name toCanonicalName (Name name) + public Name toCanonicalName(Name name) { Name canonicalName = name; @@ -1093,35 +1036,34 @@ public class NamingContext implements Context, Dumpable if (canonicalName.get(0).equals("")) canonicalName = canonicalName.getSuffix(1); - if (canonicalName.get(canonicalName.size()-1).equals("")) - canonicalName = canonicalName.getPrefix(canonicalName.size()-1); + if (canonicalName.get(canonicalName.size() - 1).equals("")) + canonicalName = canonicalName.getPrefix(canonicalName.size() - 1); } } return canonicalName; } - /* ------------------------------------------------------------ */ public boolean isLocked() { //TODO lock whole hierarchy? return _lock != null; } - /* ------------------------------------------------------------ */ @Override public String dump() { return Dumpable.dump(this); } - /* ------------------------------------------------------------ */ @Override - public void dump(Appendable out,String indent) throws IOException + public void dump(Appendable out, String indent) throws IOException { Map bindings = new HashMap<>(); - for (Map.Entry binding : _bindings.entrySet()) + for (Map.Entry binding : _bindings.entrySet()) + { bindings.put(binding.getKey(), binding.getValue().getObject()); + } Dumpable.dumpObject(out, this); Dumpable.dumpMapEntries(out, indent, bindings, _env.isEmpty()); @@ -1135,20 +1077,20 @@ public class NamingContext implements Context, Dumpable private Collection findListeners() { Collection list = new ArrayList(); - NamingContext ctx=this; - while (ctx!=null) + NamingContext ctx = this; + while (ctx != null) { - if (ctx._listeners!=null) + if (ctx._listeners != null) list.addAll(ctx._listeners); - ctx=(NamingContext)ctx.getParent(); + ctx = (NamingContext)ctx.getParent(); } return list; } public void addListener(Listener listener) { - if (_listeners==null) - _listeners=new ArrayList(); + if (_listeners == null) + _listeners = new ArrayList(); _listeners.add(listener); } @@ -1156,7 +1098,7 @@ public class NamingContext implements Context, Dumpable { return _listeners.remove(listener); } - + @Override public String toString() { diff --git a/jetty-jndi/src/main/java/org/eclipse/jetty/jndi/NamingUtil.java b/jetty-jndi/src/main/java/org/eclipse/jetty/jndi/NamingUtil.java index 47b5a404b26..b7591c247cc 100644 --- a/jetty-jndi/src/main/java/org/eclipse/jetty/jndi/NamingUtil.java +++ b/jetty-jndi/src/main/java/org/eclipse/jetty/jndi/NamingUtil.java @@ -31,7 +31,6 @@ import javax.naming.NamingException; import org.eclipse.jetty.util.log.Log; import org.eclipse.jetty.util.log.Logger; - /** * Naming Utility Methods */ @@ -39,7 +38,6 @@ public class NamingUtil { private static final Logger LOG = Log.getLogger(NamingUtil.class); - /* ------------------------------------------------------------ */ /** * Bind an object to a context ensuring all sub-contexts * are created if necessary @@ -48,9 +46,9 @@ public class NamingUtil * @param nameStr the name relative to context to bind * @param obj the object to be bound * @return the bound context - * @exception NamingException if an error occurs + * @throws NamingException if an error occurs */ - public static Context bind (Context ctx, String nameStr, Object obj) + public static Context bind(Context ctx, String nameStr, Object obj) throws NamingException { Name name = ctx.getNameParser("").parse(nameStr); @@ -62,30 +60,30 @@ public class NamingUtil Context subCtx = ctx; //last component of the name will be the name to bind - for (int i=0; i < name.size() - 1; i++) + for (int i = 0; i < name.size() - 1; i++) { try { - subCtx = (Context)subCtx.lookup (name.get(i)); - if(LOG.isDebugEnabled()) - LOG.debug("Subcontext "+name.get(i)+" already exists"); + subCtx = (Context)subCtx.lookup(name.get(i)); + if (LOG.isDebugEnabled()) + LOG.debug("Subcontext " + name.get(i) + " already exists"); } catch (NameNotFoundException e) { subCtx = subCtx.createSubcontext(name.get(i)); - if(LOG.isDebugEnabled()) - LOG.debug("Subcontext "+name.get(i)+" created"); + if (LOG.isDebugEnabled()) + LOG.debug("Subcontext " + name.get(i) + " created"); } } - subCtx.rebind (name.get(name.size() - 1), obj); - if(LOG.isDebugEnabled()) - LOG.debug("Bound object to "+name.get(name.size() - 1)); + subCtx.rebind(name.get(name.size() - 1), obj); + if (LOG.isDebugEnabled()) + LOG.debug("Bound object to " + name.get(name.size() - 1)); return subCtx; } - public static void unbind (Context ctx) - throws NamingException + public static void unbind(Context ctx) + throws NamingException { //unbind everything in the context and all of its subdirectories NamingEnumeration ne = ctx.listBindings(ctx.getNameInNamespace()); @@ -104,18 +102,19 @@ public class NamingUtil /** * Do a deep listing of the bindings for a context. + * * @param ctx the context containing the name for which to list the bindings * @param name the name in the context to list * @return map: key is fully qualified name, value is the bound object * @throws NamingException if unable to flatten bindings */ - public static Map flattenBindings (Context ctx, String name) - throws NamingException + public static Map flattenBindings(Context ctx, String name) + throws NamingException { HashMap map = new HashMap(); //the context representation of name arg - Context c = (Context)ctx.lookup (name); + Context c = (Context)ctx.lookup(name); NameParser parser = c.getNameParser(""); NamingEnumeration enm = ctx.listBindings(name); while (enm.hasMore()) @@ -124,18 +123,16 @@ public class NamingUtil if (b.getObject() instanceof Context) { - map.putAll(flattenBindings (c, b.getName())); + map.putAll(flattenBindings(c, b.getName())); } else { - Name compoundName = parser.parse (c.getNameInNamespace()); + Name compoundName = parser.parse(c.getNameInNamespace()); compoundName.add(b.getName()); - map.put (compoundName.toString(), b.getObject()); + map.put(compoundName.toString(), b.getObject()); } - } return map; } - } diff --git a/jetty-jndi/src/main/java/org/eclipse/jetty/jndi/factories/MailSessionReference.java b/jetty-jndi/src/main/java/org/eclipse/jetty/jndi/factories/MailSessionReference.java index cd28060123e..5275f88f09d 100644 --- a/jetty-jndi/src/main/java/org/eclipse/jetty/jndi/factories/MailSessionReference.java +++ b/jetty-jndi/src/main/java/org/eclipse/jetty/jndi/factories/MailSessionReference.java @@ -18,13 +18,11 @@ package org.eclipse.jetty.jndi.factories; - import java.util.Enumeration; import java.util.Hashtable; import java.util.Iterator; import java.util.Map; import java.util.Properties; - import javax.mail.Authenticator; import javax.mail.PasswordAuthentication; import javax.mail.Session; @@ -47,12 +45,10 @@ import org.eclipse.jetty.util.security.Password; * reference is bound into JNDI and it is only when the reference is looked up that * this object factory will create an instance of javax.mail.Session using the * information captured in the Reference. - * */ public class MailSessionReference extends Reference implements ObjectFactory { - public static class PasswordAuthenticator extends Authenticator { PasswordAuthentication passwordAuthentication; @@ -66,7 +62,7 @@ public class MailSessionReference extends Reference implements ObjectFactory public PasswordAuthenticator(String user, String password) { - passwordAuthentication = new PasswordAuthentication (user, (password.startsWith(Password.__OBFUSCATE)?Password.deobfuscate(password):password)); + passwordAuthentication = new PasswordAuthentication(user, (password.startsWith(Password.__OBFUSCATE) ? Password.deobfuscate(password) : password)); } @Override @@ -75,16 +71,17 @@ public class MailSessionReference extends Reference implements ObjectFactory return passwordAuthentication; } - public void setUser (String user) + public void setUser(String user) { this.user = user; } - public String getUser () + + public String getUser() { return this.user; } - public String getPassword () + public String getPassword() { return this.password; } @@ -93,33 +90,34 @@ public class MailSessionReference extends Reference implements ObjectFactory { this.password = password; } - }; + } + + ; public MailSessionReference() { - super ("javax.mail.Session", MailSessionReference.class.getName(), null); + super("javax.mail.Session", MailSessionReference.class.getName(), null); } - /** * Create a javax.mail.Session instance based on the information passed in the Reference - * @see javax.naming.spi.ObjectFactory#getObjectInstance(java.lang.Object, javax.naming.Name, javax.naming.Context, java.util.Hashtable) + * * @param ref the Reference * @param arg1 not used * @param arg2 not used * @param arg3 not used * @return the object found * @throws Exception if unable to get object instance + * @see javax.naming.spi.ObjectFactory#getObjectInstance(java.lang.Object, javax.naming.Name, javax.naming.Context, java.util.Hashtable) */ @Override public Object getObjectInstance(Object ref, Name arg1, Context arg2, Hashtable arg3) throws Exception { if (ref == null) - return null; + return null; Reference reference = (Reference)ref; - Properties props = new Properties(); String user = null; String password = null; @@ -129,7 +127,7 @@ public class MailSessionReference extends Reference implements ObjectFactory { RefAddr refAddr = (RefAddr)refs.nextElement(); String name = refAddr.getType(); - String value = (String)refAddr.getContent(); + String value = (String)refAddr.getContent(); if (name.equalsIgnoreCase("user")) user = value; else if (name.equalsIgnoreCase("pwd")) @@ -144,26 +142,25 @@ public class MailSessionReference extends Reference implements ObjectFactory return Session.getInstance(props, new PasswordAuthenticator(user, password)); } - - public void setUser (String user) + public void setUser(String user) { - StringRefAddr addr = (StringRefAddr)get("user"); - if (addr != null) - { - throw new RuntimeException ("user already set on SessionReference, can't be changed"); - } - add(new StringRefAddr("user", user)); + StringRefAddr addr = (StringRefAddr)get("user"); + if (addr != null) + { + throw new RuntimeException("user already set on SessionReference, can't be changed"); + } + add(new StringRefAddr("user", user)); } - public void setPassword (String password) + public void setPassword(String password) { StringRefAddr addr = (StringRefAddr)get("pwd"); if (addr != null) - throw new RuntimeException ("password already set on SessionReference, can't be changed"); - add(new StringRefAddr ("pwd", password)); + throw new RuntimeException("password already set on SessionReference, can't be changed"); + add(new StringRefAddr("pwd", password)); } - public void setProperties (Properties properties) + public void setProperties(Properties properties) { Iterator entries = properties.entrySet().iterator(); while (entries.hasNext()) @@ -171,11 +168,8 @@ public class MailSessionReference extends Reference implements ObjectFactory Map.Entry e = (Map.Entry)entries.next(); StringRefAddr sref = (StringRefAddr)get((String)e.getKey()); if (sref != null) - throw new RuntimeException ("property "+e.getKey()+" already set on Session reference, can't be changed"); + throw new RuntimeException("property " + e.getKey() + " already set on Session reference, can't be changed"); add(new StringRefAddr((String)e.getKey(), (String)e.getValue())); } } - - - } diff --git a/jetty-jndi/src/main/java/org/eclipse/jetty/jndi/java/javaNameParser.java b/jetty-jndi/src/main/java/org/eclipse/jetty/jndi/java/javaNameParser.java index 08d165c2d1e..c0c703ad0e0 100644 --- a/jetty-jndi/src/main/java/org/eclipse/jetty/jndi/java/javaNameParser.java +++ b/jetty-jndi/src/main/java/org/eclipse/jetty/jndi/java/javaNameParser.java @@ -19,16 +19,16 @@ package org.eclipse.jetty.jndi.java; import java.util.Properties; - import javax.naming.CompoundName; import javax.naming.Name; import javax.naming.NameParser; import javax.naming.NamingException; +// This is a required name for JNDI +// @checkstyle-disable-check : TypeNameCheck /** * javaNameParser - * */ public class javaNameParser implements NameParser { @@ -37,22 +37,22 @@ public class javaNameParser implements NameParser static { - syntax.put("jndi.syntax.direction", "left_to_right"); - syntax.put("jndi.syntax.separator", "/"); - syntax.put("jndi.syntax.ignorecase", "false"); + syntax.put("jndi.syntax.direction", "left_to_right"); + syntax.put("jndi.syntax.separator", "/"); + syntax.put("jndi.syntax.ignorecase", "false"); } - /** - * Parse a name into its components. - * @param name The non-null string name to parse. - * @return A non-null parsed form of the name using the naming convention - * of this parser. - * @exception NamingException If a naming exception was encountered. - */ - @Override - public Name parse(String name) throws NamingException - { - return new CompoundName(name, syntax); - } - + /** + * Parse a name into its components. + * + * @param name The non-null string name to parse. + * @return A non-null parsed form of the name using the naming convention + * of this parser. + * @throws NamingException If a naming exception was encountered. + */ + @Override + public Name parse(String name) throws NamingException + { + return new CompoundName(name, syntax); + } } diff --git a/jetty-jndi/src/main/java/org/eclipse/jetty/jndi/java/javaRootURLContext.java b/jetty-jndi/src/main/java/org/eclipse/jetty/jndi/java/javaRootURLContext.java index 2d5b5117feb..674528b2d70 100644 --- a/jetty-jndi/src/main/java/org/eclipse/jetty/jndi/java/javaRootURLContext.java +++ b/jetty-jndi/src/main/java/org/eclipse/jetty/jndi/java/javaRootURLContext.java @@ -32,10 +32,10 @@ import org.eclipse.jetty.jndi.NamingContext; import org.eclipse.jetty.util.log.Log; import org.eclipse.jetty.util.log.Logger; +// This is a required name for JNDI +// @checkstyle-disable-check : TypeNameCheck - - -/** +/** * javaRootURLContext *

    * This is the root of the java: url namespace @@ -54,23 +54,22 @@ public class javaRootURLContext implements Context protected static NameParser __javaNameParser; - static { try { __javaNameParser = new javaNameParser(); - __nameRoot = new NamingContext(null,null,null,__javaNameParser); + __nameRoot = new NamingContext(null, null, null, __javaNameParser); StringRefAddr parserAddr = new StringRefAddr("parser", __javaNameParser.getClass().getName()); - Reference ref = new Reference ("javax.naming.Context", - parserAddr, - ContextFactory.class.getName(), - (String)null); + Reference ref = new Reference("javax.naming.Context", + parserAddr, + ContextFactory.class.getName(), + (String)null); // bind special object factory at comp - __nameRoot.bind ("comp", ref); + __nameRoot.bind("comp", ref); } catch (Exception e) { @@ -78,9 +77,6 @@ public class javaRootURLContext implements Context } } - - - /*------------------------------------------------*/ /** * Creates a new javaRootURLContext instance. * @@ -98,7 +94,6 @@ public class javaRootURLContext implements Context return getRoot().lookup(stripProtocol(name)); } - @Override public Object lookup(String name) throws NamingException @@ -121,93 +116,89 @@ public class javaRootURLContext implements Context } @Override - public void unbind (String name) + public void unbind(String name) throws NamingException { getRoot().unbind(stripProtocol(name)); } @Override - public void unbind (Name name) + public void unbind(Name name) throws NamingException { getRoot().unbind(stripProtocol(name)); } @Override - public void rename (String oldStr, String newStr) + public void rename(String oldStr, String newStr) throws NamingException { - getRoot().rename (stripProtocol(oldStr), stripProtocol(newStr)); + getRoot().rename(stripProtocol(oldStr), stripProtocol(newStr)); } @Override - public void rename (Name oldName, Name newName) + public void rename(Name oldName, Name newName) throws NamingException { - getRoot().rename (stripProtocol(oldName), stripProtocol(newName)); + getRoot().rename(stripProtocol(oldName), stripProtocol(newName)); } @Override - public void rebind (Name name, Object obj) + public void rebind(Name name, Object obj) throws NamingException { getRoot().rebind(stripProtocol(name), obj); } @Override - public void rebind (String name, Object obj) + public void rebind(String name, Object obj) throws NamingException { getRoot().rebind(stripProtocol(name), obj); } - @Override - public Object lookupLink (Name name) + public Object lookupLink(Name name) throws NamingException { return getRoot().lookupLink(stripProtocol(name)); } @Override - public Object lookupLink (String name) + public Object lookupLink(String name) throws NamingException { return getRoot().lookupLink(stripProtocol(name)); } - @Override - public Context createSubcontext (Name name) + public Context createSubcontext(Name name) throws NamingException { return getRoot().createSubcontext(stripProtocol(name)); } @Override - public Context createSubcontext (String name) + public Context createSubcontext(String name) throws NamingException { return getRoot().createSubcontext(stripProtocol(name)); } - @Override - public void destroySubcontext (Name name) + public void destroySubcontext(Name name) throws NamingException { getRoot().destroySubcontext(stripProtocol(name)); } @Override - public void destroySubcontext (String name) + public void destroySubcontext(String name) throws NamingException { getRoot().destroySubcontext(stripProtocol(name)); } - @Override public NamingEnumeration list(Name name) throws NamingException @@ -215,7 +206,6 @@ public class javaRootURLContext implements Context return getRoot().list(stripProtocol(name)); } - @Override public NamingEnumeration list(String name) throws NamingException @@ -237,117 +227,110 @@ public class javaRootURLContext implements Context return getRoot().listBindings(stripProtocol(name)); } - @Override - public Name composeName (Name name, - Name prefix) + public Name composeName(Name name, + Name prefix) throws NamingException { return getRoot().composeName(name, prefix); } @Override - public String composeName (String name, - String prefix) + public String composeName(String name, + String prefix) throws NamingException { return getRoot().composeName(name, prefix); } - @Override - public void close () + public void close() throws NamingException { } @Override - public String getNameInNamespace () + public String getNameInNamespace() throws NamingException { return URL_PREFIX; } @Override - public NameParser getNameParser (Name name) + public NameParser getNameParser(Name name) throws NamingException { return __javaNameParser; } @Override - public NameParser getNameParser (String name) + public NameParser getNameParser(String name) throws NamingException { return __javaNameParser; } - @Override public Object addToEnvironment(String propName, Object propVal) throws NamingException { - return _env.put (propName,propVal); + return _env.put(propName, propVal); } @Override public Object removeFromEnvironment(String propName) throws NamingException { - return _env.remove (propName); + return _env.remove(propName); } @Override - public Hashtable getEnvironment () + public Hashtable getEnvironment() { return _env; } - public static NamingContext getRoot () + public static NamingContext getRoot() { return __nameRoot; } - - protected Name stripProtocol (Name name) + protected Name stripProtocol(Name name) throws NamingException { if ((name != null) && (name.size() > 0)) { String head = name.get(0); - if(LOG.isDebugEnabled()) - LOG.debug("Head element of name is: "+head); + if (LOG.isDebugEnabled()) + LOG.debug("Head element of name is: " + head); if (head.startsWith(URL_PREFIX)) { - head = head.substring (URL_PREFIX.length()); + head = head.substring(URL_PREFIX.length()); name.remove(0); if (head.length() > 0) name.add(0, head); - if(LOG.isDebugEnabled()) - LOG.debug("name modified to "+name.toString()); + if (LOG.isDebugEnabled()) + LOG.debug("name modified to " + name.toString()); } } return name; } - - - protected String stripProtocol (String name) + protected String stripProtocol(String name) { String newName = name; if ((name != null) && (!name.equals(""))) { if (name.startsWith(URL_PREFIX)) - newName = name.substring(URL_PREFIX.length()); + newName = name.substring(URL_PREFIX.length()); } return newName; } - } diff --git a/jetty-jndi/src/main/java/org/eclipse/jetty/jndi/java/javaURLContextFactory.java b/jetty-jndi/src/main/java/org/eclipse/jetty/jndi/java/javaURLContextFactory.java index 8fd9bf3d118..a3bda3d78dd 100644 --- a/jetty-jndi/src/main/java/org/eclipse/jetty/jndi/java/javaURLContextFactory.java +++ b/jetty-jndi/src/main/java/org/eclipse/jetty/jndi/java/javaURLContextFactory.java @@ -19,7 +19,6 @@ package org.eclipse.jetty.jndi.java; import java.util.Hashtable; - import javax.naming.Context; import javax.naming.Name; import javax.naming.NamingException; @@ -28,8 +27,10 @@ import javax.naming.spi.ObjectFactory; import org.eclipse.jetty.util.log.Log; import org.eclipse.jetty.util.log.Logger; +// This is a required name for JNDI +// @checkstyle-disable-check : TypeNameCheck -/** +/** * javaURLContextFactory *

    * This is the URL context factory for the java: URL. @@ -46,7 +47,7 @@ public class javaURLContextFactory implements ObjectFactory * @param ctx a Context value * @param env a Hashtable value * @return a new context or the resolved object for the url - * @exception Exception if an error occurs + * @throws Exception if an error occurs */ @Override public Object getObjectInstance(Object url, Name name, Context ctx, Hashtable env) @@ -55,31 +56,34 @@ public class javaURLContextFactory implements ObjectFactory // null object means return a root context for doing resolutions if (url == null) { - if(LOG.isDebugEnabled())LOG.debug(">>> new root context requested "); + if (LOG.isDebugEnabled()) + LOG.debug(">>> new root context requested "); return new javaRootURLContext(env); } // return the resolution of the url if (url instanceof String) { - if(LOG.isDebugEnabled())LOG.debug(">>> resolution of url "+url+" requested"); - Context rootctx = new javaRootURLContext (env); - return rootctx.lookup ((String)url); + if (LOG.isDebugEnabled()) + LOG.debug(">>> resolution of url " + url + " requested"); + Context rootctx = new javaRootURLContext(env); + return rootctx.lookup((String)url); } // return the resolution of at least one of the urls if (url instanceof String[]) { - if(LOG.isDebugEnabled())LOG.debug(">>> resolution of array of urls requested"); + if (LOG.isDebugEnabled()) + LOG.debug(">>> resolution of array of urls requested"); String[] urls = (String[])url; - Context rootctx = new javaRootURLContext (env); + Context rootctx = new javaRootURLContext(env); Object object = null; NamingException e = null; - for (int i=0;(i< urls.length) && (object == null); i++) + for (int i = 0; (i < urls.length) && (object == null); i++) { try { - object = rootctx.lookup (urls[i]); + object = rootctx.lookup(urls[i]); } catch (NamingException x) { @@ -93,7 +97,8 @@ public class javaURLContextFactory implements ObjectFactory return object; } - if(LOG.isDebugEnabled())LOG.debug(">>> No idea what to do, so return a new root context anyway"); - return new javaRootURLContext (env); + if (LOG.isDebugEnabled()) + LOG.debug(">>> No idea what to do, so return a new root context anyway"); + return new javaRootURLContext(env); } -}; +} diff --git a/jetty-jndi/src/main/java/org/eclipse/jetty/jndi/local/localContextRoot.java b/jetty-jndi/src/main/java/org/eclipse/jetty/jndi/local/localContextRoot.java index 3ad31582062..d1c5a3bd497 100644 --- a/jetty-jndi/src/main/java/org/eclipse/jetty/jndi/local/localContextRoot.java +++ b/jetty-jndi/src/main/java/org/eclipse/jetty/jndi/local/localContextRoot.java @@ -41,27 +41,25 @@ import org.eclipse.jetty.jndi.NamingContext; import org.eclipse.jetty.util.log.Log; import org.eclipse.jetty.util.log.Logger; +// This is a required name for JNDI +// @checkstyle-disable-check : TypeNameCheck + /** - * * localContext * * Implementation of the delegate for InitialContext for the local namespace. - * - * - * @version $Revision: 4780 $ $Date: 2009-03-17 16:36:08 +0100 (Tue, 17 Mar 2009) $ - * */ public class localContextRoot implements Context { private static final Logger LOG = Log.getLogger(localContextRoot.class); - protected final static NamingContext __root = new NamingRoot(); - private final Hashtable _env; + protected static final NamingContext __root = new NamingRoot(); + private final Hashtable _env; static class NamingRoot extends NamingContext { public NamingRoot() { - super (null,null,null,new LocalNameParser()); + super(null, null, null, new LocalNameParser()); } } @@ -91,7 +89,6 @@ public class localContextRoot implements Context * */ - public static NamingContext getRoot() { return __root; @@ -103,8 +100,6 @@ public class localContextRoot implements Context } /** - * - * * @see javax.naming.Context#close() */ @Override @@ -113,8 +108,6 @@ public class localContextRoot implements Context } /** - * - * * @see javax.naming.Context#getNameInNamespace() */ @Override @@ -124,8 +117,6 @@ public class localContextRoot implements Context } /** - * - * * @see javax.naming.Context#destroySubcontext(javax.naming.Name) */ @Override @@ -135,8 +126,6 @@ public class localContextRoot implements Context } /** - * - * * @see javax.naming.Context#destroySubcontext(java.lang.String) */ @Override @@ -146,8 +135,6 @@ public class localContextRoot implements Context } /** - * - * * @see javax.naming.Context#getEnvironment() */ @Override @@ -172,7 +159,7 @@ public class localContextRoot implements Context catch (Exception e) { LOG.warn(e); - throw new NamingException (e.getMessage()); + throw new NamingException(e.getMessage()); } } return ctx; @@ -185,7 +172,7 @@ public class localContextRoot implements Context if (firstComponent.equals("")) return this; - Binding binding = __root.getBinding (firstComponent); + Binding binding = __root.getBinding(firstComponent); if (binding == null) { NameNotFoundException nnfe = new NameNotFoundException(firstComponent + " is not bound"); @@ -201,8 +188,6 @@ public class localContextRoot implements Context } /** - * - * * @see javax.naming.Context#unbind(javax.naming.Name) */ @Override @@ -214,30 +199,28 @@ public class localContextRoot implements Context return; if (__root.isLocked()) - throw new NamingException ("This context is immutable"); + throw new NamingException("This context is immutable"); Name cname = __root.toCanonicalName(name); if (cname == null) - throw new NamingException ("Name is null"); + throw new NamingException("Name is null"); if (cname.size() == 0) - throw new NamingException ("Name is empty"); + throw new NamingException("Name is empty"); //if no subcontexts, just unbind it if (cname.size() == 1) { - __root.removeBinding (cname); + __root.removeBinding(cname); } else { - getContext(cname).unbind (cname.getSuffix(1)); + getContext(cname).unbind(cname.getSuffix(1)); } } /** - * - * * @see javax.naming.Context#unbind(java.lang.String) */ @Override @@ -247,8 +230,6 @@ public class localContextRoot implements Context } /** - * - * * @see javax.naming.Context#lookupLink(java.lang.String) */ @Override @@ -258,8 +239,6 @@ public class localContextRoot implements Context } /** - * - * * @see javax.naming.Context#lookupLink(javax.naming.Name) */ @Override @@ -274,11 +253,11 @@ public class localContextRoot implements Context } if (cname.size() == 0) - throw new NamingException ("Name is empty"); + throw new NamingException("Name is empty"); if (cname.size() == 1) { - Binding binding = __root.getBinding (cname); + Binding binding = __root.getBinding(cname); if (binding == null) throw new NameNotFoundException(); @@ -298,8 +277,8 @@ public class localContextRoot implements Context } catch (Exception e) { - LOG.warn("",e); - throw new NamingException (e.getMessage()); + LOG.warn("", e); + throw new NamingException(e.getMessage()); } } else @@ -311,12 +290,10 @@ public class localContextRoot implements Context } //it is a multipart name, recurse to the first subcontext - return getContext(cname).lookup (cname.getSuffix(1)); + return getContext(cname).lookup(cname.getSuffix(1)); } /** - * - * * @see javax.naming.Context#removeFromEnvironment(java.lang.String) */ @Override @@ -326,15 +303,13 @@ public class localContextRoot implements Context } /** - * - * * @see javax.naming.Context#lookup(javax.naming.Name) */ @Override public Object lookup(Name name) throws NamingException { - if(LOG.isDebugEnabled()) - LOG.debug("Looking up name=\""+name+"\""); + if (LOG.isDebugEnabled()) + LOG.debug("Looking up name=\"" + name + "\""); Name cname = __root.toCanonicalName(name); if ((cname == null) || cname.isEmpty()) @@ -344,7 +319,7 @@ public class localContextRoot implements Context if (cname.size() == 1) { - Binding binding = __root.getBinding (cname); + Binding binding = __root.getBinding(cname); if (binding == null) { NameNotFoundException nnfe = new NameNotFoundException(); @@ -360,12 +335,12 @@ public class localContextRoot implements Context //if link name starts with ./ it is relative to current context String linkName = ((LinkRef)o).getLinkName(); if (linkName.startsWith("./")) - return lookup (linkName.substring(2)); + return lookup(linkName.substring(2)); else { //link name is absolute InitialContext ictx = new InitialContext(); - return ictx.lookup (linkName); + return ictx.lookup(linkName); } } else if (o instanceof Reference) @@ -381,9 +356,11 @@ public class localContextRoot implements Context } catch (final Exception e) { - throw new NamingException (e.getMessage()) + throw new NamingException(e.getMessage()) { - { initCause(e);} + { + initCause(e); + } }; } } @@ -395,8 +372,6 @@ public class localContextRoot implements Context } /** - * - * * @see javax.naming.Context#lookup(java.lang.String) */ @Override @@ -406,8 +381,6 @@ public class localContextRoot implements Context } /** - * - * * @see javax.naming.Context#bind(java.lang.String, java.lang.Object) */ @Override @@ -417,29 +390,27 @@ public class localContextRoot implements Context } /** - * - * * @see javax.naming.Context#bind(javax.naming.Name, java.lang.Object) */ @Override public void bind(Name name, Object obj) throws NamingException { if (__root.isLocked()) - throw new NamingException ("This context is immutable"); + throw new NamingException("This context is immutable"); Name cname = __root.toCanonicalName(name); if (cname == null) - throw new NamingException ("Name is null"); + throw new NamingException("Name is null"); if (cname.size() == 0) - throw new NamingException ("Name is empty"); + throw new NamingException("Name is empty"); //if no subcontexts, just bind it if (cname.size() == 1) { //get the object to be bound - Object objToBind = NamingManager.getStateToBind(obj, name,this, _env); + Object objToBind = NamingManager.getStateToBind(obj, name, this, _env); // Check for Referenceable if (objToBind instanceof Referenceable) { @@ -447,35 +418,33 @@ public class localContextRoot implements Context } //anything else we should be able to bind directly - __root.addBinding (cname, objToBind); + __root.addBinding(cname, objToBind); } else { - if(LOG.isDebugEnabled()) - LOG.debug("Checking for existing binding for name="+cname+" for first element of name="+cname.get(0)); + if (LOG.isDebugEnabled()) + LOG.debug("Checking for existing binding for name=" + cname + " for first element of name=" + cname.get(0)); - getContext(cname).bind (cname.getSuffix(1), obj); + getContext(cname).bind(cname.getSuffix(1), obj); } } /** - * - * * @see javax.naming.Context#rebind(javax.naming.Name, java.lang.Object) */ @Override public void rebind(Name name, Object obj) throws NamingException { if (__root.isLocked()) - throw new NamingException ("This context is immutable"); + throw new NamingException("This context is immutable"); Name cname = __root.toCanonicalName(name); if (cname == null) - throw new NamingException ("Name is null"); + throw new NamingException("Name is null"); if (cname.size() == 0) - throw new NamingException ("Name is empty"); + throw new NamingException("Name is empty"); //if no subcontexts, just bind it if (cname.size() == 1) @@ -488,21 +457,19 @@ public class localContextRoot implements Context objToBind = ((Referenceable)objToBind).getReference(); } __root.removeBinding(cname); - __root.addBinding (cname, objToBind); + __root.addBinding(cname, objToBind); } else { //walk down the subcontext hierarchy - if(LOG.isDebugEnabled()) - LOG.debug("Checking for existing binding for name="+cname+" for first element of name="+cname.get(0)); + if (LOG.isDebugEnabled()) + LOG.debug("Checking for existing binding for name=" + cname + " for first element of name=" + cname.get(0)); - getContext(cname).rebind (cname.getSuffix(1), obj); + getContext(cname).rebind(cname.getSuffix(1), obj); } } /** - * - * * @see javax.naming.Context#rebind(java.lang.String, java.lang.Object) */ @Override @@ -512,8 +479,6 @@ public class localContextRoot implements Context } /** - * - * * @see javax.naming.Context#rename(javax.naming.Name, javax.naming.Name) */ @Override @@ -523,8 +488,6 @@ public class localContextRoot implements Context } /** - * - * * @see javax.naming.Context#rename(java.lang.String, java.lang.String) */ @Override @@ -534,8 +497,6 @@ public class localContextRoot implements Context } /** - * - * * @see javax.naming.Context#createSubcontext(java.lang.String) */ @Override @@ -553,8 +514,6 @@ public class localContextRoot implements Context } /** - * - * * @see javax.naming.Context#createSubcontext(javax.naming.Name) */ @Override @@ -570,39 +529,36 @@ public class localContextRoot implements Context if (__root.isLocked()) { - NamingException ne = new NamingException ("This context is immutable"); + NamingException ne = new NamingException("This context is immutable"); ne.setRemainingName(name); throw ne; } - Name cname = __root.toCanonicalName (name); + Name cname = __root.toCanonicalName(name); if (cname == null) - throw new NamingException ("Name is null"); + throw new NamingException("Name is null"); if (cname.size() == 0) - throw new NamingException ("Name is empty"); + throw new NamingException("Name is empty"); if (cname.size() == 1) { //not permitted to bind if something already bound at that name - Binding binding = __root.getBinding (cname); + Binding binding = __root.getBinding(cname); if (binding != null) - throw new NameAlreadyBoundException (cname.toString()); + throw new NameAlreadyBoundException(cname.toString()); //make a new naming context with the root as the parent - Context ctx = new NamingContext (_env, cname.get(0), __root, __root.getNameParser("")); - __root.addBinding (cname, ctx); + Context ctx = new NamingContext(_env, cname.get(0), __root, __root.getNameParser("")); + __root.addBinding(cname, ctx); return ctx; } //If the name has multiple subcontexts, return getContext(cname).createSubcontext(cname.getSuffix(1)); - } /** - * - * * @see javax.naming.Context#getNameParser(java.lang.String) */ @Override @@ -612,8 +568,6 @@ public class localContextRoot implements Context } /** - * - * * @see javax.naming.Context#getNameParser(javax.naming.Name) */ @Override @@ -623,8 +577,6 @@ public class localContextRoot implements Context } /** - * - * * @see javax.naming.Context#list(java.lang.String) */ @Override @@ -634,8 +586,6 @@ public class localContextRoot implements Context } /** - * - * * @see javax.naming.Context#list(javax.naming.Name) */ @Override @@ -645,8 +595,6 @@ public class localContextRoot implements Context } /** - * - * * @see javax.naming.Context#listBindings(javax.naming.Name) */ @Override @@ -656,8 +604,6 @@ public class localContextRoot implements Context } /** - * - * * @see javax.naming.Context#listBindings(java.lang.String) */ @Override @@ -667,35 +613,29 @@ public class localContextRoot implements Context } /** - * - * * @see javax.naming.Context#addToEnvironment(java.lang.String, - * java.lang.Object) + * java.lang.Object) */ @Override public Object addToEnvironment(String propName, Object propVal) - throws NamingException + throws NamingException { return _env.put(propName, propVal); } /** - * - * * @see javax.naming.Context#composeName(java.lang.String, java.lang.String) */ @Override public String composeName(String name, String prefix) - throws NamingException + throws NamingException { return __root.composeName(name, prefix); } /** - * - * * @see javax.naming.Context#composeName(javax.naming.Name, - * javax.naming.Name) + * javax.naming.Name) */ @Override public Name composeName(Name name, Name prefix) throws NamingException @@ -712,5 +652,4 @@ public class localContextRoot implements Context { return name; } - } diff --git a/jetty-jndi/src/main/java/org/eclipse/jetty/jndi/package-info.java b/jetty-jndi/src/main/java/org/eclipse/jetty/jndi/package-info.java index 3f719dc5e4f..cc5d88a4940 100644 --- a/jetty-jndi/src/main/java/org/eclipse/jetty/jndi/package-info.java +++ b/jetty-jndi/src/main/java/org/eclipse/jetty/jndi/package-info.java @@ -17,7 +17,7 @@ // /** - * Jetty Jndi : Java Naming Directory Interface + * Jetty Jndi : Java Naming Directory Interface */ package org.eclipse.jetty.jndi; diff --git a/jetty-jndi/src/test/java/org/eclipse/jetty/jndi/factories/TestMailSessionReference.java b/jetty-jndi/src/test/java/org/eclipse/jetty/jndi/factories/TestMailSessionReference.java index 057efd11868..ccbc5386bb1 100644 --- a/jetty-jndi/src/test/java/org/eclipse/jetty/jndi/factories/TestMailSessionReference.java +++ b/jetty-jndi/src/test/java/org/eclipse/jetty/jndi/factories/TestMailSessionReference.java @@ -18,12 +18,7 @@ package org.eclipse.jetty.jndi.factories; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertNotNull; -import static org.junit.jupiter.api.Assertions.assertTrue; - import java.util.Properties; - import javax.mail.Session; import javax.naming.Context; import javax.naming.InitialContext; @@ -34,19 +29,23 @@ import javax.naming.NameParser; import org.eclipse.jetty.jndi.NamingUtil; import org.junit.jupiter.api.Test; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertTrue; + /** * */ public class TestMailSessionReference { @Test - public void testMailSessionReference () throws Exception + public void testMailSessionReference() throws Exception { InitialContext icontext = new InitialContext(); MailSessionReference sref = new MailSessionReference(); sref.setUser("janb"); sref.setPassword("OBF:1xmk1w261z0f1w1c1xmq"); - Properties props = new Properties (); + Properties props = new Properties(); props.put("mail.smtp.host", "xxx"); props.put("mail.debug", "true"); sref.setProperties(props); @@ -55,9 +54,9 @@ public class TestMailSessionReference assertNotNull(x); assertTrue(x instanceof javax.mail.Session); javax.mail.Session session = (javax.mail.Session)x; - Properties sessionProps = session.getProperties(); + Properties sessionProps = session.getProperties(); assertEquals(props, sessionProps); - assertTrue (session.getDebug()); + assertTrue(session.getDebug()); Context foo = icontext.createSubcontext("foo"); NameParser parser = icontext.getNameParser(""); diff --git a/jetty-jndi/src/test/java/org/eclipse/jetty/jndi/java/TestJNDI.java b/jetty-jndi/src/test/java/org/eclipse/jetty/jndi/java/TestJNDI.java index c66269293fe..0b18009b0c0 100644 --- a/jetty-jndi/src/test/java/org/eclipse/jetty/jndi/java/TestJNDI.java +++ b/jetty-jndi/src/test/java/org/eclipse/jetty/jndi/java/TestJNDI.java @@ -18,18 +18,10 @@ package org.eclipse.jetty.jndi.java; -import static org.hamcrest.MatcherAssert.assertThat; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertFalse; -import static org.junit.jupiter.api.Assertions.assertNotNull; -import static org.junit.jupiter.api.Assertions.assertTrue; -import static org.junit.jupiter.api.Assertions.fail; - import java.net.URL; import java.net.URLClassLoader; import java.util.HashMap; import java.util.Hashtable; - import javax.naming.Context; import javax.naming.InitialContext; import javax.naming.LinkRef; @@ -53,6 +45,14 @@ import org.eclipse.jetty.util.log.Log; import org.eclipse.jetty.util.log.Logger; import org.hamcrest.Matchers; import org.junit.jupiter.api.Test; + +import static org.hamcrest.MatcherAssert.assertThat; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.fail; + /** * */ @@ -74,33 +74,30 @@ public class TestJNDI { return myString; } - } - - + @Test public void testThreadContextClassloaderAndCurrentContext() - throws Exception + throws Exception { - //create a jetty context, and start it so that its classloader it created //and it is the current context ClassLoader currentLoader = Thread.currentThread().getContextClassLoader(); ContextHandler ch = new ContextHandler(); URLClassLoader chLoader = new URLClassLoader(new URL[0], currentLoader); ch.setClassLoader(chLoader); - Server server = new Server(); + Server server = new Server(); HandlerList hl = new HandlerList(); server.setHandler(hl); hl.addHandler(ch); - + //Create another one ContextHandler ch2 = new ContextHandler(); URLClassLoader ch2Loader = new URLClassLoader(new URL[0], currentLoader); ch2.setClassLoader(ch2Loader); hl.addHandler(ch2); - + try { ch.setContextPath("/ch"); @@ -108,7 +105,7 @@ public class TestJNDI { private Context comp; private Object testObj = new Object(); - + @Override public void contextInitialized(ServletContextEvent sce) { @@ -135,7 +132,7 @@ public class TestJNDI try { assertNotNull(comp); - assertEquals(testObj,comp.lookup("env/ch")); + assertEquals(testObj, comp.lookup("env/ch")); comp.destroySubcontext("env"); } catch (Exception e) @@ -147,7 +144,6 @@ public class TestJNDI //Starting the context makes it current and creates a classloader for it ch.start(); - ch2.setContextPath("/ch2"); ch2.addEventListener(new ServletContextListener() { @@ -162,7 +158,7 @@ public class TestJNDI InitialContext initCtx = new InitialContext(); comp = (Context)initCtx.lookup("java:comp"); assertNotNull(comp); - + //another context's bindings should not be visible Context env = ((Context)comp).createSubcontext("env"); try @@ -180,7 +176,7 @@ public class TestJNDI throw new IllegalStateException(e); } } - + @Override public void contextDestroyed(ServletContextEvent sce) { @@ -205,15 +201,14 @@ public class TestJNDI Thread.currentThread().setContextClassLoader(currentLoader); } } - + @Test public void testJavaNameParsing() throws Exception { Thread currentThread = Thread.currentThread(); ClassLoader currentLoader = currentThread.getContextClassLoader(); ClassLoader childLoader1 = new URLClassLoader(new URL[0], currentLoader); - - + //set the current thread's classloader currentThread.setContextClassLoader(childLoader1); @@ -222,55 +217,71 @@ public class TestJNDI InitialContext initCtx = new InitialContext(); Context sub0 = (Context)initCtx.lookup("java:"); - if(LOG.isDebugEnabled())LOG.debug("------ Looked up java: --------------"); + if (LOG.isDebugEnabled()) + LOG.debug("------ Looked up java: --------------"); Name n = sub0.getNameParser("").parse("/red/green/"); - if(LOG.isDebugEnabled())LOG.debug("get(0)="+n.get(0)); - if(LOG.isDebugEnabled())LOG.debug("getPrefix(1)="+n.getPrefix(1)); + if (LOG.isDebugEnabled()) + LOG.debug("get(0)=" + n.get(0)); + if (LOG.isDebugEnabled()) + LOG.debug("getPrefix(1)=" + n.getPrefix(1)); n = n.getSuffix(1); - if(LOG.isDebugEnabled())LOG.debug("getSuffix(1)="+n); - if(LOG.isDebugEnabled())LOG.debug("get(0)="+n.get(0)); - if(LOG.isDebugEnabled())LOG.debug("getPrefix(1)="+n.getPrefix(1)); + if (LOG.isDebugEnabled()) + LOG.debug("getSuffix(1)=" + n); + if (LOG.isDebugEnabled()) + LOG.debug("get(0)=" + n.get(0)); + if (LOG.isDebugEnabled()) + LOG.debug("getPrefix(1)=" + n.getPrefix(1)); n = n.getSuffix(1); - if(LOG.isDebugEnabled())LOG.debug("getSuffix(1)="+n); - if(LOG.isDebugEnabled())LOG.debug("get(0)="+n.get(0)); - if(LOG.isDebugEnabled())LOG.debug("getPrefix(1)="+n.getPrefix(1)); + if (LOG.isDebugEnabled()) + LOG.debug("getSuffix(1)=" + n); + if (LOG.isDebugEnabled()) + LOG.debug("get(0)=" + n.get(0)); + if (LOG.isDebugEnabled()) + LOG.debug("getPrefix(1)=" + n.getPrefix(1)); n = n.getSuffix(1); - if(LOG.isDebugEnabled())LOG.debug("getSuffix(1)="+n); + if (LOG.isDebugEnabled()) + LOG.debug("getSuffix(1)=" + n); n = sub0.getNameParser("").parse("pink/purple/"); - if(LOG.isDebugEnabled())LOG.debug("get(0)="+n.get(0)); - if(LOG.isDebugEnabled())LOG.debug("getPrefix(1)="+n.getPrefix(1)); + if (LOG.isDebugEnabled()) + LOG.debug("get(0)=" + n.get(0)); + if (LOG.isDebugEnabled()) + LOG.debug("getPrefix(1)=" + n.getPrefix(1)); n = n.getSuffix(1); - if(LOG.isDebugEnabled())LOG.debug("getSuffix(1)="+n); - if(LOG.isDebugEnabled())LOG.debug("get(0)="+n.get(0)); - if(LOG.isDebugEnabled())LOG.debug("getPrefix(1)="+n.getPrefix(1)); + if (LOG.isDebugEnabled()) + LOG.debug("getSuffix(1)=" + n); + if (LOG.isDebugEnabled()) + LOG.debug("get(0)=" + n.get(0)); + if (LOG.isDebugEnabled()) + LOG.debug("getPrefix(1)=" + n.getPrefix(1)); NamingContext ncontext = (NamingContext)sub0; Name nn = ncontext.toCanonicalName(ncontext.getNameParser("").parse("/yellow/blue/")); LOG.debug(nn.toString()); - assertEquals (2, nn.size()); + assertEquals(2, nn.size()); nn = ncontext.toCanonicalName(ncontext.getNameParser("").parse("/yellow/blue")); LOG.debug(nn.toString()); - assertEquals (2, nn.size()); + assertEquals(2, nn.size()); nn = ncontext.toCanonicalName(ncontext.getNameParser("").parse("/")); - if(LOG.isDebugEnabled())LOG.debug("/ parses as: "+nn+" with size="+nn.size()); + if (LOG.isDebugEnabled()) + LOG.debug("/ parses as: " + nn + " with size=" + nn.size()); LOG.debug(nn.toString()); - assertEquals (1, nn.size()); + assertEquals(1, nn.size()); nn = ncontext.toCanonicalName(ncontext.getNameParser("").parse("")); LOG.debug(nn.toString()); - assertEquals (0, nn.size()); + assertEquals(0, nn.size()); Context fee = ncontext.createSubcontext("fee"); - fee.bind ("fi", "88"); + fee.bind("fi", "88"); assertEquals("88", initCtx.lookup("java:/fee/fi")); assertEquals("88", initCtx.lookup("java:/fee/fi/")); - assertTrue (initCtx.lookup("java:/fee/") instanceof javax.naming.Context); + assertTrue(initCtx.lookup("java:/fee/") instanceof javax.naming.Context); } finally { @@ -280,8 +291,6 @@ public class TestJNDI currentThread.setContextClassLoader(currentLoader); } } - - @Test public void testIt() throws Exception @@ -325,20 +334,20 @@ public class TestJNDI } }); */ - + //Set up the tccl before doing any jndi operations currentThread.setContextClassLoader(childLoader1); initCtx = new InitialContext(); - + //Test we can lookup the root java: naming tree Context sub0 = (Context)initCtx.lookup("java:"); assertNotNull(sub0); - + //Test that we cannot bind java:comp as it should //already be bound try { - Context sub1 = sub0.createSubcontext ("comp"); + Context sub1 = sub0.createSubcontext("comp"); fail("Comp should already be bound"); } catch (NameAlreadyBoundException e) @@ -350,37 +359,37 @@ public class TestJNDI Context sub1 = (Context)initCtx.lookup("java:comp"); assertNotNull(sub1); - Context sub2 = sub1.createSubcontext ("env"); + Context sub2 = sub1.createSubcontext("env"); assertNotNull(sub2); - initCtx.bind ("java:comp/env/rubbish", "abc"); - assertEquals ("abc", initCtx.lookup("java:comp/env/rubbish")); + initCtx.bind("java:comp/env/rubbish", "abc"); + assertEquals("abc", initCtx.lookup("java:comp/env/rubbish")); //check binding LinkRefs - LinkRef link = new LinkRef ("java:comp/env/rubbish"); - initCtx.bind ("java:comp/env/poubelle", link); - assertEquals ("abc", initCtx.lookup("java:comp/env/poubelle")); + LinkRef link = new LinkRef("java:comp/env/rubbish"); + initCtx.bind("java:comp/env/poubelle", link); + assertEquals("abc", initCtx.lookup("java:comp/env/poubelle")); //check binding References StringRefAddr addr = new StringRefAddr("blah", "myReferenceable"); - Reference ref = new Reference (java.lang.String.class.getName(), - addr, - MyObjectFactory.class.getName(), - null); + Reference ref = new Reference(java.lang.String.class.getName(), + addr, + MyObjectFactory.class.getName(), + null); - initCtx.bind ("java:comp/env/quatsch", ref); - assertEquals (MyObjectFactory.myString, initCtx.lookup("java:comp/env/quatsch")); + initCtx.bind("java:comp/env/quatsch", ref); + assertEquals(MyObjectFactory.myString, initCtx.lookup("java:comp/env/quatsch")); //test binding something at java: Context sub3 = initCtx.createSubcontext("java:zero"); - initCtx.bind ("java:zero/one", "ONE"); - assertEquals ("ONE", initCtx.lookup("java:zero/one")); + initCtx.bind("java:zero/one", "ONE"); + assertEquals("ONE", initCtx.lookup("java:zero/one")); //change the current thread's classloader to check distinct naming currentThread.setContextClassLoader(childLoader2); Context otherSub1 = (Context)initCtx.lookup("java:comp"); - assertTrue (!(sub1 == otherSub1)); + assertTrue(!(sub1 == otherSub1)); try { initCtx.lookup("java:comp/env/rubbish"); @@ -396,46 +405,45 @@ public class TestJNDI //test rebind with existing binding initCtx.rebind("java:comp/env/rubbish", "xyz"); - assertEquals ("xyz", initCtx.lookup("java:comp/env/rubbish")); + assertEquals("xyz", initCtx.lookup("java:comp/env/rubbish")); //test rebind with no existing binding - initCtx.rebind ("java:comp/env/mullheim", "hij"); - assertEquals ("hij", initCtx.lookup("java:comp/env/mullheim")); + initCtx.rebind("java:comp/env/mullheim", "hij"); + assertEquals("hij", initCtx.lookup("java:comp/env/mullheim")); //test that the other bindings are already there - assertEquals ("xyz", initCtx.lookup("java:comp/env/poubelle")); + assertEquals("xyz", initCtx.lookup("java:comp/env/poubelle")); //test java:/comp/env/stuff - assertEquals ("xyz", initCtx.lookup("java:/comp/env/poubelle/")); + assertEquals("xyz", initCtx.lookup("java:/comp/env/poubelle/")); //test list Names - NamingEnumeration nenum = initCtx.list ("java:comp/env"); + NamingEnumeration nenum = initCtx.list("java:comp/env"); HashMap results = new HashMap(); while (nenum.hasMore()) { NameClassPair ncp = (NameClassPair)nenum.next(); - results.put (ncp.getName(), ncp.getClassName()); + results.put(ncp.getName(), ncp.getClassName()); } - assertEquals (4, results.size()); + assertEquals(4, results.size()); - assertEquals ("java.lang.String", results.get("rubbish")); - assertEquals ("javax.naming.LinkRef", results.get("poubelle")); - assertEquals ("java.lang.String", results.get("mullheim")); - assertEquals ("javax.naming.Reference", results.get("quatsch")); + assertEquals("java.lang.String", results.get("rubbish")); + assertEquals("javax.naming.LinkRef", results.get("poubelle")); + assertEquals("java.lang.String", results.get("mullheim")); + assertEquals("javax.naming.Reference", results.get("quatsch")); //test list Bindings NamingEnumeration benum = initCtx.list("java:comp/env"); - assertEquals (4, results.size()); + assertEquals(4, results.size()); //test NameInNamespace - assertEquals ("comp/env", sub2.getNameInNamespace()); + assertEquals("comp/env", sub2.getNameInNamespace()); //test close does nothing Context closeCtx = (Context)initCtx.lookup("java:comp/env"); closeCtx.close(); - //test what happens when you close an initial context InitialContext closeInit = new InitialContext(); closeInit.close(); @@ -452,9 +460,9 @@ public class TestJNDI //check we can't get the lock assertFalse(ectx.getEnvironment().containsKey("org.eclipse.jetty.jndi.lock")); //check once locked we can still do lookups - assertEquals ("xxx", initCtx.lookup("java:comp/crud")); + assertEquals("xxx", initCtx.lookup("java:comp/crud")); assertNotNull(initCtx.lookup("java:comp/ttt/ttt2")); - + //test trying to bind into java:comp after lock InitialContext zzz = null; try @@ -463,7 +471,6 @@ public class TestJNDI ((Context)zzz.lookup("java:comp")).bind("crud2", "xxx2"); fail("Should not be able to write to locked context"); - } catch (NamingException ne) { diff --git a/jetty-jndi/src/test/java/org/eclipse/jetty/jndi/java/TestLocalJNDI.java b/jetty-jndi/src/test/java/org/eclipse/jetty/jndi/java/TestLocalJNDI.java index ab1099727b7..0f49d633ea2 100644 --- a/jetty-jndi/src/test/java/org/eclipse/jetty/jndi/java/TestLocalJNDI.java +++ b/jetty-jndi/src/test/java/org/eclipse/jetty/jndi/java/TestLocalJNDI.java @@ -18,12 +18,7 @@ package org.eclipse.jetty.jndi.java; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertNotNull; -import static org.junit.jupiter.api.Assertions.fail; - import java.util.Hashtable; - import javax.naming.Context; import javax.naming.InitialContext; import javax.naming.Name; @@ -40,6 +35,10 @@ import org.eclipse.jetty.jndi.NamingUtil; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.Test; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.fail; + /** * */ @@ -56,7 +55,7 @@ public class TestLocalJNDI { if (!env.containsKey("flavour")) - throw new Exception ("No flavour!"); + throw new Exception("No flavour!"); if (obj instanceof Reference) { @@ -71,10 +70,9 @@ public class TestLocalJNDI } } return null; - } + } } - public static class Fruit implements Referenceable { String fruit; @@ -101,13 +99,6 @@ public class TestLocalJNDI } } - - - - - - - @AfterEach public void tearDown() throws Exception { @@ -115,11 +106,10 @@ public class TestLocalJNDI ic.destroySubcontext("a"); } - @Test public void testLocalReferenceable() throws Exception { - Hashtable env1 = new Hashtable(); + Hashtable env1 = new Hashtable(); env1.put("flavour", "orange"); InitialContext ic1 = new InitialContext(env1); @@ -127,7 +117,7 @@ public class TestLocalJNDI Object o = ic1.lookup("valencia"); - Hashtable env2 = new Hashtable(); + Hashtable env2 = new Hashtable(); InitialContext ic2 = new InitialContext(env2); try { @@ -140,11 +130,10 @@ public class TestLocalJNDI } } - @Test public void testLocalEnvironment() throws Exception { - Hashtable env1 = new Hashtable(); + Hashtable env1 = new Hashtable(); env1.put("make", "holden"); env1.put("model", "commodore"); @@ -162,7 +151,7 @@ public class TestLocalJNDI assertEquals("holden", ht.get("make")); assertEquals("commodore", ht.get("model")); - Hashtable env2 = new Hashtable(); + Hashtable env2 = new Hashtable(); env2.put("flavour", "strawberry"); InitialContext ic2 = new InitialContext(env2); assertEquals(car1, ic2.lookup("car1")); @@ -188,14 +177,10 @@ public class TestLocalJNDI c = (Context)ic.lookup("carz/hatchbackz"); assertNotNull(c); assertEquals(hatchbackz, c); - } - - - @Test - public void testLocal () throws Exception + public void testLocal() throws Exception { InitialContext ic = new InitialContext(); NameParser parser = ic.getNameParser(""); diff --git a/jetty-jspc-maven-plugin/pom.xml b/jetty-jspc-maven-plugin/pom.xml index 66ccbd850a4..2e260fffbe6 100644 --- a/jetty-jspc-maven-plugin/pom.xml +++ b/jetty-jspc-maven-plugin/pom.xml @@ -1,4 +1,5 @@ - + + org.eclipse.jetty jetty-project @@ -99,7 +100,7 @@ org.eclipse.jetty apache-jsp ${project.version} - + org.eclipse.jetty apache-jstl diff --git a/jetty-jspc-maven-plugin/src/it/package-root/pom.xml b/jetty-jspc-maven-plugin/src/it/package-root/pom.xml index 9e53639c1e1..310a1fc0c0c 100644 --- a/jetty-jspc-maven-plugin/src/it/package-root/pom.xml +++ b/jetty-jspc-maven-plugin/src/it/package-root/pom.xml @@ -1,6 +1,5 @@ - + 4.0.0 org.eclipse.jetty.its.jspc diff --git a/jetty-jspc-maven-plugin/src/it/simple-jsp-fail/pom.xml b/jetty-jspc-maven-plugin/src/it/simple-jsp-fail/pom.xml index f6c1416e8e8..5c8fe323d9e 100644 --- a/jetty-jspc-maven-plugin/src/it/simple-jsp-fail/pom.xml +++ b/jetty-jspc-maven-plugin/src/it/simple-jsp-fail/pom.xml @@ -1,6 +1,5 @@ - + 4.0.0 org.eclipse.jetty.its.jspc @@ -18,7 +17,6 @@ @project.version@ - diff --git a/jetty-jspc-maven-plugin/src/it/simple-jsp/pom.xml b/jetty-jspc-maven-plugin/src/it/simple-jsp/pom.xml index 5b1bb09a31b..b4b4052c0d3 100644 --- a/jetty-jspc-maven-plugin/src/it/simple-jsp/pom.xml +++ b/jetty-jspc-maven-plugin/src/it/simple-jsp/pom.xml @@ -1,6 +1,5 @@ - + 4.0.0 org.eclipse.jetty.its.jspc @@ -17,7 +16,6 @@ @project.version@ - diff --git a/jetty-jspc-maven-plugin/src/main/java/org/eclipse/jetty/jspc/plugin/JspcMojo.java b/jetty-jspc-maven-plugin/src/main/java/org/eclipse/jetty/jspc/plugin/JspcMojo.java index 373e9675c39..2b93292bbe4 100644 --- a/jetty-jspc-maven-plugin/src/main/java/org/eclipse/jetty/jspc/plugin/JspcMojo.java +++ b/jetty-jspc-maven-plugin/src/main/java/org/eclipse/jetty/jspc/plugin/JspcMojo.java @@ -70,90 +70,83 @@ import org.eclipse.jetty.util.resource.Resource; *

    * Runs jspc compiler to produce .java and .class files */ -@Mojo( name = "jspc", defaultPhase = LifecyclePhase.PROCESS_CLASSES, requiresDependencyResolution = ResolutionScope.COMPILE_PLUS_RUNTIME) +@Mojo(name = "jspc", defaultPhase = LifecyclePhase.PROCESS_CLASSES, requiresDependencyResolution = ResolutionScope.COMPILE_PLUS_RUNTIME) public class JspcMojo extends AbstractMojo { public static final String END_OF_WEBAPP = ""; public static final String PRECOMPILED_FLAG = "org.eclipse.jetty.jsp.precompiled"; - /** * JettyJspC * * Add some extra setters to standard JspC class to help configure it * for running in maven. - * + * * TODO move all setters on the plugin onto this jspc class instead. */ public static class JettyJspC extends JspC { - + private boolean scanAll; - - public void setClassLoader (ClassLoader loader) + + public void setClassLoader(ClassLoader loader) { this.loader = loader; } - - public void setScanAllDirectories (boolean scanAll) - { - this.scanAll = scanAll; - } - - public boolean getScanAllDirectories () - { - return this.scanAll; - } - + + public void setScanAllDirectories(boolean scanAll) + { + this.scanAll = scanAll; + } + + public boolean getScanAllDirectories() + { + return this.scanAll; + } @Override protected TldScanner newTldScanner(JspCServletContext context, boolean namespaceAware, boolean validate, boolean blockExternal) - { - if (context != null && context.getAttribute(JarScanner.class.getName()) == null) + { + if (context != null && context.getAttribute(JarScanner.class.getName()) == null) { - StandardJarScanner jarScanner = new StandardJarScanner(); + StandardJarScanner jarScanner = new StandardJarScanner(); jarScanner.setScanAllDirectories(getScanAllDirectories()); context.setAttribute(JarScanner.class.getName(), jarScanner); } - + return super.newTldScanner(context, namespaceAware, validate, blockExternal); - } + } } - - + /** * Whether or not to include dependencies on the plugin's classpath with <scope>provided</scope> * Use WITH CAUTION as you may wind up with duplicate jars/classes. - * + * * @since jetty-7.6.3 */ @Parameter(defaultValue = "false") private boolean useProvidedScope; - + /** * The artifacts for the project. - * + * * @since jetty-7.6.3 */ @Parameter(defaultValue = "${project.artifacts}", readonly = true) private Set projectArtifacts; - - + /** * The maven project. */ - @Parameter(defaultValue = "${project}", readonly = true , required = true) + @Parameter(defaultValue = "${project}", readonly = true, required = true) private MavenProject project; - - /** * The artifacts for the plugin itself. */ @Parameter(defaultValue = "${plugin.artifacts}", readonly = true) private List pluginArtifacts; - - + /** * File into which to generate the <servlet> and * <servlet-mapping> tags for the compiled jsps @@ -204,7 +197,6 @@ public class JspcMojo extends AbstractMojo @Parameter(defaultValue = "${basedir}/src/main/webapp/WEB-INF/web.xml") private String webXml; - /** * The comma separated list of patterns for file extensions to be processed. By default * will include all .jsp and .jspx files. @@ -224,35 +216,30 @@ public class JspcMojo extends AbstractMojo @Parameter(defaultValue = "${project.build.outputDirectory}") private File classesDirectory; - /** * Patterns of jars on the system path that contain tlds. Use | to separate each pattern. */ @Parameter(defaultValue = ".*taglibs[^/]*\\.jar|.*jstl[^/]*\\.jar$") private String tldJarNamePatterns; - - + /** * Source version - if not set defaults to jsp default (currently 1.7) */ @Parameter private String sourceVersion; - - + /** * Target version - if not set defaults to jsp default (currently 1.7) */ @Parameter private String targetVersion; - + /** - * * The JspC instance being used to compile the jsps. */ @Parameter private JettyJspC jspc; - /** * Whether dirs on the classpath should be scanned as well as jars. * True by default. This allows for scanning for tlds of dependent projects that @@ -260,7 +247,6 @@ public class JspcMojo extends AbstractMojo */ @Parameter(defaultValue = "true") private boolean scanAllDirectories; - @Override public void execute() throws MojoExecutionException, MojoFailureException @@ -271,14 +257,14 @@ public class JspcMojo extends AbstractMojo getLog().info("webAppSourceDirectory=" + webAppSourceDirectory); getLog().info("generatedClasses=" + generatedClasses); getLog().info("webXmlFragment=" + webXmlFragment); - getLog().info("webXml="+webXml); - getLog().info("insertionMarker="+ (insertionMarker == null || insertionMarker.equals("") ? END_OF_WEBAPP : insertionMarker)); + getLog().info("webXml=" + webXml); + getLog().info("insertionMarker=" + (insertionMarker == null || insertionMarker.equals("") ? END_OF_WEBAPP : insertionMarker)); getLog().info("keepSources=" + keepSources); - getLog().info("mergeFragment=" + mergeFragment); + getLog().info("mergeFragment=" + mergeFragment); if (sourceVersion != null) - getLog().info("sourceVersion="+sourceVersion); + getLog().info("sourceVersion=" + sourceVersion); if (targetVersion != null) - getLog().info("targetVersion="+targetVersion); + getLog().info("targetVersion=" + targetVersion); } try { @@ -299,17 +285,16 @@ public class JspcMojo extends AbstractMojo //set up the classpath of the webapp List webAppUrls = setUpWebAppClassPath(); - + //set up the classpath of the container (ie jetty and jsp jars) Set pluginJars = getPluginJars(); Set providedJars = getProvidedScopeJars(pluginJars); - //Make a classloader so provided jars will be on the classpath List sysUrls = new ArrayList<>(); - sysUrls.addAll(providedJars); + sysUrls.addAll(providedJars); URLClassLoader sysClassLoader = new URLClassLoader(sysUrls.toArray(new URL[0]), currentClassLoader); - + //make a classloader with the webapp classpath URLClassLoader webAppClassLoader = new URLClassLoader(webAppUrls.toArray(new URL[0]), sysClassLoader); StringBuilder webAppClassPath = new StringBuilder(); @@ -317,26 +302,25 @@ public class JspcMojo extends AbstractMojo for (int i = 0; i < webAppUrls.size(); i++) { if (getLog().isDebugEnabled()) - getLog().debug("webappclassloader contains: " + webAppUrls.get(i)); + getLog().debug("webappclassloader contains: " + webAppUrls.get(i)); webAppClassPath.append(new File(webAppUrls.get(i).toURI()).getCanonicalPath()); if (getLog().isDebugEnabled()) getLog().debug("added to classpath: " + (webAppUrls.get(i)).getFile()); - if (i+1 { + delete(generatedClassesDir, pathname -> + { return pathname.isDirectory() || pathname.getName().endsWith(".java"); }); } } } - + static void delete(File dir, FileFilter filter) { File[] files = dir.listFiles(filter); if (files != null) { - for(File f: files) + for (File f : files) { - if(f.isDirectory()) + if (f.isDirectory()) delete(f, filter); else f.delete(); @@ -416,13 +400,13 @@ public class JspcMojo extends AbstractMojo /** * Take the web fragment and put it inside a copy of the web.xml. - * + * * You can specify the insertion point by specifying the string in the * insertionMarker configuration entry. - * + * * If you dont specify the insertionMarker, then the fragment will be * inserted at the end of the file just before the </webapp> - * + * * @throws Exception if unable to merge the web xml */ public void mergeWebXml() throws Exception @@ -431,18 +415,18 @@ public class JspcMojo extends AbstractMojo { // open the src web.xml File webXml = getWebXmlFile(); - + if (!webXml.exists()) { getLog().info(webXml.toString() + " does not exist, cannot merge with generated fragment"); return; } - File fragmentWebXml = new File(webXmlFragment); + File fragmentWebXml = new File(webXmlFragment); File mergedWebXml = new File(fragmentWebXml.getParentFile(), "web.xml"); try (BufferedReader webXmlReader = new BufferedReader(new FileReader(webXml)); - PrintWriter mergedWebXmlWriter = new PrintWriter(new FileWriter(mergedWebXml))) + PrintWriter mergedWebXmlWriter = new PrintWriter(new FileWriter(mergedWebXml))) { if (!fragmentWebXml.exists()) @@ -457,8 +441,7 @@ public class JspcMojo extends AbstractMojo // marker boolean atInsertPoint = false; boolean atEOF = false; - String marker = (insertionMarker == null - || insertionMarker.equals("") ? END_OF_WEBAPP : insertionMarker); + String marker = (insertionMarker == null || insertionMarker.equals("") ? END_OF_WEBAPP : insertionMarker); while (!atInsertPoint && !atEOF) { String line = webXmlReader.readLine(); @@ -475,15 +458,14 @@ public class JspcMojo extends AbstractMojo } if (atEOF && !atInsertPoint) - throw new IllegalStateException("web.xml does not contain insertionMarker "+insertionMarker); + throw new IllegalStateException("web.xml does not contain insertionMarker " + insertionMarker); //put in a context init-param to flag that the contents have been precompiled - mergedWebXmlWriter.println(""+PRECOMPILED_FLAG+"true"); - + mergedWebXmlWriter.println("" + PRECOMPILED_FLAG + "true"); // put in the generated fragment - try (BufferedReader fragmentWebXmlReader = - new BufferedReader(new FileReader(fragmentWebXml))) + try (BufferedReader fragmentWebXmlReader = + new BufferedReader(new FileReader(fragmentWebXml))) { IO.copy(fragmentWebXmlReader, mergedWebXmlWriter); @@ -510,12 +492,11 @@ public class JspcMojo extends AbstractMojo /** * Set up the execution classpath for Jasper. - * + * * Put everything in the classesDirectory and all of the dependencies on the * classpath. - * + * * @returns a list of the urls of the dependencies - * @throws Exception */ private List setUpWebAppClassPath() throws Exception { @@ -529,7 +510,7 @@ public class JspcMojo extends AbstractMojo getLog().debug("Adding to classpath classes dir: " + classesDir); //add the dependencies of the webapp (which will form WEB-INF/lib) - for (Iterator iter = project.getArtifacts().iterator(); iter.hasNext();) + for (Iterator iter = project.getArtifacts().iterator(); iter.hasNext(); ) { Artifact artifact = iter.next(); @@ -545,14 +526,11 @@ public class JspcMojo extends AbstractMojo } return urls; } - - - + /** - * @return - * @throws MalformedURLException + * */ - private Set getPluginJars () throws MalformedURLException + private Set getPluginJars() throws MalformedURLException { HashSet pluginJars = new HashSet<>(); for (Iterator iter = pluginArtifacts.iterator(); iter.hasNext(); ) @@ -560,30 +538,29 @@ public class JspcMojo extends AbstractMojo Artifact pluginArtifact = iter.next(); if ("jar".equalsIgnoreCase(pluginArtifact.getType())) { - if (getLog().isDebugEnabled()) { getLog().debug("Adding plugin artifact "+pluginArtifact);} + if (getLog().isDebugEnabled()) + { + getLog().debug("Adding plugin artifact " + pluginArtifact); + } pluginJars.add(pluginArtifact.getFile().toURI().toURL()); } } - + return pluginJars; } - - - + /** - * @param pluginJars - * @return - * @throws MalformedURLException + * */ - private Set getProvidedScopeJars (Set pluginJars) throws MalformedURLException + private Set getProvidedScopeJars(Set pluginJars) throws MalformedURLException { if (!useProvidedScope) return Collections.emptySet(); - + HashSet providedJars = new HashSet<>(); - - for ( Iterator iter = projectArtifacts.iterator(); iter.hasNext(); ) - { + + for (Iterator iter = projectArtifacts.iterator(); iter.hasNext(); ) + { Artifact artifact = iter.next(); if (Artifact.SCOPE_PROVIDED.equals(artifact.getScope())) { @@ -592,39 +569,43 @@ public class JspcMojo extends AbstractMojo if (!pluginJars.contains(jar)) { providedJars.add(jar); - if (getLog().isDebugEnabled()) { getLog().debug("Adding provided artifact: "+artifact);} - } + if (getLog().isDebugEnabled()) + { + getLog().debug("Adding provided artifact: " + artifact); + } + } else { - if (getLog().isDebugEnabled()) { getLog().debug("Skipping provided artifact: "+artifact);} + if (getLog().isDebugEnabled()) + { + getLog().debug("Skipping provided artifact: " + artifact); + } } } } return providedJars; } - - - private File getWebXmlFile () - throws IOException + private File getWebXmlFile() + throws IOException { File file = null; File baseDir = project.getBasedir().getCanonicalFile(); - File defaultWebAppSrcDir = new File (baseDir, "src/main/webapp").getCanonicalFile(); - File webAppSrcDir = new File (webAppSourceDirectory).getCanonicalFile(); - File defaultWebXml = new File (defaultWebAppSrcDir, "web.xml").getCanonicalFile(); - + File defaultWebAppSrcDir = new File(baseDir, "src/main/webapp").getCanonicalFile(); + File webAppSrcDir = new File(webAppSourceDirectory).getCanonicalFile(); + File defaultWebXml = new File(defaultWebAppSrcDir, "web.xml").getCanonicalFile(); + //If the web.xml has been changed from the default, try that - File webXmlFile = new File (webXml).getCanonicalFile(); + File webXmlFile = new File(webXml).getCanonicalFile(); if (webXmlFile.compareTo(defaultWebXml) != 0) { - file = new File (webXml); + file = new File(webXml); return file; } - + //If the web app src directory has not been changed from the default, use whatever //is set for the web.xml location - file = new File (webAppSrcDir, "web.xml"); + file = new File(webAppSrcDir, "web.xml"); return file; } } diff --git a/jetty-maven-plugin/pom.xml b/jetty-maven-plugin/pom.xml index 41fc86cd239..60f0d378879 100644 --- a/jetty-maven-plugin/pom.xml +++ b/jetty-maven-plugin/pom.xml @@ -111,7 +111,7 @@ org.apache.maven maven-artifact - + org.apache.maven maven-core @@ -220,11 +220,11 @@ apache-jstl ${project.version} - - jakarta.transaction - jakarta.transaction-api - compile - + + jakarta.transaction + jakarta.transaction-api + compile + org.eclipse.jetty jetty-home diff --git a/jetty-maven-plugin/src/it/it-parent-pom/pom.xml b/jetty-maven-plugin/src/it/it-parent-pom/pom.xml index ed397c76f56..891289181aa 100644 --- a/jetty-maven-plugin/src/it/it-parent-pom/pom.xml +++ b/jetty-maven-plugin/src/it/it-parent-pom/pom.xml @@ -1,6 +1,5 @@ - + 4.0.0 org.eclipse.jetty.its diff --git a/jetty-maven-plugin/src/it/javax-annotation-api/pom.xml b/jetty-maven-plugin/src/it/javax-annotation-api/pom.xml index 3862a46d228..98f982254f0 100644 --- a/jetty-maven-plugin/src/it/javax-annotation-api/pom.xml +++ b/jetty-maven-plugin/src/it/javax-annotation-api/pom.xml @@ -1,7 +1,6 @@ - + 4.0.0 org.eclipse.jetty.its diff --git a/jetty-maven-plugin/src/it/javax-annotation-api/src/main/java/test/App.java b/jetty-maven-plugin/src/it/javax-annotation-api/src/main/java/test/App.java index 78386d9142b..ab3b8dc2c77 100644 --- a/jetty-maven-plugin/src/it/javax-annotation-api/src/main/java/test/App.java +++ b/jetty-maven-plugin/src/it/javax-annotation-api/src/main/java/test/App.java @@ -18,47 +18,48 @@ package test; +import java.io.InputStream; +import java.util.Properties; +import javax.annotation.PostConstruct; +import javax.annotation.Resource; + import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.boot.builder.SpringApplicationBuilder; import org.springframework.boot.web.servlet.support.SpringBootServletInitializer; import org.springframework.context.annotation.Bean; -import javax.annotation.PostConstruct; -import javax.annotation.Resource; -import java.io.InputStream; -import java.util.Properties; - /** * Hello world! - * */ -public class App extends SpringBootServletInitializer { +public class App extends SpringBootServletInitializer +{ - private Logger logger = LoggerFactory.getLogger( getClass() ); + private Logger logger = LoggerFactory.getLogger(getClass()); - @Resource(name="my.properties") + @Resource(name = "my.properties") private Properties somePropertyFile; @Override - protected SpringApplicationBuilder configure(SpringApplicationBuilder builder ) { - return builder.sources( App.class ); + protected SpringApplicationBuilder configure(SpringApplicationBuilder builder) + { + return builder.sources(App.class); } @PostConstruct - public void done(){ - logger.info( "all good guys get a good {}", somePropertyFile.get( "drink" ) ); - + public void done() + { + logger.info("all good guys get a good {}", somePropertyFile.get("drink")); } @Bean(name = "my.properties") - public Properties getSomeProperties() throws Exception{ - Properties properties = new Properties( ); - try(InputStream inputStream = Thread.currentThread().getContextClassLoader().getResourceAsStream( "my.properties" )) + public Properties getSomeProperties() throws Exception + { + Properties properties = new Properties(); + try (InputStream inputStream = Thread.currentThread().getContextClassLoader().getResourceAsStream("my.properties")) { - properties.load( inputStream ); + properties.load(inputStream); } return properties; } - } diff --git a/jetty-maven-plugin/src/it/jetty-cdi-run-forked/pom.xml b/jetty-maven-plugin/src/it/jetty-cdi-run-forked/pom.xml index 6787fc1d436..7d42ae6b313 100644 --- a/jetty-maven-plugin/src/it/jetty-cdi-run-forked/pom.xml +++ b/jetty-maven-plugin/src/it/jetty-cdi-run-forked/pom.xml @@ -1,7 +1,5 @@ - + 4.0.0 diff --git a/jetty-maven-plugin/src/it/jetty-cdi-run-forked/src/main/java/test/Greeter.java b/jetty-maven-plugin/src/it/jetty-cdi-run-forked/src/main/java/test/Greeter.java index 43d854fc63c..4534448fc90 100644 --- a/jetty-maven-plugin/src/it/jetty-cdi-run-forked/src/main/java/test/Greeter.java +++ b/jetty-maven-plugin/src/it/jetty-cdi-run-forked/src/main/java/test/Greeter.java @@ -18,24 +18,24 @@ package test; +import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; -import java.io.IOException; -@WebServlet( "/*" ) +@WebServlet("/*") public class Greeter extends HttpServlet { @Override - protected void doGet( final HttpServletRequest req, final HttpServletResponse resp ) + protected void doGet(final HttpServletRequest req, final HttpServletResponse resp) throws ServletException, IOException { - String who = req.getParameter( "name" ); + String who = req.getParameter("name"); - resp.getWriter().write( "Hello " + (who == null ? "unknown" : who) ); + resp.getWriter().write("Hello " + (who == null ? "unknown" : who)); } } diff --git a/jetty-maven-plugin/src/it/jetty-deploy-war-mojo-it/pom.xml b/jetty-maven-plugin/src/it/jetty-deploy-war-mojo-it/pom.xml index 880efef22af..217882f4361 100644 --- a/jetty-maven-plugin/src/it/jetty-deploy-war-mojo-it/pom.xml +++ b/jetty-maven-plugin/src/it/jetty-deploy-war-mojo-it/pom.xml @@ -1,6 +1,5 @@ - + 4.0.0 @@ -96,7 +95,6 @@ - org.apache.maven.plugins maven-dependency-plugin diff --git a/jetty-maven-plugin/src/it/jetty-maven-plugin-provided-module-dep/api/pom.xml b/jetty-maven-plugin/src/it/jetty-maven-plugin-provided-module-dep/api/pom.xml index 3bd331ee290..da37bc1e3d6 100755 --- a/jetty-maven-plugin/src/it/jetty-maven-plugin-provided-module-dep/api/pom.xml +++ b/jetty-maven-plugin/src/it/jetty-maven-plugin-provided-module-dep/api/pom.xml @@ -1,5 +1,4 @@ - + 4.0.0 diff --git a/jetty-maven-plugin/src/it/jetty-maven-plugin-provided-module-dep/api/src/main/java/test/Api.java b/jetty-maven-plugin/src/it/jetty-maven-plugin-provided-module-dep/api/src/main/java/test/Api.java index c68931dcabb..cf09b59a299 100755 --- a/jetty-maven-plugin/src/it/jetty-maven-plugin-provided-module-dep/api/src/main/java/test/Api.java +++ b/jetty-maven-plugin/src/it/jetty-maven-plugin-provided-module-dep/api/src/main/java/test/Api.java @@ -16,7 +16,6 @@ // ======================================================================== // - package test; public class Api diff --git a/jetty-maven-plugin/src/it/jetty-maven-plugin-provided-module-dep/pom.xml b/jetty-maven-plugin/src/it/jetty-maven-plugin-provided-module-dep/pom.xml index 6546cb87f21..d7e74fcaa00 100755 --- a/jetty-maven-plugin/src/it/jetty-maven-plugin-provided-module-dep/pom.xml +++ b/jetty-maven-plugin/src/it/jetty-maven-plugin-provided-module-dep/pom.xml @@ -1,5 +1,4 @@ - + 4.0.0 @@ -13,7 +12,6 @@ 1.0-SNAPSHOT pom - api web diff --git a/jetty-maven-plugin/src/it/jetty-maven-plugin-provided-module-dep/web/pom.xml b/jetty-maven-plugin/src/it/jetty-maven-plugin-provided-module-dep/web/pom.xml index 69a29e1e437..dd221342be9 100755 --- a/jetty-maven-plugin/src/it/jetty-maven-plugin-provided-module-dep/web/pom.xml +++ b/jetty-maven-plugin/src/it/jetty-maven-plugin-provided-module-dep/web/pom.xml @@ -1,5 +1,4 @@ - + 4.0.0 diff --git a/jetty-maven-plugin/src/it/jetty-maven-plugin-provided-module-dep/web/src/main/java/test/ClassLoadingTestingServletContextListener.java b/jetty-maven-plugin/src/it/jetty-maven-plugin-provided-module-dep/web/src/main/java/test/ClassLoadingTestingServletContextListener.java index 0118c62bf94..e5c41993eb0 100755 --- a/jetty-maven-plugin/src/it/jetty-maven-plugin-provided-module-dep/web/src/main/java/test/ClassLoadingTestingServletContextListener.java +++ b/jetty-maven-plugin/src/it/jetty-maven-plugin-provided-module-dep/web/src/main/java/test/ClassLoadingTestingServletContextListener.java @@ -16,7 +16,6 @@ // ======================================================================== // - package test; import javax.servlet.ServletContextEvent; @@ -29,13 +28,13 @@ public class ClassLoadingTestingServletContextListener { @Override - public void contextInitialized( ServletContextEvent sce ) + public void contextInitialized(ServletContextEvent sce) { try { Api api = new Api(); } - catch ( java.lang.Exception exception ) + catch (java.lang.Exception exception) { exception.printStackTrace(); } @@ -43,7 +42,7 @@ public class ClassLoadingTestingServletContextListener } @Override - public void contextDestroyed( ServletContextEvent sce ) + public void contextDestroyed(ServletContextEvent sce) { } } diff --git a/jetty-maven-plugin/src/it/jetty-run-distro-mojo-it/jetty-simple-base/pom.xml b/jetty-maven-plugin/src/it/jetty-run-distro-mojo-it/jetty-simple-base/pom.xml index f6e2fd01cc4..5e293380ed8 100644 --- a/jetty-maven-plugin/src/it/jetty-run-distro-mojo-it/jetty-simple-base/pom.xml +++ b/jetty-maven-plugin/src/it/jetty-run-distro-mojo-it/jetty-simple-base/pom.xml @@ -1,6 +1,5 @@ - + 4.0.0 diff --git a/jetty-maven-plugin/src/it/jetty-run-distro-mojo-it/jetty-simple-base/src/main/java/org/eclipse/jetty/its/jetty_run_distro_mojo_it/HelloServlet.java b/jetty-maven-plugin/src/it/jetty-run-distro-mojo-it/jetty-simple-base/src/main/java/org/eclipse/jetty/its/jetty_run_distro_mojo_it/HelloServlet.java index db83c9748a6..72553f5395f 100644 --- a/jetty-maven-plugin/src/it/jetty-run-distro-mojo-it/jetty-simple-base/src/main/java/org/eclipse/jetty/its/jetty_run_distro_mojo_it/HelloServlet.java +++ b/jetty-maven-plugin/src/it/jetty-run-distro-mojo-it/jetty-simple-base/src/main/java/org/eclipse/jetty/its/jetty_run_distro_mojo_it/HelloServlet.java @@ -16,15 +16,14 @@ // ======================================================================== // - package org.eclipse.jetty.its.jetty_run_distro_mojo_it; +import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; -import java.io.IOException; /** * @@ -35,11 +34,11 @@ public class HelloServlet { @Override - protected void doGet( HttpServletRequest req, HttpServletResponse resp ) + protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException - { - String who = req.getParameter( "name" ); + { + String who = req.getParameter("name"); - resp.getWriter().write( "Hello " + (who == null ? "unknown" : who) ); + resp.getWriter().write("Hello " + (who == null ? "unknown" : who)); } } diff --git a/jetty-maven-plugin/src/it/jetty-run-distro-mojo-it/jetty-simple-base/src/main/java/org/eclipse/jetty/its/jetty_run_distro_mojo_it/PingServlet.java b/jetty-maven-plugin/src/it/jetty-run-distro-mojo-it/jetty-simple-base/src/main/java/org/eclipse/jetty/its/jetty_run_distro_mojo_it/PingServlet.java index b0f2d2fb885..4dd7c6f7eb8 100644 --- a/jetty-maven-plugin/src/it/jetty-run-distro-mojo-it/jetty-simple-base/src/main/java/org/eclipse/jetty/its/jetty_run_distro_mojo_it/PingServlet.java +++ b/jetty-maven-plugin/src/it/jetty-run-distro-mojo-it/jetty-simple-base/src/main/java/org/eclipse/jetty/its/jetty_run_distro_mojo_it/PingServlet.java @@ -16,26 +16,24 @@ // ======================================================================== // - package org.eclipse.jetty.its.jetty_run_distro_mojo_it; +import java.io.IOException; import javax.servlet.ServletException; -import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; -import java.io.IOException; public class PingServlet extends HttpServlet { @Override - protected void doGet( HttpServletRequest req, HttpServletResponse resp ) + protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { - String who = req.getParameter( "name" ); + String who = req.getParameter("name"); - resp.getWriter().write( "pong " + (who == null ? "unknown" : who) ); + resp.getWriter().write("pong " + (who == null ? "unknown" : who)); } } diff --git a/jetty-maven-plugin/src/it/jetty-run-distro-mojo-it/jetty-simple-webapp/pom.xml b/jetty-maven-plugin/src/it/jetty-run-distro-mojo-it/jetty-simple-webapp/pom.xml index 5237db3ddcb..1fd3ec985f2 100644 --- a/jetty-maven-plugin/src/it/jetty-run-distro-mojo-it/jetty-simple-webapp/pom.xml +++ b/jetty-maven-plugin/src/it/jetty-run-distro-mojo-it/jetty-simple-webapp/pom.xml @@ -1,6 +1,5 @@ - + 4.0.0 @@ -112,5 +111,4 @@ - diff --git a/jetty-maven-plugin/src/it/jetty-run-distro-mojo-it/pom.xml b/jetty-maven-plugin/src/it/jetty-run-distro-mojo-it/pom.xml index 6ad8242c113..4b7fea358b2 100644 --- a/jetty-maven-plugin/src/it/jetty-run-distro-mojo-it/pom.xml +++ b/jetty-maven-plugin/src/it/jetty-run-distro-mojo-it/pom.xml @@ -1,6 +1,5 @@ - + 4.0.0 diff --git a/jetty-maven-plugin/src/it/jetty-run-forked-mojo-it/jetty-simple-base/pom.xml b/jetty-maven-plugin/src/it/jetty-run-forked-mojo-it/jetty-simple-base/pom.xml index b44e131b87d..f89fb007715 100644 --- a/jetty-maven-plugin/src/it/jetty-run-forked-mojo-it/jetty-simple-base/pom.xml +++ b/jetty-maven-plugin/src/it/jetty-run-forked-mojo-it/jetty-simple-base/pom.xml @@ -1,6 +1,5 @@ - + 4.0.0 diff --git a/jetty-maven-plugin/src/it/jetty-run-forked-mojo-it/jetty-simple-base/src/main/java/org/eclipse/jetty/its/jetty_run_forked_mojo_it/HelloServlet.java b/jetty-maven-plugin/src/it/jetty-run-forked-mojo-it/jetty-simple-base/src/main/java/org/eclipse/jetty/its/jetty_run_forked_mojo_it/HelloServlet.java index 5d6de2e2083..267d52bafaa 100644 --- a/jetty-maven-plugin/src/it/jetty-run-forked-mojo-it/jetty-simple-base/src/main/java/org/eclipse/jetty/its/jetty_run_forked_mojo_it/HelloServlet.java +++ b/jetty-maven-plugin/src/it/jetty-run-forked-mojo-it/jetty-simple-base/src/main/java/org/eclipse/jetty/its/jetty_run_forked_mojo_it/HelloServlet.java @@ -16,15 +16,14 @@ // ======================================================================== // - package org.eclipse.jetty.its.jetty_run_forked_mojo_it; +import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; -import java.io.IOException; /** * @@ -35,11 +34,11 @@ public class HelloServlet { @Override - protected void doGet( HttpServletRequest req, HttpServletResponse resp ) + protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { - String who = req.getParameter( "name" ); + String who = req.getParameter("name"); - resp.getWriter().write( "Hello " + (who == null ? "unknown" : who) ); + resp.getWriter().write("Hello " + (who == null ? "unknown" : who)); } } diff --git a/jetty-maven-plugin/src/it/jetty-run-forked-mojo-it/jetty-simple-base/src/main/java/org/eclipse/jetty/its/jetty_run_forked_mojo_it/PingServlet.java b/jetty-maven-plugin/src/it/jetty-run-forked-mojo-it/jetty-simple-base/src/main/java/org/eclipse/jetty/its/jetty_run_forked_mojo_it/PingServlet.java index 28d55df50db..386bbe55295 100644 --- a/jetty-maven-plugin/src/it/jetty-run-forked-mojo-it/jetty-simple-base/src/main/java/org/eclipse/jetty/its/jetty_run_forked_mojo_it/PingServlet.java +++ b/jetty-maven-plugin/src/it/jetty-run-forked-mojo-it/jetty-simple-base/src/main/java/org/eclipse/jetty/its/jetty_run_forked_mojo_it/PingServlet.java @@ -16,26 +16,24 @@ // ======================================================================== // - package org.eclipse.jetty.its.jetty_run_forked_mojo_it; +import java.io.IOException; import javax.servlet.ServletException; -import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; -import java.io.IOException; public class PingServlet extends HttpServlet { @Override - protected void doGet( HttpServletRequest req, HttpServletResponse resp ) + protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { - String who = req.getParameter( "name" ); + String who = req.getParameter("name"); - resp.getWriter().write( "pong " + (who == null ? "unknown" : who) ); + resp.getWriter().write("pong " + (who == null ? "unknown" : who)); } } diff --git a/jetty-maven-plugin/src/it/jetty-run-forked-mojo-it/jetty-simple-webapp/pom.xml b/jetty-maven-plugin/src/it/jetty-run-forked-mojo-it/jetty-simple-webapp/pom.xml index 9ba881556cf..386ae2e2531 100644 --- a/jetty-maven-plugin/src/it/jetty-run-forked-mojo-it/jetty-simple-webapp/pom.xml +++ b/jetty-maven-plugin/src/it/jetty-run-forked-mojo-it/jetty-simple-webapp/pom.xml @@ -1,6 +1,5 @@ - + 4.0.0 @@ -97,7 +96,7 @@ ${basedir}/src/config/jetty.xml ${jetty.jvmArgs} - jetty.port.file=${jetty.port.file} + jetty.port.file=${jetty.port.file} @@ -115,5 +114,4 @@ - diff --git a/jetty-maven-plugin/src/it/jetty-run-forked-mojo-it/pom.xml b/jetty-maven-plugin/src/it/jetty-run-forked-mojo-it/pom.xml index 93e5bc38b15..813ecc5bfd0 100644 --- a/jetty-maven-plugin/src/it/jetty-run-forked-mojo-it/pom.xml +++ b/jetty-maven-plugin/src/it/jetty-run-forked-mojo-it/pom.xml @@ -1,6 +1,5 @@ - + 4.0.0 diff --git a/jetty-maven-plugin/src/it/jetty-run-mojo-it/jetty-simple-base/pom.xml b/jetty-maven-plugin/src/it/jetty-run-mojo-it/jetty-simple-base/pom.xml index 2bebc902d0b..601aae0d1d1 100644 --- a/jetty-maven-plugin/src/it/jetty-run-mojo-it/jetty-simple-base/pom.xml +++ b/jetty-maven-plugin/src/it/jetty-run-mojo-it/jetty-simple-base/pom.xml @@ -1,6 +1,5 @@ - + 4.0.0 diff --git a/jetty-maven-plugin/src/it/jetty-run-mojo-it/jetty-simple-base/src/main/java/org/eclipse/jetty/its/jetty_run_mojo_it/HelloServlet.java b/jetty-maven-plugin/src/it/jetty-run-mojo-it/jetty-simple-base/src/main/java/org/eclipse/jetty/its/jetty_run_mojo_it/HelloServlet.java index 8ef4c4841a1..5cf82ccf88e 100644 --- a/jetty-maven-plugin/src/it/jetty-run-mojo-it/jetty-simple-base/src/main/java/org/eclipse/jetty/its/jetty_run_mojo_it/HelloServlet.java +++ b/jetty-maven-plugin/src/it/jetty-run-mojo-it/jetty-simple-base/src/main/java/org/eclipse/jetty/its/jetty_run_mojo_it/HelloServlet.java @@ -16,15 +16,14 @@ // ======================================================================== // - package org.eclipse.jetty.its.jetty_run_mojo_it; +import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; -import java.io.IOException; /** * @@ -35,11 +34,11 @@ public class HelloServlet { @Override - protected void doGet( HttpServletRequest req, HttpServletResponse resp ) + protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { - String who = req.getParameter( "name" ); + String who = req.getParameter("name"); - resp.getWriter().write( "Hello " + (who == null ? "unknown" : who) ); + resp.getWriter().write("Hello " + (who == null ? "unknown" : who)); } } diff --git a/jetty-maven-plugin/src/it/jetty-run-mojo-it/jetty-simple-base/src/main/java/org/eclipse/jetty/its/jetty_run_mojo_it/PingServlet.java b/jetty-maven-plugin/src/it/jetty-run-mojo-it/jetty-simple-base/src/main/java/org/eclipse/jetty/its/jetty_run_mojo_it/PingServlet.java index ce057142549..48152a7b735 100644 --- a/jetty-maven-plugin/src/it/jetty-run-mojo-it/jetty-simple-base/src/main/java/org/eclipse/jetty/its/jetty_run_mojo_it/PingServlet.java +++ b/jetty-maven-plugin/src/it/jetty-run-mojo-it/jetty-simple-base/src/main/java/org/eclipse/jetty/its/jetty_run_mojo_it/PingServlet.java @@ -16,26 +16,24 @@ // ======================================================================== // - package org.eclipse.jetty.its.jetty_run_mojo_it; +import java.io.IOException; import javax.servlet.ServletException; -import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; -import java.io.IOException; public class PingServlet extends HttpServlet { @Override - protected void doGet( HttpServletRequest req, HttpServletResponse resp ) + protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { - String who = req.getParameter( "name" ); + String who = req.getParameter("name"); - resp.getWriter().write( "pong " + (who == null ? "unknown" : who) ); + resp.getWriter().write("pong " + (who == null ? "unknown" : who)); } } diff --git a/jetty-maven-plugin/src/it/jetty-run-mojo-it/jetty-simple-base/src/test/java/org/eclipse/jetty/its/jetty_run_mojo_it_test/HelloTestServlet.java b/jetty-maven-plugin/src/it/jetty-run-mojo-it/jetty-simple-base/src/test/java/org/eclipse/jetty/its/jetty_run_mojo_it_test/HelloTestServlet.java index dbacf9498f3..91c72bacf55 100644 --- a/jetty-maven-plugin/src/it/jetty-run-mojo-it/jetty-simple-base/src/test/java/org/eclipse/jetty/its/jetty_run_mojo_it_test/HelloTestServlet.java +++ b/jetty-maven-plugin/src/it/jetty-run-mojo-it/jetty-simple-base/src/test/java/org/eclipse/jetty/its/jetty_run_mojo_it_test/HelloTestServlet.java @@ -16,15 +16,14 @@ // ======================================================================== // - package org.eclipse.jetty.its.jetty_run_mojo_it_test; +import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; -import java.io.IOException; /** * @@ -35,11 +34,11 @@ public class HelloTestServlet { @Override - protected void doGet( HttpServletRequest req, HttpServletResponse resp ) + protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { - String who = req.getParameter( "name" ); + String who = req.getParameter("name"); - resp.getWriter().write( "Hello from test " + (who == null ? "unknown" : who) ); + resp.getWriter().write("Hello from test " + (who == null ? "unknown" : who)); } } diff --git a/jetty-maven-plugin/src/it/jetty-run-mojo-it/jetty-simple-webapp/pom.xml b/jetty-maven-plugin/src/it/jetty-run-mojo-it/jetty-simple-webapp/pom.xml index d0fb927984a..d17cc126f78 100644 --- a/jetty-maven-plugin/src/it/jetty-run-mojo-it/jetty-simple-webapp/pom.xml +++ b/jetty-maven-plugin/src/it/jetty-run-mojo-it/jetty-simple-webapp/pom.xml @@ -1,6 +1,5 @@ - + 4.0.0 @@ -126,5 +125,4 @@ - diff --git a/jetty-maven-plugin/src/it/jetty-run-mojo-it/pom.xml b/jetty-maven-plugin/src/it/jetty-run-mojo-it/pom.xml index 453b36ef875..d082c71bbe5 100644 --- a/jetty-maven-plugin/src/it/jetty-run-mojo-it/pom.xml +++ b/jetty-maven-plugin/src/it/jetty-run-mojo-it/pom.xml @@ -1,6 +1,5 @@ - + 4.0.0 diff --git a/jetty-maven-plugin/src/it/jetty-run-mojo-jsp/pom.xml b/jetty-maven-plugin/src/it/jetty-run-mojo-jsp/pom.xml index 932bac3b7fb..2b8d3949624 100644 --- a/jetty-maven-plugin/src/it/jetty-run-mojo-jsp/pom.xml +++ b/jetty-maven-plugin/src/it/jetty-run-mojo-jsp/pom.xml @@ -1,6 +1,5 @@ - + 4.0.0 @@ -101,5 +100,4 @@ - diff --git a/jetty-maven-plugin/src/it/jetty-run-mojo-jsp/src/main/java/com/acme/Counter.java b/jetty-maven-plugin/src/it/jetty-run-mojo-jsp/src/main/java/com/acme/Counter.java index 3c87fc55cfa..4ff284e5dbe 100644 --- a/jetty-maven-plugin/src/it/jetty-run-mojo-jsp/src/main/java/com/acme/Counter.java +++ b/jetty-maven-plugin/src/it/jetty-run-mojo-jsp/src/main/java/com/acme/Counter.java @@ -21,7 +21,7 @@ package com.acme; @SuppressWarnings("serial") public class Counter implements java.io.Serializable { - int counter=0; + int counter = 0; String last; public int getCount() @@ -30,11 +30,13 @@ public class Counter implements java.io.Serializable return counter; } - public void setLast(String uri) { - last=uri; + public void setLast(String uri) + { + last = uri; } - public String getLast() { + public String getLast() + { return last; } } diff --git a/jetty-maven-plugin/src/it/jetty-run-mojo-multi-module-single-war-it/common/pom.xml b/jetty-maven-plugin/src/it/jetty-run-mojo-multi-module-single-war-it/common/pom.xml index 045791a4491..06de7ece78d 100644 --- a/jetty-maven-plugin/src/it/jetty-run-mojo-multi-module-single-war-it/common/pom.xml +++ b/jetty-maven-plugin/src/it/jetty-run-mojo-multi-module-single-war-it/common/pom.xml @@ -1,6 +1,5 @@ - + 4.0.0 test.jetty-run-mojo-multi-module-single-war-it diff --git a/jetty-maven-plugin/src/it/jetty-run-mojo-multi-module-single-war-it/module/module-api/pom.xml b/jetty-maven-plugin/src/it/jetty-run-mojo-multi-module-single-war-it/module/module-api/pom.xml index 33d0edf5d8d..f3a237dbd74 100644 --- a/jetty-maven-plugin/src/it/jetty-run-mojo-multi-module-single-war-it/module/module-api/pom.xml +++ b/jetty-maven-plugin/src/it/jetty-run-mojo-multi-module-single-war-it/module/module-api/pom.xml @@ -1,6 +1,5 @@ - + 4.0.0 test.jetty-run-mojo-multi-module-single-war-it diff --git a/jetty-maven-plugin/src/it/jetty-run-mojo-multi-module-single-war-it/module/module-impl/pom.xml b/jetty-maven-plugin/src/it/jetty-run-mojo-multi-module-single-war-it/module/module-impl/pom.xml index 8ae3faa0415..0e26990e518 100644 --- a/jetty-maven-plugin/src/it/jetty-run-mojo-multi-module-single-war-it/module/module-impl/pom.xml +++ b/jetty-maven-plugin/src/it/jetty-run-mojo-multi-module-single-war-it/module/module-impl/pom.xml @@ -1,6 +1,5 @@ - + 4.0.0 test.jetty-run-mojo-multi-module-single-war-it diff --git a/jetty-maven-plugin/src/it/jetty-run-mojo-multi-module-single-war-it/module/module-impl/src/main/java/mca/module/ModuleImpl.java b/jetty-maven-plugin/src/it/jetty-run-mojo-multi-module-single-war-it/module/module-impl/src/main/java/mca/module/ModuleImpl.java index ef59d156fcc..4b00df5286a 100644 --- a/jetty-maven-plugin/src/it/jetty-run-mojo-multi-module-single-war-it/module/module-impl/src/main/java/mca/module/ModuleImpl.java +++ b/jetty-maven-plugin/src/it/jetty-run-mojo-multi-module-single-war-it/module/module-impl/src/main/java/mca/module/ModuleImpl.java @@ -24,5 +24,4 @@ public class ModuleImpl implements ModuleApi { private static final CommonService cs = new CommonService(); - } diff --git a/jetty-maven-plugin/src/it/jetty-run-mojo-multi-module-single-war-it/module/pom.xml b/jetty-maven-plugin/src/it/jetty-run-mojo-multi-module-single-war-it/module/pom.xml index 80ebae8d327..f91edba7216 100644 --- a/jetty-maven-plugin/src/it/jetty-run-mojo-multi-module-single-war-it/module/pom.xml +++ b/jetty-maven-plugin/src/it/jetty-run-mojo-multi-module-single-war-it/module/pom.xml @@ -1,6 +1,5 @@ - + 4.0.0 test.jetty-run-mojo-multi-module-single-war-it diff --git a/jetty-maven-plugin/src/it/jetty-run-mojo-multi-module-single-war-it/pom.xml b/jetty-maven-plugin/src/it/jetty-run-mojo-multi-module-single-war-it/pom.xml index 40e1ddbd775..a098c9a06d1 100644 --- a/jetty-maven-plugin/src/it/jetty-run-mojo-multi-module-single-war-it/pom.xml +++ b/jetty-maven-plugin/src/it/jetty-run-mojo-multi-module-single-war-it/pom.xml @@ -1,6 +1,5 @@ - + 4.0.0 diff --git a/jetty-maven-plugin/src/it/jetty-run-mojo-multi-module-single-war-it/webapp-war/pom.xml b/jetty-maven-plugin/src/it/jetty-run-mojo-multi-module-single-war-it/webapp-war/pom.xml index b1ad640a9e8..99c213c243b 100644 --- a/jetty-maven-plugin/src/it/jetty-run-mojo-multi-module-single-war-it/webapp-war/pom.xml +++ b/jetty-maven-plugin/src/it/jetty-run-mojo-multi-module-single-war-it/webapp-war/pom.xml @@ -1,6 +1,5 @@ - + 4.0.0 test.jetty-run-mojo-multi-module-single-war-it diff --git a/jetty-maven-plugin/src/it/jetty-run-mojo-multi-module-single-war-it/webapp-war/src/main/java/mca/webapp/WebAppServletListener.java b/jetty-maven-plugin/src/it/jetty-run-mojo-multi-module-single-war-it/webapp-war/src/main/java/mca/webapp/WebAppServletListener.java index af8b389bd18..c7ba86c9802 100644 --- a/jetty-maven-plugin/src/it/jetty-run-mojo-multi-module-single-war-it/webapp-war/src/main/java/mca/webapp/WebAppServletListener.java +++ b/jetty-maven-plugin/src/it/jetty-run-mojo-multi-module-single-war-it/webapp-war/src/main/java/mca/webapp/WebAppServletListener.java @@ -18,11 +18,10 @@ package mca.webapp; +import java.net.URL; import javax.servlet.ServletContextEvent; import javax.servlet.ServletContextListener; -import java.net.URL; - import static java.lang.String.format; public class WebAppServletListener implements ServletContextListener @@ -49,8 +48,8 @@ public class WebAppServletListener implements ServletContextListener String res = className.replaceAll("\\.", "/") + ".class"; URL url = Thread.currentThread().getContextClassLoader().getResource(res); System.out.println( - format("(%sa) >> %s loaded from %s << (%sb)", - counter, className, url, counter) + format("(%sa) >> %s loaded from %s << (%sb)", + counter, className, url, counter) ); } } diff --git a/jetty-maven-plugin/src/it/jetty-run-war-exploded-mojo-it/jetty-simple-base/pom.xml b/jetty-maven-plugin/src/it/jetty-run-war-exploded-mojo-it/jetty-simple-base/pom.xml index ebca593cdc4..348a3bc6e8d 100644 --- a/jetty-maven-plugin/src/it/jetty-run-war-exploded-mojo-it/jetty-simple-base/pom.xml +++ b/jetty-maven-plugin/src/it/jetty-run-war-exploded-mojo-it/jetty-simple-base/pom.xml @@ -1,6 +1,5 @@ - + 4.0.0 diff --git a/jetty-maven-plugin/src/it/jetty-run-war-exploded-mojo-it/jetty-simple-base/src/main/java/org/eclipse/jetty/its/jetty_run_war_exploded_mojo_it/HelloServlet.java b/jetty-maven-plugin/src/it/jetty-run-war-exploded-mojo-it/jetty-simple-base/src/main/java/org/eclipse/jetty/its/jetty_run_war_exploded_mojo_it/HelloServlet.java index cc6cf89df32..01cadf64ae9 100644 --- a/jetty-maven-plugin/src/it/jetty-run-war-exploded-mojo-it/jetty-simple-base/src/main/java/org/eclipse/jetty/its/jetty_run_war_exploded_mojo_it/HelloServlet.java +++ b/jetty-maven-plugin/src/it/jetty-run-war-exploded-mojo-it/jetty-simple-base/src/main/java/org/eclipse/jetty/its/jetty_run_war_exploded_mojo_it/HelloServlet.java @@ -16,15 +16,14 @@ // ======================================================================== // - package org.eclipse.jetty.its.jetty_run_war_exploded_mojo_it; +import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; -import java.io.IOException; /** * @@ -35,11 +34,11 @@ public class HelloServlet { @Override - protected void doGet( HttpServletRequest req, HttpServletResponse resp ) + protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { - String who = req.getParameter( "name" ); + String who = req.getParameter("name"); - resp.getWriter().write( "Hello " + (who == null ? "unknown" : who) ); + resp.getWriter().write("Hello " + (who == null ? "unknown" : who)); } } diff --git a/jetty-maven-plugin/src/it/jetty-run-war-exploded-mojo-it/jetty-simple-base/src/main/java/org/eclipse/jetty/its/jetty_run_war_exploded_mojo_it/PingServlet.java b/jetty-maven-plugin/src/it/jetty-run-war-exploded-mojo-it/jetty-simple-base/src/main/java/org/eclipse/jetty/its/jetty_run_war_exploded_mojo_it/PingServlet.java index d14e2838461..c4abedfae8e 100644 --- a/jetty-maven-plugin/src/it/jetty-run-war-exploded-mojo-it/jetty-simple-base/src/main/java/org/eclipse/jetty/its/jetty_run_war_exploded_mojo_it/PingServlet.java +++ b/jetty-maven-plugin/src/it/jetty-run-war-exploded-mojo-it/jetty-simple-base/src/main/java/org/eclipse/jetty/its/jetty_run_war_exploded_mojo_it/PingServlet.java @@ -16,26 +16,24 @@ // ======================================================================== // - package org.eclipse.jetty.its.jetty_run_war_exploded_mojo_it; +import java.io.IOException; import javax.servlet.ServletException; -import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; -import java.io.IOException; public class PingServlet extends HttpServlet { @Override - protected void doGet( HttpServletRequest req, HttpServletResponse resp ) + protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { - String who = req.getParameter( "name" ); + String who = req.getParameter("name"); - resp.getWriter().write( "pong " + (who == null ? "unknown" : who) ); + resp.getWriter().write("pong " + (who == null ? "unknown" : who)); } } diff --git a/jetty-maven-plugin/src/it/jetty-run-war-exploded-mojo-it/jetty-simple-webapp/pom.xml b/jetty-maven-plugin/src/it/jetty-run-war-exploded-mojo-it/jetty-simple-webapp/pom.xml index ccb42203249..7c9eae6c588 100644 --- a/jetty-maven-plugin/src/it/jetty-run-war-exploded-mojo-it/jetty-simple-webapp/pom.xml +++ b/jetty-maven-plugin/src/it/jetty-run-war-exploded-mojo-it/jetty-simple-webapp/pom.xml @@ -1,6 +1,5 @@ - + 4.0.0 @@ -121,5 +120,4 @@ - diff --git a/jetty-maven-plugin/src/it/jetty-run-war-exploded-mojo-it/pom.xml b/jetty-maven-plugin/src/it/jetty-run-war-exploded-mojo-it/pom.xml index ad5a29cad54..b6ac179988a 100644 --- a/jetty-maven-plugin/src/it/jetty-run-war-exploded-mojo-it/pom.xml +++ b/jetty-maven-plugin/src/it/jetty-run-war-exploded-mojo-it/pom.xml @@ -1,6 +1,5 @@ - + 4.0.0 diff --git a/jetty-maven-plugin/src/it/jetty-run-war-mojo-it/jetty-simple-base/pom.xml b/jetty-maven-plugin/src/it/jetty-run-war-mojo-it/jetty-simple-base/pom.xml index aa635b3af2a..a241cfa2f58 100644 --- a/jetty-maven-plugin/src/it/jetty-run-war-mojo-it/jetty-simple-base/pom.xml +++ b/jetty-maven-plugin/src/it/jetty-run-war-mojo-it/jetty-simple-base/pom.xml @@ -1,6 +1,5 @@ - + 4.0.0 diff --git a/jetty-maven-plugin/src/it/jetty-run-war-mojo-it/jetty-simple-base/src/main/java/org/eclipse/jetty/its/jetty_run_mojo_it/HelloServlet.java b/jetty-maven-plugin/src/it/jetty-run-war-mojo-it/jetty-simple-base/src/main/java/org/eclipse/jetty/its/jetty_run_mojo_it/HelloServlet.java index 8ef4c4841a1..5cf82ccf88e 100644 --- a/jetty-maven-plugin/src/it/jetty-run-war-mojo-it/jetty-simple-base/src/main/java/org/eclipse/jetty/its/jetty_run_mojo_it/HelloServlet.java +++ b/jetty-maven-plugin/src/it/jetty-run-war-mojo-it/jetty-simple-base/src/main/java/org/eclipse/jetty/its/jetty_run_mojo_it/HelloServlet.java @@ -16,15 +16,14 @@ // ======================================================================== // - package org.eclipse.jetty.its.jetty_run_mojo_it; +import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; -import java.io.IOException; /** * @@ -35,11 +34,11 @@ public class HelloServlet { @Override - protected void doGet( HttpServletRequest req, HttpServletResponse resp ) + protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { - String who = req.getParameter( "name" ); + String who = req.getParameter("name"); - resp.getWriter().write( "Hello " + (who == null ? "unknown" : who) ); + resp.getWriter().write("Hello " + (who == null ? "unknown" : who)); } } diff --git a/jetty-maven-plugin/src/it/jetty-run-war-mojo-it/jetty-simple-base/src/main/java/org/eclipse/jetty/its/jetty_run_mojo_it/PingServlet.java b/jetty-maven-plugin/src/it/jetty-run-war-mojo-it/jetty-simple-base/src/main/java/org/eclipse/jetty/its/jetty_run_mojo_it/PingServlet.java index ce057142549..48152a7b735 100644 --- a/jetty-maven-plugin/src/it/jetty-run-war-mojo-it/jetty-simple-base/src/main/java/org/eclipse/jetty/its/jetty_run_mojo_it/PingServlet.java +++ b/jetty-maven-plugin/src/it/jetty-run-war-mojo-it/jetty-simple-base/src/main/java/org/eclipse/jetty/its/jetty_run_mojo_it/PingServlet.java @@ -16,26 +16,24 @@ // ======================================================================== // - package org.eclipse.jetty.its.jetty_run_mojo_it; +import java.io.IOException; import javax.servlet.ServletException; -import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; -import java.io.IOException; public class PingServlet extends HttpServlet { @Override - protected void doGet( HttpServletRequest req, HttpServletResponse resp ) + protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { - String who = req.getParameter( "name" ); + String who = req.getParameter("name"); - resp.getWriter().write( "pong " + (who == null ? "unknown" : who) ); + resp.getWriter().write("pong " + (who == null ? "unknown" : who)); } } diff --git a/jetty-maven-plugin/src/it/jetty-run-war-mojo-it/jetty-simple-webapp/pom.xml b/jetty-maven-plugin/src/it/jetty-run-war-mojo-it/jetty-simple-webapp/pom.xml index 8b6c7257ac4..67b31e5a081 100644 --- a/jetty-maven-plugin/src/it/jetty-run-war-mojo-it/jetty-simple-webapp/pom.xml +++ b/jetty-maven-plugin/src/it/jetty-run-war-mojo-it/jetty-simple-webapp/pom.xml @@ -1,6 +1,5 @@ - + 4.0.0 @@ -14,7 +13,6 @@ Jetty :: Simple :: Webapp - ${project.build.directory}/jetty-run-war-port.txt @@ -121,5 +119,4 @@ - diff --git a/jetty-maven-plugin/src/it/jetty-run-war-mojo-it/pom.xml b/jetty-maven-plugin/src/it/jetty-run-war-mojo-it/pom.xml index 96f0c6bc8ef..3ae620b58ad 100644 --- a/jetty-maven-plugin/src/it/jetty-run-war-mojo-it/pom.xml +++ b/jetty-maven-plugin/src/it/jetty-run-war-mojo-it/pom.xml @@ -1,6 +1,5 @@ - + 4.0.0 diff --git a/jetty-maven-plugin/src/it/jetty-start-mojo-it/jetty-simple-base/pom.xml b/jetty-maven-plugin/src/it/jetty-start-mojo-it/jetty-simple-base/pom.xml index 399a0f4639f..af65d2b0377 100644 --- a/jetty-maven-plugin/src/it/jetty-start-mojo-it/jetty-simple-base/pom.xml +++ b/jetty-maven-plugin/src/it/jetty-start-mojo-it/jetty-simple-base/pom.xml @@ -1,6 +1,5 @@ - + 4.0.0 diff --git a/jetty-maven-plugin/src/it/jetty-start-mojo-it/jetty-simple-base/src/main/java/org/eclipse/jetty/its/jetty_start_mojo_it/HelloServlet.java b/jetty-maven-plugin/src/it/jetty-start-mojo-it/jetty-simple-base/src/main/java/org/eclipse/jetty/its/jetty_start_mojo_it/HelloServlet.java index 75912023601..64df66b845e 100644 --- a/jetty-maven-plugin/src/it/jetty-start-mojo-it/jetty-simple-base/src/main/java/org/eclipse/jetty/its/jetty_start_mojo_it/HelloServlet.java +++ b/jetty-maven-plugin/src/it/jetty-start-mojo-it/jetty-simple-base/src/main/java/org/eclipse/jetty/its/jetty_start_mojo_it/HelloServlet.java @@ -16,15 +16,14 @@ // ======================================================================== // - package org.eclipse.jetty.its.jetty_start_mojo_it; +import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; -import java.io.IOException; /** * @@ -35,11 +34,11 @@ public class HelloServlet { @Override - protected void doGet( HttpServletRequest req, HttpServletResponse resp ) + protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { - String who = req.getParameter( "name" ); + String who = req.getParameter("name"); - resp.getWriter().write( "Hello " + (who == null ? "unknown" : who) ); + resp.getWriter().write("Hello " + (who == null ? "unknown" : who)); } } diff --git a/jetty-maven-plugin/src/it/jetty-start-mojo-it/jetty-simple-base/src/main/java/org/eclipse/jetty/its/jetty_start_mojo_it/PingServlet.java b/jetty-maven-plugin/src/it/jetty-start-mojo-it/jetty-simple-base/src/main/java/org/eclipse/jetty/its/jetty_start_mojo_it/PingServlet.java index 3f0adfdf342..d4718cc2662 100644 --- a/jetty-maven-plugin/src/it/jetty-start-mojo-it/jetty-simple-base/src/main/java/org/eclipse/jetty/its/jetty_start_mojo_it/PingServlet.java +++ b/jetty-maven-plugin/src/it/jetty-start-mojo-it/jetty-simple-base/src/main/java/org/eclipse/jetty/its/jetty_start_mojo_it/PingServlet.java @@ -16,26 +16,24 @@ // ======================================================================== // - package org.eclipse.jetty.its.jetty_start_mojo_it; +import java.io.IOException; import javax.servlet.ServletException; -import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; -import java.io.IOException; public class PingServlet extends HttpServlet { @Override - protected void doGet( HttpServletRequest req, HttpServletResponse resp ) + protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { - String who = req.getParameter( "name" ); + String who = req.getParameter("name"); - resp.getWriter().write( "pong " + (who == null ? "unknown" : who) ); + resp.getWriter().write("pong " + (who == null ? "unknown" : who)); } } diff --git a/jetty-maven-plugin/src/it/jetty-start-mojo-it/jetty-simple-webapp/pom.xml b/jetty-maven-plugin/src/it/jetty-start-mojo-it/jetty-simple-webapp/pom.xml index d807ad4c34f..9c4cf1d1c51 100644 --- a/jetty-maven-plugin/src/it/jetty-start-mojo-it/jetty-simple-webapp/pom.xml +++ b/jetty-maven-plugin/src/it/jetty-start-mojo-it/jetty-simple-webapp/pom.xml @@ -1,6 +1,5 @@ - + 4.0.0 @@ -87,13 +86,13 @@ start - + jetty.port.file ${jetty.port.file} - - ${basedir}/src/config/jetty.xml + + ${basedir}/src/config/jetty.xml @@ -101,5 +100,4 @@ - diff --git a/jetty-maven-plugin/src/it/jetty-start-mojo-it/pom.xml b/jetty-maven-plugin/src/it/jetty-start-mojo-it/pom.xml index bd5cb98a9b7..040eeb56b96 100644 --- a/jetty-maven-plugin/src/it/jetty-start-mojo-it/pom.xml +++ b/jetty-maven-plugin/src/it/jetty-start-mojo-it/pom.xml @@ -1,6 +1,5 @@ - + 4.0.0 diff --git a/jetty-maven-plugin/src/it/run-mojo-gwt-it/beer-client/src/main/java/org/olamy/App.java b/jetty-maven-plugin/src/it/run-mojo-gwt-it/beer-client/src/main/java/org/olamy/App.java index 1e02da18d13..e6e8d9d8993 100644 --- a/jetty-maven-plugin/src/it/run-mojo-gwt-it/beer-client/src/main/java/org/olamy/App.java +++ b/jetty-maven-plugin/src/it/run-mojo-gwt-it/beer-client/src/main/java/org/olamy/App.java @@ -38,25 +38,27 @@ import com.google.gwt.user.client.ui.VerticalPanel; /** * Entry point classes define onModuleLoad(). */ -public class App implements EntryPoint { - /** - * The message displayed to the user when the server cannot be reached or - * returns an error. - */ - private static final String SERVER_ERROR = "An error occurred while " - + "attempting to contact the server. Please check your network " - + "connection and try again."; +public class App implements EntryPoint +{ + /** + * The message displayed to the user when the server cannot be reached or + * returns an error. + */ + private static final String SERVER_ERROR = "An error occurred while " + + "attempting to contact the server. Please check your network " + + "connection and try again."; /** * Create a remote service proxy to talk to the server-side Greeting service. */ private final GreetingServiceAsync greetingService = GWT - .create(GreetingService.class); + .create(GreetingService.class); /** * This is the entry point method. */ - public void onModuleLoad() { + public void onModuleLoad() + { final Button sendButton = new Button("Send"); final TextBox nameField = new TextBox(); nameField.setText("GWT User"); @@ -95,8 +97,10 @@ public class App implements EntryPoint { dialogBox.setWidget(dialogVPanel); // Add a handler to close the DialogBox - closeButton.addClickHandler(new ClickHandler() { - public void onClick(ClickEvent event) { + closeButton.addClickHandler(new ClickHandler() + { + public void onClick(ClickEvent event) + { dialogBox.hide(); sendButton.setEnabled(true); sendButton.setFocus(true); @@ -104,19 +108,23 @@ public class App implements EntryPoint { }); // Create a handler for the sendButton and nameField - class MyHandler implements ClickHandler, KeyUpHandler { + class MyHandler implements ClickHandler, KeyUpHandler + { /** * Fired when the user clicks on the sendButton. */ - public void onClick(ClickEvent event) { + public void onClick(ClickEvent event) + { sendNameToServer(); } /** * Fired when the user types in the nameField. */ - public void onKeyUp(KeyUpEvent event) { - if (event.getNativeKeyCode() == KeyCodes.KEY_ENTER) { + public void onKeyUp(KeyUpEvent event) + { + if (event.getNativeKeyCode() == KeyCodes.KEY_ENTER) + { sendNameToServer(); } } @@ -124,11 +132,13 @@ public class App implements EntryPoint { /** * Send the name from the nameField to the server and wait for a response. */ - private void sendNameToServer() { + private void sendNameToServer() + { // First, we validate the input. errorLabel.setText(""); String textToServer = nameField.getText(); - if (!FieldVerifier.isValidName(textToServer)) { + if (!FieldVerifier.isValidName(textToServer)) + { errorLabel.setText("Please enter at least four characters"); return; } @@ -138,33 +148,36 @@ public class App implements EntryPoint { textToServerLabel.setText(textToServer); serverResponseLabel.setText(""); greetingService.greetServer(textToServer, - new AsyncCallback() { - public void onFailure(Throwable caught) { - // Show the RPC error message to the user - dialogBox - .setText("Remote Procedure Call - Failure"); - serverResponseLabel - .addStyleName("serverResponseLabelError"); - serverResponseLabel.setHTML(SERVER_ERROR); - dialogBox.center(); - closeButton.setFocus(true); - } + new AsyncCallback() + { + public void onFailure(Throwable caught) + { + // Show the RPC error message to the user + dialogBox + .setText("Remote Procedure Call - Failure"); + serverResponseLabel + .addStyleName("serverResponseLabelError"); + serverResponseLabel.setHTML(SERVER_ERROR); + dialogBox.center(); + closeButton.setFocus(true); + } - public void onSuccess(GreetingResponse result) { - dialogBox.setText("Remote Procedure Call"); - serverResponseLabel - .removeStyleName("serverResponseLabelError"); - serverResponseLabel.setHTML(new SafeHtmlBuilder() - .appendEscaped(result.getGreeting()) - .appendHtmlConstant("

    I am running ") - .appendEscaped(result.getServerInfo()) - .appendHtmlConstant(".

    It looks like you are using:
    ") - .appendEscaped(result.getUserAgent()) - .toSafeHtml()); - dialogBox.center(); - closeButton.setFocus(true); - } - }); + public void onSuccess(GreetingResponse result) + { + dialogBox.setText("Remote Procedure Call"); + serverResponseLabel + .removeStyleName("serverResponseLabelError"); + serverResponseLabel.setHTML(new SafeHtmlBuilder() + .appendEscaped(result.getGreeting()) + .appendHtmlConstant("

    I am running ") + .appendEscaped(result.getServerInfo()) + .appendHtmlConstant(".

    It looks like you are using:
    ") + .appendEscaped(result.getUserAgent()) + .toSafeHtml()); + dialogBox.center(); + closeButton.setFocus(true); + } + }); } } diff --git a/jetty-maven-plugin/src/it/run-mojo-gwt-it/beer-server/src/main/java/org/olamy/GreetingServiceImpl.java b/jetty-maven-plugin/src/it/run-mojo-gwt-it/beer-server/src/main/java/org/olamy/GreetingServiceImpl.java index d079bf87c71..190f491ce06 100644 --- a/jetty-maven-plugin/src/it/run-mojo-gwt-it/beer-server/src/main/java/org/olamy/GreetingServiceImpl.java +++ b/jetty-maven-plugin/src/it/run-mojo-gwt-it/beer-server/src/main/java/org/olamy/GreetingServiceImpl.java @@ -25,15 +25,18 @@ import com.google.gwt.user.server.rpc.RemoteServiceServlet; */ @SuppressWarnings("serial") public class GreetingServiceImpl extends RemoteServiceServlet implements - GreetingService { + GreetingService +{ - public GreetingResponse greetServer(String input) throws IllegalArgumentException { + public GreetingResponse greetServer(String input) throws IllegalArgumentException + { // Verify that the input is valid. - if (!FieldVerifier.isValidName(input)) { + if (!FieldVerifier.isValidName(input)) + { // If the input is not valid, throw an IllegalArgumentException back to // the client. throw new IllegalArgumentException( - "Name must be at least 4 characters long"); + "Name must be at least 4 characters long"); } GreetingResponse response = new GreetingResponse(); diff --git a/jetty-maven-plugin/src/it/run-mojo-gwt-it/beer-shared/src/main/java/org/olamy/FieldVerifier.java b/jetty-maven-plugin/src/it/run-mojo-gwt-it/beer-shared/src/main/java/org/olamy/FieldVerifier.java index 8a7ac9139a7..108466ff435 100644 --- a/jetty-maven-plugin/src/it/run-mojo-gwt-it/beer-shared/src/main/java/org/olamy/FieldVerifier.java +++ b/jetty-maven-plugin/src/it/run-mojo-gwt-it/beer-shared/src/main/java/org/olamy/FieldVerifier.java @@ -38,21 +38,24 @@ package org.olamy; * JavaScript (such as Widgets) cannot be run on the server. *

    */ -public class FieldVerifier { +public class FieldVerifier +{ /** * Verifies that the specified name is valid for our service. - * + * * In this example, we only require that the name is at least four * characters. In your application, you can use more complex checks to ensure * that usernames, passwords, email addresses, URLs, and other fields have the * proper syntax. - * + * * @param name the name to validate * @return true if valid, false if invalid */ - public static boolean isValidName(String name) { - if (name == null) { + public static boolean isValidName(String name) + { + if (name == null) + { return false; } return name.length() > 3; diff --git a/jetty-maven-plugin/src/it/run-mojo-gwt-it/beer-shared/src/main/java/org/olamy/GreetingResponse.java b/jetty-maven-plugin/src/it/run-mojo-gwt-it/beer-shared/src/main/java/org/olamy/GreetingResponse.java index e179c9e248b..aa92eeb22f8 100644 --- a/jetty-maven-plugin/src/it/run-mojo-gwt-it/beer-shared/src/main/java/org/olamy/GreetingResponse.java +++ b/jetty-maven-plugin/src/it/run-mojo-gwt-it/beer-shared/src/main/java/org/olamy/GreetingResponse.java @@ -21,32 +21,39 @@ package org.olamy; import java.io.Serializable; @SuppressWarnings("serial") -public class GreetingResponse implements Serializable { +public class GreetingResponse implements Serializable +{ private String greeting; private String serverInfo; private String userAgent; - public String getGreeting() { + public String getGreeting() + { return greeting; } - public void setGreeting(String greeting) { + public void setGreeting(String greeting) + { this.greeting = greeting; } - public String getServerInfo() { + public String getServerInfo() + { return serverInfo; } - public void setServerInfo(String serverInfo) { + public void setServerInfo(String serverInfo) + { this.serverInfo = serverInfo; } - public String getUserAgent() { + public String getUserAgent() + { return userAgent; } - public void setUserAgent(String userAgent) { + public void setUserAgent(String userAgent) + { this.userAgent = userAgent; } } diff --git a/jetty-maven-plugin/src/it/run-mojo-gwt-it/beer-shared/src/main/java/org/olamy/GreetingService.java b/jetty-maven-plugin/src/it/run-mojo-gwt-it/beer-shared/src/main/java/org/olamy/GreetingService.java index cca1568d188..d4084b162c8 100644 --- a/jetty-maven-plugin/src/it/run-mojo-gwt-it/beer-shared/src/main/java/org/olamy/GreetingService.java +++ b/jetty-maven-plugin/src/it/run-mojo-gwt-it/beer-shared/src/main/java/org/olamy/GreetingService.java @@ -25,6 +25,7 @@ import com.google.gwt.user.client.rpc.RemoteServiceRelativePath; * The client side stub for the RPC service. */ @RemoteServiceRelativePath("greet") -public interface GreetingService extends RemoteService { +public interface GreetingService extends RemoteService +{ GreetingResponse greetServer(String name) throws IllegalArgumentException; } diff --git a/jetty-maven-plugin/src/it/run-mojo-gwt-it/beer-shared/src/main/java/org/olamy/GreetingServiceAsync.java b/jetty-maven-plugin/src/it/run-mojo-gwt-it/beer-shared/src/main/java/org/olamy/GreetingServiceAsync.java index 7346668b4d2..7cf480ac432 100644 --- a/jetty-maven-plugin/src/it/run-mojo-gwt-it/beer-shared/src/main/java/org/olamy/GreetingServiceAsync.java +++ b/jetty-maven-plugin/src/it/run-mojo-gwt-it/beer-shared/src/main/java/org/olamy/GreetingServiceAsync.java @@ -23,7 +23,8 @@ import com.google.gwt.user.client.rpc.AsyncCallback; /** * The async counterpart of GreetingService. */ -public interface GreetingServiceAsync { +public interface GreetingServiceAsync +{ void greetServer(String input, AsyncCallback callback) - throws IllegalArgumentException; + throws IllegalArgumentException; } diff --git a/jetty-maven-plugin/src/it/run-mojo-gwt-it/pom.xml b/jetty-maven-plugin/src/it/run-mojo-gwt-it/pom.xml index ee8e2e8247a..9d310560684 100644 --- a/jetty-maven-plugin/src/it/run-mojo-gwt-it/pom.xml +++ b/jetty-maven-plugin/src/it/run-mojo-gwt-it/pom.xml @@ -1,6 +1,5 @@ - + 4.0.0 @@ -47,8 +46,7 @@ org.eclipse.jetty jetty-maven-plugin - - + net.ltgt.gwt.maven diff --git a/jetty-maven-plugin/src/main/java/org/eclipse/jetty/maven/plugin/AbstractJettyMojo.java b/jetty-maven-plugin/src/main/java/org/eclipse/jetty/maven/plugin/AbstractJettyMojo.java index 661b9523326..9cd178766d4 100644 --- a/jetty-maven-plugin/src/main/java/org/eclipse/jetty/maven/plugin/AbstractJettyMojo.java +++ b/jetty-maven-plugin/src/main/java/org/eclipse/jetty/maven/plugin/AbstractJettyMojo.java @@ -63,202 +63,173 @@ public abstract class AbstractJettyMojo extends AbstractMojo /** * Whether or not to include dependencies on the plugin's classpath with <scope>provided</scope> * Use WITH CAUTION as you may wind up with duplicate jars/classes. - * + * * @since jetty-7.5.2 */ @Parameter(defaultValue = "false") protected boolean useProvidedScope; - + /** * List of goals that are NOT to be used - * + * * @since jetty-7.5.2 */ @Parameter protected String[] excludedGoals; - + /** * List of other contexts to set up. Consider using instead - * the <jettyXml> element to specify external jetty xml config file. + * the <jettyXml> element to specify external jetty xml config file. * Optional. - * */ @Parameter protected ContextHandler[] contextHandlers; - + /** * List of security realms to set up. Consider using instead - * the <jettyXml> element to specify external jetty xml config file. + * the <jettyXml> element to specify external jetty xml config file. * Optional. - * */ @Parameter protected LoginService[] loginServices; /** * A RequestLog implementation to use for the webapp at runtime. - * Consider using instead the <jettyXml> element to specify external jetty xml config file. + * Consider using instead the <jettyXml> element to specify external jetty xml config file. * Optional. - * */ @Parameter protected RequestLog requestLog; - + /** * An instance of org.eclipse.jetty.webapp.WebAppContext that represents the webapp. * Use any of its setters to configure the webapp. This is the preferred and most * flexible method of configuration, rather than using the (deprecated) individual * parameters like "tmpDirectory", "contextPath" etc. - * */ @Parameter(alias = "webAppConfig") protected JettyWebAppContext webApp; /** - * The interval in seconds to scan the webapp for changes + * The interval in seconds to scan the webapp for changes * and restart the context if necessary. Ignored if reload * is enabled. Disabled by default. - * */ @Parameter(property = "jetty.scanIntervalSeconds", defaultValue = "0", required = true) protected int scanIntervalSeconds; - + /** * reload can be set to either 'automatic' or 'manual' * * if 'manual' then the context can be reloaded by a linefeed in the console * if 'automatic' then traditional reloading on changed files is enabled. - * */ @Parameter(property = "jetty.reload", defaultValue = "automatic") protected String reload; - /** * File containing system properties to be set before execution - * + * * Note that these properties will NOT override System properties - * that have been set on the command line, by the JVM, or directly + * that have been set on the command line, by the JVM, or directly * in the POM via systemProperties. Optional. - * */ @Parameter(property = "jetty.systemPropertiesFile") protected File systemPropertiesFile; - /** - * System properties to set before execution. - * Note that these properties will NOT override System properties - * that have been set on the command line or by the JVM. They WILL + * System properties to set before execution. + * Note that these properties will NOT override System properties + * that have been set on the command line or by the JVM. They WILL * override System properties that have been set via systemPropertiesFile. * Optional. */ @Parameter protected SystemProperties systemProperties; - - + /** - * Comma separated list of a jetty xml configuration files whose contents + * Comma separated list of a jetty xml configuration files whose contents * will be applied before any plugin configuration. Optional. - * */ - @Parameter(alias="jettyConfig") + @Parameter(alias = "jettyConfig") protected String jettyXml; - - + /** - * Port to listen to stop jetty on executing -DSTOP.PORT=<stopPort> + * Port to listen to stop jetty on executing -DSTOP.PORT=<stopPort> * -DSTOP.KEY=<stopKey> -jar start.jar --stop - * */ @Parameter protected int stopPort; - - + /** - * Key to provide when stopping jetty on executing java -DSTOP.KEY=<stopKey> + * Key to provide when stopping jetty on executing java -DSTOP.KEY=<stopKey> * -DSTOP.PORT=<stopPort> -jar start.jar --stop - * */ @Parameter protected String stopKey; /** * Use the dump() facility of jetty to print out the server configuration to logging - * */ - @Parameter( property="dumponStart", defaultValue="false") + @Parameter(property = "dumponStart", defaultValue = "false") protected boolean dumpOnStart; - - - /** + + /** * Skip this mojo execution. */ - @Parameter(property="jetty.skip", defaultValue="false") + @Parameter(property = "jetty.skip", defaultValue = "false") protected boolean skip; - /** * Location of a context xml configuration file whose contents * will be applied to the webapp AFTER anything in <webApp>.Optional. - * */ - @Parameter(alias="webAppXml") + @Parameter(alias = "webAppXml") protected String contextXml; - /** * The maven project. - * */ - @Parameter(defaultValue="${project}", readonly = true) + @Parameter(defaultValue = "${project}", readonly = true) protected MavenProject project; - /** * The artifacts for the project. - * */ - @Parameter(defaultValue="${project.artifacts}", readonly = true) + @Parameter(defaultValue = "${project.artifacts}", readonly = true) protected Set projectArtifacts; - - - @Parameter(defaultValue="${mojoExecution}", readonly = true) + + @Parameter(defaultValue = "${mojoExecution}", readonly = true) protected MojoExecution execution; /** * The artifacts for the plugin itself. - * */ - @Parameter(defaultValue="${plugin.artifacts}", readonly = true) + @Parameter(defaultValue = "${plugin.artifacts}", readonly = true) protected List pluginArtifacts; /** * A ServerConnector to use. - * */ @Parameter protected MavenServerConnector httpConnector; - - + /** * A wrapper for the Server object */ @Parameter protected Server server; - - + /** * A scanner to check for changes to the webapp */ protected PathWatcher scanner; - /** * A scanner to check ENTER hits on the console */ protected Thread consoleScanner; - + protected ServerSupport serverSupport; /** @@ -266,8 +237,8 @@ public abstract class AbstractJettyMojo extends AbstractMojo * Determines whether or not the server blocks when started. The default * behavior (false) will cause the server to pause other processes * while it continues to handle web requests. This is useful when starting the - * server with the intent to work with it interactively. This is the - * behaviour of the jetty:run, jetty:run-war, jetty:run-war-exploded goals. + * server with the intent to work with it interactively. This is the + * behaviour of the jetty:run, jetty:run-war, jetty:run-war-exploded goals. *

    * If true, the server will not block the execution of subsequent code. This * is the behaviour of the jetty:start and default behaviour of the jetty:deploy goals. @@ -279,21 +250,18 @@ public abstract class AbstractJettyMojo extends AbstractMojo /** * Per default this goal support only war packaging. * If your project use an other type please configure it here. - * */ @Parameter - protected List supportedPackagings = Collections.singletonList( "war"); - - + protected List supportedPackagings = Collections.singletonList("war"); + public abstract void restartWebApp(boolean reconfigureScanner) throws Exception; - public boolean checkPomConfiguration() throws MojoExecutionException { return true; } - public abstract void configureScanner () throws MojoExecutionException; + public abstract void configureScanner() throws MojoExecutionException; protected String getSkipMessage(String reason) { @@ -307,7 +275,7 @@ public abstract class AbstractJettyMojo extends AbstractMojo public boolean checkPackagingConfiguration() { - if (!supportedPackagings.contains( project.getPackaging() )) + if (!supportedPackagings.contains(project.getPackaging())) { getLog().info(getSkipMessage("packaging type [" + project.getPackaging() + "] is unsupported")); return false; @@ -315,8 +283,7 @@ public abstract class AbstractJettyMojo extends AbstractMojo return true; } - - /** + /** * @see org.apache.maven.plugin.Mojo#execute() */ @Override @@ -334,8 +301,8 @@ public abstract class AbstractJettyMojo extends AbstractMojo if (isExcluded(execution.getMojoDescriptor().getGoal())) { - getLog().info("The goal \""+execution.getMojoDescriptor().getFullGoalName()+ - "\" has been made unavailable for this web application by an configuration."); + getLog().info("The goal \"" + execution.getMojoDescriptor().getFullGoalName() + + "\" has been made unavailable for this web application by an configuration."); return; } @@ -344,15 +311,14 @@ public abstract class AbstractJettyMojo extends AbstractMojo startJetty(); } } - + public boolean isConfigurationSupported() throws MojoExecutionException { return (checkPackagingConfiguration() && checkPomConfiguration()); } - - + public void configurePluginClasspath() throws MojoExecutionException - { + { //if we are configured to include the provided dependencies on the plugin's classpath //(which mimics being on jetty's classpath vs being on the webapp's classpath), we first //try and filter out ones that will clash with jars that are plugin dependencies, then @@ -363,21 +329,24 @@ public abstract class AbstractJettyMojo extends AbstractMojo { List provided = new ArrayList<>(); - for ( Artifact artifact : projectArtifacts) - { + for (Artifact artifact : projectArtifacts) + { if (Artifact.SCOPE_PROVIDED.equals(artifact.getScope()) && !isPluginArtifact(artifact)) { provided.add(artifact.getFile().toURI().toURL()); - if (getLog().isDebugEnabled()) { getLog().debug("Adding provided artifact: "+artifact);} + if (getLog().isDebugEnabled()) + { + getLog().debug("Adding provided artifact: " + artifact); + } } } if (!provided.isEmpty()) { URL[] urls = provided.stream().toArray(URL[]::new); - URLClassLoader loader = new URLClassLoader(urls, getClass().getClassLoader()); + URLClassLoader loader = new URLClassLoader(urls, getClass().getClassLoader()); Thread.currentThread().setContextClassLoader(loader); - getLog().info("Plugin classpath augmented with provided dependencies: "+Arrays.toString(urls)); + getLog().info("Plugin classpath augmented with provided dependencies: " + Arrays.toString(urls)); } } catch (MalformedURLException e) @@ -386,62 +355,65 @@ public abstract class AbstractJettyMojo extends AbstractMojo } } } - + public boolean isPluginArtifact(Artifact artifact) { if (pluginArtifacts == null || pluginArtifacts.isEmpty()) return false; - - for (Artifact pluginArtifact : pluginArtifacts ) + + for (Artifact pluginArtifact : pluginArtifacts) { - if (getLog().isDebugEnabled()) { getLog().debug("Checking "+pluginArtifact);} - if (pluginArtifact.getGroupId().equals(artifact.getGroupId()) // - && pluginArtifact.getArtifactId().equals(artifact.getArtifactId())) + if (getLog().isDebugEnabled()) + { + getLog().debug("Checking " + pluginArtifact); + } + if (pluginArtifact.getGroupId().equals(artifact.getGroupId()) && + pluginArtifact.getArtifactId().equals(artifact.getArtifactId())) return true; } - + return false; } public void finishConfigurationBeforeStart() throws Exception { HandlerCollection contexts = server.getChildHandlerByClass(ContextHandlerCollection.class); - if (contexts==null) + if (contexts == null) contexts = server.getChildHandlerByClass(HandlerCollection.class); - - for (int i=0; (this.contextHandlers != null) && (i < this.contextHandlers.length); i++) + + for (int i = 0; (this.contextHandlers != null) && (i < this.contextHandlers.length); i++) { contexts.addHandler(this.contextHandlers[i]); } } public void applyJettyXml() throws Exception - { + { Server tmp = ServerSupport.applyXmlConfigurations(server, getJettyXmlFiles()); if (server == null) server = tmp; - + if (server == null) server = new Server(); } - public void startJetty () throws MojoExecutionException + public void startJetty() throws MojoExecutionException { try { getLog().debug("Starting Jetty Server ..."); - + //make sure Jetty does not use URLConnection caches with the plugin Resource.setDefaultUseCaches(false); - + configureMonitor(); - + printSystemProperties(); - + //apply any config from a jetty.xml file first which is able to //be overwritten by config in the pom.xml - applyJettyXml (); - + applyJettyXml(); + // if a was specified in the pom, use it if (httpConnector != null) { @@ -451,9 +423,9 @@ public abstract class AbstractJettyMojo extends AbstractMojo { //use any jetty.http.port settings provided String tmp = System.getProperty(MavenServerConnector.PORT_SYSPROPERTY, // - System.getProperty("jetty.port", MavenServerConnector.DEFAULT_PORT_STR)); + System.getProperty("jetty.port", MavenServerConnector.DEFAULT_PORT_STR)); httpConnector.setPort(Integer.parseInt(tmp.trim())); - } + } httpConnector.setServer(server); } @@ -461,7 +433,7 @@ public abstract class AbstractJettyMojo extends AbstractMojo //set up a RequestLog if one is provided and the handle structure ServerSupport.configureHandlers(server, this.requestLog); - + //Set up list of default Configurations to apply to a webapp ServerSupport.configureDefaultConfigurationClasses(server); configureWebApplication(); @@ -477,9 +449,9 @@ public abstract class AbstractJettyMojo extends AbstractMojo // start Jetty this.server.start(); - getLog().info( "Started Jetty Server" ); + getLog().info("Started Jetty Server"); - if ( dumpOnStart ) + if (dumpOnStart) { getLog().info(this.server.dump()); } @@ -488,7 +460,7 @@ public abstract class AbstractJettyMojo extends AbstractMojo if (isScanningEnabled()) { scanner = new PathWatcher(); - configureScanner (); + configureScanner(); startScanner(); } @@ -496,11 +468,10 @@ public abstract class AbstractJettyMojo extends AbstractMojo startConsoleScanner(); // keep the thread going if not in daemon mode - if (!nonBlocking ) + if (!nonBlocking) { server.join(); } - } catch (Exception e) { @@ -508,42 +479,36 @@ public abstract class AbstractJettyMojo extends AbstractMojo } finally { - if (!nonBlocking ) + if (!nonBlocking) { getLog().info("Jetty server exiting."); - } - } + } + } } - - + public void configureMonitor() - { - if(stopPort>0 && stopKey!=null) + { + if (stopPort > 0 && stopKey != null) { ShutdownMonitor monitor = ShutdownMonitor.getInstance(); monitor.setPort(stopPort); monitor.setKey(stopKey); - monitor.setExitVm(!nonBlocking ); + monitor.setExitVm(!nonBlocking); } } - - - - - /** * Subclasses should invoke this to setup basic info * on the webapp - * - * @throws Exception if unable to configure web application + * + * @throws Exception if unable to configure web application */ - public void configureWebApplication () throws Exception + public void configureWebApplication() throws Exception { //As of jetty-7, you must use a element if (webApp == null) webApp = new JettyWebAppContext(); - + //Apply any context xml file to set up the webapp //CAUTION: if you've defined a element then the //context xml file can OVERRIDE those settings @@ -556,44 +521,42 @@ public abstract class AbstractJettyMojo extends AbstractMojo path = workDir.resolve(path); contextXml = path.toFile().getAbsolutePath(); } - + XmlConfiguration xmlConfiguration = new XmlConfiguration(new PathResource(path)); - getLog().info("Applying context xml file "+contextXml); - xmlConfiguration.configure(webApp); + getLog().info("Applying context xml file " + contextXml); + xmlConfiguration.configure(webApp); } - + //If no contextPath was specified, go with default of project artifactid String cp = webApp.getContextPath(); if (cp == null || "".equals(cp)) { - cp = "/"+project.getArtifactId(); + cp = "/" + project.getArtifactId(); webApp.setContextPath(cp); - } + } //If no tmp directory was specified, and we have one, use it if (webApp.getTempDirectory() == null) { File target = new File(project.getBuild().getDirectory()); - File tmp = new File(target,"tmp"); + File tmp = new File(target, "tmp"); if (!tmp.exists()) - tmp.mkdirs(); + tmp.mkdirs(); webApp.setTempDirectory(tmp); } - + getLog().info("Context path = " + webApp.getContextPath()); - getLog().info("Tmp directory = "+ (webApp.getTempDirectory()== null? " determined at runtime": webApp.getTempDirectory())); - getLog().info("Web defaults = "+(webApp.getDefaultsDescriptor()==null?" jetty default":webApp.getDefaultsDescriptor())); - getLog().info("Web overrides = "+(webApp.getOverrideDescriptor()==null?" none":webApp.getOverrideDescriptor())); + getLog().info("Tmp directory = " + (webApp.getTempDirectory() == null ? " determined at runtime" : webApp.getTempDirectory())); + getLog().info("Web defaults = " + (webApp.getDefaultsDescriptor() == null ? " jetty default" : webApp.getDefaultsDescriptor())); + getLog().info("Web overrides = " + (webApp.getOverrideDescriptor() == null ? " none" : webApp.getOverrideDescriptor())); } - - - /** * Run a scanner thread on the given list of files and directories, calling * stop/start on the given list of LifeCycle objects if any of the watched * files change. - * @throws Exception if unable to start scanner + * + * @throws Exception if unable to start scanner */ public void startScanner() throws Exception { @@ -601,53 +564,52 @@ public abstract class AbstractJettyMojo extends AbstractMojo return; scanner.setNotifyExistingOnStart(false); - - + scanner.start(); } - - - public boolean isScanningEnabled () + + public boolean isScanningEnabled() { - if (scanIntervalSeconds <=0 || "manual".equalsIgnoreCase( reload )) + if (scanIntervalSeconds <= 0 || "manual".equalsIgnoreCase(reload)) return false; return true; } - + public void stopScanner() throws Exception { if (!isScanningEnabled()) return; - + if (scanner != null) scanner.stop(); } - - + /** * Run a thread that monitors the console input to detect ENTER hits. + * * @throws Exception if unable to start the console */ protected void startConsoleScanner() throws Exception { - if ( "manual".equalsIgnoreCase( reload ) ) + if ("manual".equalsIgnoreCase(reload)) { getLog().info("Console reloading is ENABLED. Hit ENTER on the console to restart the context."); consoleScanner = new ConsoleScanner(this); consoleScanner.start(); - } + } } - protected void printSystemProperties () + protected void printSystemProperties() { // print out which system properties were set up if (getLog().isDebugEnabled()) { if (systemProperties != null) { - systemProperties.getSystemProperties().stream().forEach( prop -> { - getLog().debug("Property "+prop.getName()+"="+prop.getValue()+" was "+ (prop.isSet() ? "set" : "skipped")); - } ); + systemProperties.getSystemProperties().stream().forEach(prop -> + { + getLog().debug("Property " + prop.getName() + "=" + prop.getValue() + " was " + (prop.isSet() ? "set" : "skipped")); + }); } } } @@ -655,25 +617,26 @@ public abstract class AbstractJettyMojo extends AbstractMojo /** * Try and find a jetty-web.xml file, using some * historical naming conventions if necessary. + * * @param webInfDir the web inf directory * @return the jetty web xml file */ - public File findJettyWebXmlFile (File webInfDir) + public File findJettyWebXmlFile(File webInfDir) { if (webInfDir == null) return null; if (!webInfDir.exists()) return null; - File f = new File (webInfDir, "jetty-web.xml"); + File f = new File(webInfDir, "jetty-web.xml"); if (f.exists()) return f; //try some historical alternatives - f = new File (webInfDir, "web-jetty.xml"); + f = new File(webInfDir, "web-jetty.xml"); if (f.exists()) return f; - + return null; } @@ -685,78 +648,78 @@ public abstract class AbstractJettyMojo extends AbstractMojo { properties.load(propFile); } - if (this.systemProperties == null ) + if (this.systemProperties == null) this.systemProperties = new SystemProperties(); - - for (Enumeration keys = properties.keys(); keys.hasMoreElements(); ) + + for (Enumeration keys = properties.keys(); keys.hasMoreElements(); ) { String key = (String)keys.nextElement(); - if ( ! systemProperties.containsSystemProperty(key) ) + if (!systemProperties.containsSystemProperty(key)) { SystemProperty prop = new SystemProperty(); prop.setKey(key); prop.setValue(properties.getProperty(key)); - + this.systemProperties.setSystemProperty(prop); } - } + } } - + public void setSystemProperties(SystemProperties systemProperties) { if (this.systemProperties == null) this.systemProperties = systemProperties; else { - for (SystemProperty prop: systemProperties.getSystemProperties()) + for (SystemProperty prop : systemProperties.getSystemProperties()) { this.systemProperties.setSystemProperty(prop); - } + } } } - + public List getJettyXmlFiles() { - if ( this.jettyXml == null ) + if (this.jettyXml == null) { return null; } - + List jettyXmlFiles = new ArrayList(); - - if ( this.jettyXml.indexOf(',') == -1 ) + + if (this.jettyXml.indexOf(',') == -1) { - jettyXmlFiles.add( new File( this.jettyXml ) ); + jettyXmlFiles.add(new File(this.jettyXml)); } else { String[] files = StringUtil.csvSplit(this.jettyXml); - - for ( String file : files ) + + for (String file : files) { - jettyXmlFiles.add( new File(file) ); + jettyXmlFiles.add(new File(file)); } } - + return jettyXmlFiles; } - public boolean isExcluded (String goal) + public boolean isExcluded(String goal) { if (excludedGoals == null || goal == null) return false; - + goal = goal.trim(); if ("".equals(goal)) return false; - + boolean excluded = false; - for (int i=0; i 0) { + + private void checkSystemInput() throws IOException + { + while (System.in.available() > 0) + { int inputByte = System.in.read(); - if (inputByte >= 0) + if (inputByte >= 0) { char c = (char)inputByte; - if (c == '\n') { + if (c == '\n') + { restartWebApp(); } } } } - + /** * Skip buffered bytes of system console. */ - private void clearInputBuffer() + private void clearInputBuffer() { try { @@ -102,9 +104,9 @@ public class ConsoleScanner extends Thread catch (IOException e) { mojo.getLog().warn("Error discarding console input buffer", e); - } + } } - + private void restartWebApp() { try @@ -117,8 +119,8 @@ public class ConsoleScanner extends Thread catch (Exception e) { mojo.getLog().error( - "Error reconfiguring/restarting webapp after a new line on the console", - e); + "Error reconfiguring/restarting webapp after a new line on the console", + e); } } } diff --git a/jetty-maven-plugin/src/main/java/org/eclipse/jetty/maven/plugin/JettyDeployWar.java b/jetty-maven-plugin/src/main/java/org/eclipse/jetty/maven/plugin/JettyDeployWar.java index a3800d0571b..5f0ad431d3c 100644 --- a/jetty-maven-plugin/src/main/java/org/eclipse/jetty/maven/plugin/JettyDeployWar.java +++ b/jetty-maven-plugin/src/main/java/org/eclipse/jetty/maven/plugin/JettyDeployWar.java @@ -31,20 +31,19 @@ import org.apache.maven.plugins.annotations.ResolutionScope; * This goal is used to run Jetty with a pre-assembled war. *

    *

    - * It accepts exactly the same options as the run-war goal. + * It accepts exactly the same options as the run-war goal. * However, it doesn't assume that the current artifact is a - * webapp and doesn't try to assemble it into a war before its execution. - * So using it makes sense only when used in conjunction with the + * webapp and doesn't try to assemble it into a war before its execution. + * So using it makes sense only when used in conjunction with the * war configuration parameter pointing to a pre-built WAR. *

    *

    - * This goal is useful e.g. for launching a web app in Jetty as a target for unit-tested + * This goal is useful e.g. for launching a web app in Jetty as a target for unit-tested * HTTP client components. *

    * Deploy a pre-assembled war - * */ -@Mojo( name = "deploy-war", requiresDependencyResolution = ResolutionScope.RUNTIME) +@Mojo(name = "deploy-war", requiresDependencyResolution = ResolutionScope.RUNTIME) @Execute(phase = LifecyclePhase.VALIDATE) public class JettyDeployWar extends JettyRunWarMojo { @@ -52,12 +51,10 @@ public class JettyDeployWar extends JettyRunWarMojo * If true, the plugin should continue and not block. Otherwise the * plugin will block further execution and you will need to use * cntrl-c to stop it. - * */ @Parameter(property = "jetty.daemon", defaultValue = "true") protected boolean daemon = true; - - + @Override public void execute() throws MojoExecutionException, MojoFailureException { @@ -65,14 +62,11 @@ public class JettyDeployWar extends JettyRunWarMojo super.execute(); } - - @Override public void finishConfigurationBeforeStart() throws Exception { super.finishConfigurationBeforeStart(); //only stop the server at shutdown if we are blocking - server.setStopAtShutdown(!nonBlocking ); + server.setStopAtShutdown(!nonBlocking); } - } diff --git a/jetty-maven-plugin/src/main/java/org/eclipse/jetty/maven/plugin/JettyEffectiveWebXml.java b/jetty-maven-plugin/src/main/java/org/eclipse/jetty/maven/plugin/JettyEffectiveWebXml.java index fd284fffb29..9749cb16c04 100644 --- a/jetty-maven-plugin/src/main/java/org/eclipse/jetty/maven/plugin/JettyEffectiveWebXml.java +++ b/jetty-maven-plugin/src/main/java/org/eclipse/jetty/maven/plugin/JettyEffectiveWebXml.java @@ -16,11 +16,9 @@ // ======================================================================== // - package org.eclipse.jetty.maven.plugin; import java.io.File; -import java.io.IOException; import org.apache.maven.plugin.MojoExecutionException; import org.apache.maven.plugin.MojoFailureException; @@ -31,6 +29,7 @@ import org.apache.maven.plugins.annotations.Parameter; import org.apache.maven.plugins.annotations.ResolutionScope; import org.eclipse.jetty.annotations.AnnotationConfiguration; import org.eclipse.jetty.util.IO; +import org.eclipse.jetty.util.component.LifeCycle; import org.eclipse.jetty.util.resource.Resource; import org.eclipse.jetty.util.thread.QueuedThreadPool; @@ -39,12 +38,12 @@ import org.eclipse.jetty.util.thread.QueuedThreadPool; * a comprehensive web.xml that combines all information from annotations, webdefault.xml and all web-fragment.xml * files. By default, the web.xml is generated to the console output only. Use the effectiveWebXml parameter * to provide a file name into which to save the output. - * + * * See http://www.eclipse.org/jetty/documentation for more information on this and other jetty plugins. * * Runs jetty on the unassembled webapp to generate the effective web.xml */ -@Mojo( name = "effective-web-xml", requiresDependencyResolution = ResolutionScope.TEST) +@Mojo(name = "effective-web-xml", requiresDependencyResolution = ResolutionScope.TEST) @Execute(phase = LifecyclePhase.TEST_COMPILE) public class JettyEffectiveWebXml extends JettyRunMojo { @@ -53,16 +52,14 @@ public class JettyEffectiveWebXml extends JettyRunMojo */ @Parameter(defaultValue = "${project.build.directory}", readonly = true, required = true) protected File target; - + /** * The name of the file to generate into - * */ @Parameter protected File effectiveWebXml; protected boolean deleteOnExit = true; - /** * @see org.apache.maven.plugin.Mojo#execute() @@ -72,35 +69,33 @@ public class JettyEffectiveWebXml extends JettyRunMojo { super.execute(); } - - + @Override public void startJetty() throws MojoExecutionException { //Only do enough setup to be able to produce a quickstart-web.xml file QueuedThreadPool tpool = null; - + try { printSystemProperties(); //apply any config from a jetty.xml file first to our "fake" server instance //TODO probably not necessary - applyJettyXml (); - + applyJettyXml(); + ServerSupport.configureHandlers(server, null); ServerSupport.configureDefaultConfigurationClasses(server); - + //ensure config of the webapp based on settings in plugin configureWebApplication(); - + //set the webapp up to do very little other than generate the quickstart-web.xml webApp.setCopyWebDir(false); webApp.setCopyWebInf(false); webApp.setGenerateQuickStart(true); - //if the user didn't nominate a file to generate into, pick the name and //make sure that it is deleted on exit if (webApp.getQuickStartWebDescriptor() == null) @@ -121,9 +116,9 @@ public class JettyEffectiveWebXml extends JettyRunMojo webApp.setQuickStartWebDescriptor(descriptor); } - + ServerSupport.addWebApplication(server, webApp); - + //if our server has a thread pool associated we can do any annotation scanning multithreaded, //otherwise scanning will be single threaded tpool = server.getBean(QueuedThreadPool.class); @@ -131,9 +126,8 @@ public class JettyEffectiveWebXml extends JettyRunMojo tpool.start(); else webApp.setAttribute(AnnotationConfiguration.MULTI_THREADED, Boolean.FALSE.toString()); - - webApp.start(); //just enough to generate the quickstart - + + webApp.start(); //just enough to generate the quickstart } catch (Exception e) { @@ -141,12 +135,24 @@ public class JettyEffectiveWebXml extends JettyRunMojo } finally { - try {webApp.stop();}catch (Exception x) {}; - - try {if (tpool != null) tpool.stop();} catch (Exception x) {}; + try + { + webApp.stop(); + } + catch (Exception ignored) + { + } + + try + { + if (tpool != null) + tpool.stop(); + } + catch (Exception ignored) + { + } } - - + if (deleteOnExit) { try @@ -156,10 +162,8 @@ public class JettyEffectiveWebXml extends JettyRunMojo } catch (Exception e) { - throw new MojoExecutionException("Unable to output effective web.xml", e); + throw new MojoExecutionException("Unable to output effective web.xml", e); } - } - } } diff --git a/jetty-maven-plugin/src/main/java/org/eclipse/jetty/maven/plugin/JettyRunDistro.java b/jetty-maven-plugin/src/main/java/org/eclipse/jetty/maven/plugin/JettyRunDistro.java index 447ec91f935..3c7cb084427 100644 --- a/jetty-maven-plugin/src/main/java/org/eclipse/jetty/maven/plugin/JettyRunDistro.java +++ b/jetty-maven-plugin/src/main/java/org/eclipse/jetty/maven/plugin/JettyRunDistro.java @@ -16,7 +16,6 @@ // ======================================================================== // - package org.eclipse.jetty.maven.plugin; import java.io.File; @@ -66,87 +65,76 @@ import org.eclipse.jetty.util.resource.JarResource; import org.eclipse.jetty.util.resource.Resource; /** - * * This goal is used to deploy the unassembled webapp into a jetty distribution. If the location - * of an existing unpacked distribution is not supplied as the configuration param jettyHome, + * of an existing unpacked distribution is not supplied as the configuration param jettyHome, * this goal will download and unpack the jetty distro matching the version of this plugin before deploying the webapp. - * + * * The webapp will execute in the distro in a forked process. - * + * * The stopKey, stopPort configuration elements can be used to control the stopping of the forked process. By default, this plugin will launch * the forked jetty instance and wait for it to complete (in which case it acts much like the jetty:run goal, and you will need to Cntrl-C to stop). * By setting the configuration element waitForChild to false, the plugin will terminate after having forked the jetty process. In this case * you can use the jetty:stop goal to terminate the process. - * + * * This goal does NOT support the scanIntervalSeconds parameter: the webapp will be deployed only once. - * + * * See http://www.eclipse.org/jetty/documentation for more information on this and other jetty plugins. - * + * * Runs unassembled webapp in a locally installed jetty distro - * */ -@Mojo( name = "run-distro", requiresDependencyResolution = ResolutionScope.TEST) +@Mojo(name = "run-distro", requiresDependencyResolution = ResolutionScope.TEST) @Execute(phase = LifecyclePhase.TEST_COMPILE) public class JettyRunDistro extends JettyRunMojo { - + public static final String JETTY_HOME_GROUPID = "org.eclipse.jetty"; public static final String JETTY_HOME_ARTIFACTID = "jetty-home"; - - + /** * This plugin */ @Parameter(defaultValue = "${plugin}", required = true, readonly = true) protected PluginDescriptor plugin; - + /** * The target directory */ @Parameter(defaultValue = "${project.build.directory}", readonly = true, required = true) protected File target; - - + /** * Optional jetty.home dir - * */ @Parameter private File jettyHome; - - + /** * Optional jetty.base dir - * */ @Parameter private File jettyBase; - + /** * Optional list of other modules to * activate. */ @Parameter private String[] modules; - + /** * Arbitrary jvm args to pass to the forked process - * */ @Parameter(property = "jetty.jvmArgs") private String jvmArgs; - + /** * Extra environment variables to be passed to the forked process - * */ @Parameter - private Map env = new HashMap<>(); - - + private Map env = new HashMap<>(); + /** * Optional list of jetty properties to put on the command line - * */ @Parameter private String[] jettyProperties; @@ -156,53 +144,48 @@ public class JettyRunDistro extends JettyRunMojo /** * The project's remote repositories to use for the resolution. - * */ - @Parameter(defaultValue="${project.remoteArtifactRepositories}", required = true, readonly = true) + @Parameter(defaultValue = "${project.remoteArtifactRepositories}", required = true, readonly = true) private List remoteRepositories; @Component private ArtifactResolver artifactResolver; - - @Parameter( defaultValue="${plugin.version}", readonly = true) + @Parameter(defaultValue = "${plugin.version}", readonly = true) private String pluginVersion; - - + /** * Whether to wait for the child to finish or not. - * */ - @Parameter(defaultValue="true") + @Parameter(defaultValue = "true") private boolean waitForChild; - + /** * Max number of times to try checking if the * child has started successfully. - * */ - @Parameter(defaultValue="10") + @Parameter(defaultValue = "10") private int maxChildChecks; - + /** * Millisecs to wait between each * check to see if the child started successfully. */ - @Parameter(defaultValue="100") + @Parameter(defaultValue = "100") private long maxChildCheckInterval; - + private File targetBase; - + private List libExtJars; - + private Random random; - + private Path tokenFile; @Parameter(property = "jetty.javaPath") private String javaPath; - /** + /** * @see org.eclipse.jetty.maven.plugin.JettyRunMojo#execute() */ @Override @@ -213,7 +196,7 @@ public class JettyRunDistro extends JettyRunMojo if (pdeps != null && !pdeps.isEmpty()) { boolean warned = false; - for (Dependency d:pdeps) + for (Dependency d : pdeps) { if (d.getGroupId().equalsIgnoreCase("org.eclipse.jetty")) { @@ -230,14 +213,12 @@ public class JettyRunDistro extends JettyRunMojo libExtJars.add(d); } } - } super.execute(); } - - /** + /** * @see org.eclipse.jetty.maven.plugin.AbstractJettyMojo#startJetty() */ @Override @@ -248,7 +229,7 @@ public class JettyRunDistro extends JettyRunMojo try { printSystemProperties(); - + //download and install jetty-home if necessary configureJettyHome(); @@ -260,9 +241,7 @@ public class JettyRunDistro extends JettyRunMojo //create the command to run the new process ProcessBuilder command = configureCommand(); - - - + if (waitForChild) { command.inheritIO(); @@ -272,9 +251,9 @@ public class JettyRunDistro extends JettyRunMojo command.redirectOutput(new File(target, "jetty.out")); command.redirectErrorStream(true); } - + Process process = command.start(); - + if (waitForChild) //keep executing until the child dies process.waitFor(); @@ -287,23 +266,20 @@ public class JettyRunDistro extends JettyRunMojo Thread.currentThread().sleep(maxChildCheckInterval); --attempts; } - if (attempts <=0 ) + if (attempts <= 0) getLog().info("Couldn't verify success of child startup"); } - } catch (Exception e) { throw new MojoExecutionException("Failed to start Jetty", e); } - } - /** * If jetty home does not exist, download it and * unpack to build dir. - * + * * @throws Exception if jetty distribution cannot be found neither downloaded */ public void configureJettyHome() throws Exception @@ -311,25 +287,24 @@ public class JettyRunDistro extends JettyRunMojo if (jettyHome == null) { //no jetty home, download from repo and unpack it. Get the same version as the plugin - Artifact jettyHomeArtifact = resolveArtifact(JETTY_HOME_GROUPID, JETTY_HOME_ARTIFACTID, pluginVersion, "zip"); - JarResource res = (JarResource) JarResource.newJarResource(Resource.newResource(jettyHomeArtifact.getFile())); + Artifact jettyHomeArtifact = resolveArtifact(JETTY_HOME_GROUPID, JETTY_HOME_ARTIFACTID, pluginVersion, "zip"); + JarResource res = (JarResource)JarResource.newJarResource(Resource.newResource(jettyHomeArtifact.getFile())); res.copyTo(target); //zip will unpack to target/jetty-home- - jettyHome = new File (target, JETTY_HOME_ARTIFACTID+"-"+pluginVersion); + jettyHome = new File(target, JETTY_HOME_ARTIFACTID + "-" + pluginVersion); } else { - if (!jettyHome.exists()) - throw new IllegalStateException(jettyHome.getAbsolutePath()+" does not exist"); + if (!jettyHome.exists()) + throw new IllegalStateException(jettyHome.getAbsolutePath() + " does not exist"); } - - getLog().info("jetty.home = "+jettyHome.getAbsolutePath()); - } + getLog().info("jetty.home = " + jettyHome.getAbsolutePath()); + } /** * Resolve an Artifact from remote repo if necessary. - * + * * @param groupId the groupid of the artifact * @param artifactId the artifactId of the artifact * @param version the version of the artifact @@ -337,8 +312,8 @@ public class JettyRunDistro extends JettyRunMojo * @return the artifact from the local or remote repo * @throws ArtifactResolverException in case of an error while resolving the artifact */ - public Artifact resolveArtifact (String groupId, String artifactId, String version, String extension) - throws ArtifactResolverException + public Artifact resolveArtifact(String groupId, String artifactId, String version, String extension) + throws ArtifactResolverException { DefaultArtifactCoordinate coordinate = new DefaultArtifactCoordinate(); coordinate.setGroupId(groupId); @@ -351,66 +326,65 @@ public class JettyRunDistro extends JettyRunMojo buildingRequest.setRemoteRepositories(remoteRepositories); - return artifactResolver.resolveArtifact( buildingRequest, coordinate ).getArtifact(); + return artifactResolver.resolveArtifact(buildingRequest, coordinate).getArtifact(); } /** * Create or configure a jetty base. - * + * * @throws Exception if any error occurred while copying files */ public void configureJettyBase() throws Exception { if (jettyBase != null && !jettyBase.exists()) - throw new IllegalStateException(jettyBase.getAbsolutePath() +" does not exist"); - + throw new IllegalStateException(jettyBase.getAbsolutePath() + " does not exist"); + targetBase = new File(target, "jetty-base"); Path targetBasePath = targetBase.toPath(); Files.deleteIfExists(targetBase.toPath()); targetBase.mkdirs(); - + if (jettyBase != null) { Path jettyBasePath = jettyBase.toPath(); - + //copy the existing jetty base - Files.walkFileTree(jettyBasePath,EnumSet.of(FileVisitOption.FOLLOW_LINKS), - Integer.MAX_VALUE, - new SimpleFileVisitor<>() - { - /** - * @see java.nio.file.SimpleFileVisitor#preVisitDirectory(java.lang.Object, java.nio.file.attribute.BasicFileAttributes) - */ - @Override - public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException + Files.walkFileTree(jettyBasePath, EnumSet.of(FileVisitOption.FOLLOW_LINKS), + Integer.MAX_VALUE, + new SimpleFileVisitor<>() { - Path targetDir = targetBasePath.resolve(jettyBasePath.relativize(dir)); - try + /** + * @see java.nio.file.SimpleFileVisitor#preVisitDirectory(java.lang.Object, java.nio.file.attribute.BasicFileAttributes) + */ + @Override + public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException { - Files.copy(dir, targetDir); - } - catch (FileAlreadyExistsException e) - { - if (!Files.isDirectory(targetDir)) //ignore attempt to recreate dir + Path targetDir = targetBasePath.resolve(jettyBasePath.relativize(dir)); + try + { + Files.copy(dir, targetDir); + } + catch (FileAlreadyExistsException e) + { + if (!Files.isDirectory(targetDir)) //ignore attempt to recreate dir throw e; + } + return FileVisitResult.CONTINUE; } - return FileVisitResult.CONTINUE; - } - /** - * @see java.nio.file.SimpleFileVisitor#visitFile(java.lang.Object, java.nio.file.attribute.BasicFileAttributes) - */ - @Override - public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException - { - if (contextXml != null && Files.isSameFile(Paths.get(contextXml), file)) - return FileVisitResult.CONTINUE; //skip copying the context xml file - Files.copy(file, targetBasePath.resolve(jettyBasePath.relativize(file))); - return FileVisitResult.CONTINUE; - } - - }); + /** + * @see java.nio.file.SimpleFileVisitor#visitFile(java.lang.Object, java.nio.file.attribute.BasicFileAttributes) + */ + @Override + public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException + { + if (contextXml != null && Files.isSameFile(Paths.get(contextXml), file)) + return FileVisitResult.CONTINUE; //skip copying the context xml file + Files.copy(file, targetBasePath.resolve(jettyBasePath.relativize(file))); + return FileVisitResult.CONTINUE; + } + }); } //make the jetty base structure @@ -425,142 +399,141 @@ public class JettyRunDistro extends JettyRunMojo if (thisJar == null) throw new IllegalStateException("Can't find jar for jetty-maven-plugin"); - try(InputStream jarStream = thisJar.toURL().openStream(); - FileOutputStream fileStream = new FileOutputStream(mavenLibPath.resolve("plugin.jar").toFile())) + try (InputStream jarStream = thisJar.toURL().openStream(); + FileOutputStream fileStream = new FileOutputStream(mavenLibPath.resolve("plugin.jar").toFile())) { - IO.copy(jarStream,fileStream); + IO.copy(jarStream, fileStream); } //copy in the maven.xml webapp file - try (InputStream mavenXmlStream = getClass().getClassLoader().getResourceAsStream("maven.xml"); + try (InputStream mavenXmlStream = getClass().getClassLoader().getResourceAsStream("maven.xml"); FileOutputStream fileStream = new FileOutputStream(webappPath.resolve("maven.xml").toFile())) { IO.copy(mavenXmlStream, fileStream); } - + //copy in the maven.mod file try (InputStream mavenModStream = getClass().getClassLoader().getResourceAsStream("maven.mod"); - FileOutputStream fileStream = new FileOutputStream(modulesPath.resolve("maven.mod").toFile())) + FileOutputStream fileStream = new FileOutputStream(modulesPath.resolve("maven.mod").toFile())) { IO.copy(mavenModStream, fileStream); } - + //copy in the jetty-maven.xml file try (InputStream jettyMavenStream = getClass().getClassLoader().getResourceAsStream("jetty-maven.xml"); - FileOutputStream fileStream = new FileOutputStream(etcPath.resolve("jetty-maven.xml").toFile())) + FileOutputStream fileStream = new FileOutputStream(etcPath.resolve("jetty-maven.xml").toFile())) { IO.copy(jettyMavenStream, fileStream); } - + //if there were plugin dependencies, copy them into lib/ext if (libExtJars != null && !libExtJars.isEmpty()) { Path libExtPath = Files.createDirectories(libPath.resolve("ext")); - for (Dependency d:libExtJars) + for (Dependency d : libExtJars) { Artifact a = resolveArtifact(d.getGroupId(), d.getArtifactId(), d.getVersion(), d.getType()); try (InputStream jarStream = new FileInputStream(a.getFile()); - FileOutputStream fileStream = new FileOutputStream(libExtPath.resolve(d.getGroupId()+"."+d.getArtifactId()+"-"+d.getVersion()+"."+d.getType()).toFile())) + FileOutputStream fileStream = new FileOutputStream(libExtPath.resolve(d.getGroupId() + "." + d.getArtifactId() + "-" + d.getVersion() + "." + d.getType()).toFile())) { IO.copy(jarStream, fileStream); } } } - + //create properties file that describes the webapp createPropertiesFile(etcPath.resolve("maven.props").toFile()); } - - + /** * Convert webapp config to properties - * + * * @param file the file to place the properties into * @throws Exception if any I/O exception during generating the properties file */ - public void createPropertiesFile (File file) - throws Exception + public void createPropertiesFile(File file) + throws Exception { WebAppPropertyConverter.toProperties(webApp, file, contextXml); } - - + /** * Make the command to spawn a process to * run jetty from a distro. - * + * * @return the command configured */ public ProcessBuilder configureCommand() { List cmd = new ArrayList<>(); - if(StringUtil.isNotBlank( javaPath )) + if (StringUtil.isNotBlank(javaPath)) { - cmd.add( javaPath ); + cmd.add(javaPath); } else { - cmd.add( getJavaBin() ); + cmd.add(getJavaBin()); } cmd.add("-jar"); cmd.add(new File(jettyHome, "start.jar").getAbsolutePath()); - - cmd.add("-DSTOP.PORT="+stopPort); + + cmd.add("-DSTOP.PORT=" + stopPort); if (stopKey != null) - cmd.add("-DSTOP.KEY="+stopKey); - + cmd.add("-DSTOP.KEY=" + stopKey); + //add any args to the jvm if (jvmArgs != null) { String[] args = jvmArgs.split(" "); - for (String a:args) + for (String a : args) { if (!StringUtil.isBlank(a)) cmd.add(a.trim()); } } - + //set up enabled jetty modules StringBuilder tmp = new StringBuilder(); tmp.append("--module="); tmp.append("server,http,webapp,deploy"); if (modules != null) { - for (String m:modules) + for (String m : modules) { if (tmp.indexOf(m) < 0) - tmp.append(","+m); + tmp.append("," + m); } } - + if (libExtJars != null && !libExtJars.isEmpty() && tmp.indexOf("ext") < 0) tmp.append(",ext"); tmp.append(",maven"); cmd.add(tmp.toString()); - + //put any jetty properties onto the command line if (jettyProperties != null) { - for (String p:jettyProperties) + for (String p : jettyProperties) + { cmd.add(p); + } } - + //existence of this file signals process started - tokenFile = target.toPath().resolve(createToken()+".txt"); - cmd.add("jetty.token.file="+tokenFile.toAbsolutePath().toString()); + tokenFile = target.toPath().resolve(createToken() + ".txt"); + cmd.add("jetty.token.file=" + tokenFile.toAbsolutePath().toString()); ProcessBuilder builder = new ProcessBuilder(cmd); builder.directory(targetBase); - + //set up extra environment vars if there are any if (!env.isEmpty()) builder.environment().putAll(env); return builder; } - - /** + /** * @see org.eclipse.jetty.maven.plugin.AbstractJettyMojo#startScanner() */ @Override @@ -569,9 +542,7 @@ public class JettyRunDistro extends JettyRunMojo //don't scan } - - - /** + /** * @see org.eclipse.jetty.maven.plugin.AbstractJettyMojo#stopScanner() */ @Override @@ -580,9 +551,7 @@ public class JettyRunDistro extends JettyRunMojo //don't scan } - - - /** + /** * @see org.eclipse.jetty.maven.plugin.AbstractJettyMojo#restartWebApp(boolean) */ @Override @@ -591,7 +560,7 @@ public class JettyRunDistro extends JettyRunMojo //do nothing } - /** + /** * @see org.eclipse.jetty.maven.plugin.AbstractJettyMojo#configureScanner() */ @Override @@ -599,11 +568,9 @@ public class JettyRunDistro extends JettyRunMojo { //do nothing } - - private String createToken () - { - return Long.toString(random.nextLong()^System.currentTimeMillis(), 36).toUpperCase(Locale.ENGLISH); - } - + private String createToken() + { + return Long.toString(random.nextLong() ^ System.currentTimeMillis(), 36).toUpperCase(Locale.ENGLISH); + } } diff --git a/jetty-maven-plugin/src/main/java/org/eclipse/jetty/maven/plugin/JettyRunForkedMojo.java b/jetty-maven-plugin/src/main/java/org/eclipse/jetty/maven/plugin/JettyRunForkedMojo.java index b69bef67ba8..5e122634663 100644 --- a/jetty-maven-plugin/src/main/java/org/eclipse/jetty/maven/plugin/JettyRunForkedMojo.java +++ b/jetty-maven-plugin/src/main/java/org/eclipse/jetty/maven/plugin/JettyRunForkedMojo.java @@ -48,13 +48,12 @@ import org.eclipse.jetty.util.StringUtil; import org.eclipse.jetty.util.resource.Resource; import org.eclipse.jetty.util.thread.QueuedThreadPool; - /** * This goal is used to deploy your unassembled webapp into a forked JVM. *

    * You need to define a jetty.xml file to configure connectors etc. You can use the normal setters of o.e.j.webapp.WebAppContext on the webApp * configuration element for this plugin. You may also need context xml file for any particularly complex webapp setup. - * + * *

    * Unlike the other jetty goals, this does NOT support the scanIntervalSeconds parameter: the webapp will be deployed only once. *

    @@ -64,86 +63,75 @@ import org.eclipse.jetty.util.thread.QueuedThreadPool; * you can use the jetty:stop goal to terminate the process. *

    * See http://www.eclipse.org/jetty/documentation for more information on this and other jetty plugins. - * - * Runs Jetty in forked JVM on an unassembled webapp * + * Runs Jetty in forked JVM on an unassembled webapp */ -@Mojo( name = "run-forked", requiresDependencyResolution = ResolutionScope.TEST) +@Mojo(name = "run-forked", requiresDependencyResolution = ResolutionScope.TEST) @Execute(phase = LifecyclePhase.TEST_COMPILE) public class JettyRunForkedMojo extends JettyRunMojo -{ +{ /** * The target directory */ - @Parameter(defaultValue="${project.build.directory}", readonly = true, required = true) + @Parameter(defaultValue = "${project.build.directory}", readonly = true, required = true) protected File target; - + /** * The file into which to generate the quickstart web xml for the forked process to use - * */ - @Parameter(defaultValue="${project.build.directory}/fork-web.xml") + @Parameter(defaultValue = "${project.build.directory}/fork-web.xml") protected File forkWebXml; - - + /** * Arbitrary jvm args to pass to the forked process - * */ - @Parameter(property="jetty.jvmArgs") + @Parameter(property = "jetty.jvmArgs") private String jvmArgs; - - + /** * Optional list of jetty properties to put on the command line - * */ @Parameter private String[] jettyProperties; - - @Parameter(defaultValue="${plugin.artifacts}",readonly = true) + + @Parameter(defaultValue = "${plugin.artifacts}", readonly = true) private List pluginArtifacts; - @Parameter(defaultValue="${plugin}", readonly = true) + @Parameter(defaultValue = "${plugin}", readonly = true) private PluginDescriptor plugin; - @Parameter(defaultValue="true") + @Parameter(defaultValue = "true") private boolean waitForChild; - /** * Max number of times to try checking if the * child has started successfully. - * */ - @Parameter(alias="maxStartupLines", defaultValue="50") + @Parameter(alias = "maxStartupLines", defaultValue = "50") private int maxChildChecks; - + /** * Millisecs to wait between each * check to see if the child started successfully. */ - @Parameter(defaultValue="100") + @Parameter(defaultValue = "100") private long maxChildCheckInterval; - + /** * Extra environment variables to be passed to the forked process - * */ @Parameter - private Map env = new HashMap<>(); + private Map env = new HashMap<>(); /** * The forked jetty instance */ private Process forkedProcess; - - + /** * Random number generator */ - private Random random; - + private Random random; /** * Whether or not the plugin has explicit slf4j dependencies. @@ -158,8 +146,6 @@ public class JettyRunForkedMojo extends JettyRunMojo /** * ShutdownThread - * - * */ public class ShutdownThread extends Thread { @@ -167,9 +153,9 @@ public class JettyRunForkedMojo extends JettyRunMojo { super("RunForkedShutdown"); } - + @Override - public void run () + public void run() { if (forkedProcess != null && waitForChild) { @@ -177,11 +163,7 @@ public class JettyRunForkedMojo extends JettyRunMojo } } } - - - - - + /** * @see org.apache.maven.plugin.Mojo#execute() */ @@ -190,9 +172,9 @@ public class JettyRunForkedMojo extends JettyRunMojo { Runtime.getRuntime().addShutdownHook(new ShutdownThread()); random = new Random(); - + List deps = plugin.getPlugin().getDependencies(); - for (Dependency d:deps) + for (Dependency d : deps) { if (d.getGroupId().contains("slf4j")) { @@ -200,12 +182,9 @@ public class JettyRunForkedMojo extends JettyRunMojo break; } } - + super.execute(); } - - - @Override public void startJetty() throws MojoExecutionException @@ -223,9 +202,9 @@ public class JettyRunForkedMojo extends JettyRunMojo //ensure handler structure enabled ServerSupport.configureHandlers(server, null); - + ServerSupport.configureDefaultConfigurationClasses(server); - + //ensure config of the webapp based on settings in plugin configureWebApplication(); @@ -237,7 +216,7 @@ public class JettyRunForkedMojo extends JettyRunMojo if (webApp.getQuickStartWebDescriptor() == null) { if (forkWebXml == null) - forkWebXml = new File (target, "fork-web.xml"); + forkWebXml = new File(target, "fork-web.xml"); if (!forkWebXml.getParentFile().exists()) forkWebXml.getParentFile().mkdirs(); @@ -246,10 +225,10 @@ public class JettyRunForkedMojo extends JettyRunMojo webApp.setQuickStartWebDescriptor(Resource.newResource(forkWebXml)); } - + //add webapp to our fake server instance ServerSupport.addWebApplication(server, webApp); - + //if our server has a thread pool associated we can do annotation scanning multithreaded, //otherwise scanning will be single threaded QueuedThreadPool tpool = server.getBean(QueuedThreadPool.class); @@ -260,39 +239,37 @@ public class JettyRunForkedMojo extends JettyRunMojo //leave everything unpacked for the forked process to use webApp.setPersistTempDirectory(true); - + webApp.start(); //just enough to generate the quickstart - + //save config of the webapp BEFORE we stop File props = prepareConfiguration(); - + webApp.stop(); - - - + if (tpool != null) tpool.stop(); - + List cmd = new ArrayList<>(); - if( StringUtil.isNotBlank( javaPath )) + if (StringUtil.isNotBlank(javaPath)) { - cmd.add( javaPath ); + cmd.add(javaPath); } else { - cmd.add( getJavaBin() ); + cmd.add(getJavaBin()); } - + if (jvmArgs != null) { String[] args = jvmArgs.split(" "); - for (int i=0;args != null && i 0) { @@ -300,7 +277,7 @@ public class JettyRunForkedMojo extends JettyRunMojo cmd.add(classPath); } cmd.add(Starter.class.getCanonicalName()); - + if (stopPort > 0 && stopKey != null) { cmd.add("--stop-port"); @@ -313,36 +290,36 @@ public class JettyRunForkedMojo extends JettyRunMojo cmd.add("--jetty-xml"); cmd.add(jettyXml); } - + cmd.add("--props"); cmd.add(props.getAbsolutePath()); - - Path tokenFile = target.toPath().resolve(createToken()+".txt"); + + Path tokenFile = target.toPath().resolve(createToken() + ".txt"); cmd.add("--token"); cmd.add(tokenFile.toAbsolutePath().toString()); - + if (jettyProperties != null) { - for (String jettyProp:jettyProperties) + for (String jettyProp : jettyProperties) { cmd.add(jettyProp); } } - + ProcessBuilder builder = new ProcessBuilder(cmd); builder.directory(project.getBasedir()); - + if (PluginLog.getLog().isDebugEnabled()) - PluginLog.getLog().debug("Forked cli:"+Arrays.toString(cmd.toArray())); - + PluginLog.getLog().debug("Forked cli:" + Arrays.toString(cmd.toArray())); + PluginLog.getLog().info("Forked process starting"); - + //set up extra environment vars if there are any if (!env.isEmpty()) { builder.environment().putAll(env); } - + if (waitForChild) { builder.inheritIO(); @@ -352,16 +329,16 @@ public class JettyRunForkedMojo extends JettyRunMojo builder.redirectOutput(new File(target, "jetty.out")); builder.redirectErrorStream(true); } - + forkedProcess = builder.start(); - + if (waitForChild) { - int exitcode = forkedProcess.waitFor(); - PluginLog.getLog().info("Forked execution exit: "+exitcode); + int exitcode = forkedProcess.waitFor(); + PluginLog.getLog().info("Forked execution exit: " + exitcode); } else - { + { //just wait until the child has started successfully int attempts = maxChildChecks; while (!Files.exists(tokenFile) && attempts > 0) @@ -369,7 +346,7 @@ public class JettyRunForkedMojo extends JettyRunMojo Thread.currentThread().sleep(maxChildCheckInterval); --attempts; } - if (attempts <=0 ) + if (attempts <= 0) getLog().info("Couldn't verify success of child startup"); } } @@ -377,49 +354,51 @@ public class JettyRunForkedMojo extends JettyRunMojo { if (forkedProcess != null && waitForChild) forkedProcess.destroy(); - + throw new MojoExecutionException("Failed to start Jetty within time limit"); } catch (Exception ex) { if (forkedProcess != null && waitForChild) forkedProcess.destroy(); - + throw new MojoExecutionException("Failed to create Jetty process", ex); } } public List getProvidedJars() throws MojoExecutionException - { + { //if we are configured to include the provided dependencies on the plugin's classpath //(which mimics being on jetty's classpath vs being on the webapp's classpath), we first //try and filter out ones that will clash with jars that are plugin dependencies, then //create a new classloader that we setup in the parent chain. if (useProvidedScope) { - + List provided = new ArrayList<>(); - for ( Artifact artifact : project.getArtifacts()) + for (Artifact artifact : project.getArtifacts()) { if (Artifact.SCOPE_PROVIDED.equals(artifact.getScope()) && !isPluginArtifact(artifact)) { provided.add(artifact.getFile().getAbsolutePath()); - if (getLog().isDebugEnabled()) { getLog().debug("Adding provided artifact: "+artifact);} + if (getLog().isDebugEnabled()) + { + getLog().debug("Adding provided artifact: " + artifact); + } } } return provided; - } else return null; } - + public File prepareConfiguration() throws MojoExecutionException { try - { + { //work out the configuration based on what is configured in the pom - File propsFile = new File (target, "fork.props"); + File propsFile = new File(target, "fork.props"); WebAppPropertyConverter.toProperties(webApp, propsFile, contextXml); return propsFile; } @@ -428,31 +407,31 @@ public class JettyRunForkedMojo extends JettyRunMojo throw new MojoExecutionException("Prepare webapp configuration", e); } } - - @Override public boolean isPluginArtifact(Artifact artifact) { if (pluginArtifacts == null || pluginArtifacts.isEmpty()) return false; - + for (Artifact pluginArtifact : pluginArtifacts) { - if (getLog().isDebugEnabled()) { getLog().debug("Checking "+pluginArtifact);} + if (getLog().isDebugEnabled()) + { + getLog().debug("Checking " + pluginArtifact); + } if (pluginArtifact.getGroupId().equals(artifact.getGroupId()) && pluginArtifact.getArtifactId().equals(artifact.getArtifactId())) return true; } - + return false; } - + private Set getExtraJars() - throws Exception + throws Exception { Set extraJars = new HashSet<>(); - - + List l = pluginArtifacts; Artifact pluginArtifact = null; @@ -461,7 +440,7 @@ public class JettyRunForkedMojo extends JettyRunMojo Iterator itor = l.iterator(); while (itor.hasNext() && pluginArtifact == null) - { + { Artifact a = (Artifact)itor.next(); if (a.getArtifactId().equals(plugin.getArtifactId())) //get the jetty-maven-plugin jar { @@ -482,43 +461,39 @@ public class JettyRunForkedMojo extends JettyRunMojo { //ignore slf4j from inside maven if (artifact.getGroupId().contains("slf4j") && !hasSlf4jDeps) - continue; + continue; if (classPath.length() > 0) { classPath.append(File.pathSeparator); } classPath.append(artifact.getFile().getAbsolutePath()); - } } - //Any jars that we need from the plugin environment (like the ones containing Starter class) Set extraJars = getExtraJars(); - for (Artifact a:extraJars) - { + for (Artifact a : extraJars) + { classPath.append(File.pathSeparator); classPath.append(a.getFile().getAbsolutePath()); } - - + //Any jars that we need from the project's dependencies because we're useProvided List providedJars = getProvidedJars(); if (providedJars != null && !providedJars.isEmpty()) { - for (String jar:providedJars) + for (String jar : providedJars) { classPath.append(File.pathSeparator); classPath.append(jar); - if (getLog().isDebugEnabled()) getLog().debug("Adding provided jar: "+jar); + if (getLog().isDebugEnabled()) + getLog().debug("Adding provided jar: " + jar); } } return classPath.toString(); } - - public static String pathSeparators(String path) { StringBuilder ret = new StringBuilder(); @@ -536,8 +511,8 @@ public class JettyRunForkedMojo extends JettyRunMojo return ret.toString(); } - private String createToken () + private String createToken() { - return Long.toString(random.nextLong()^System.currentTimeMillis(), 36).toUpperCase(Locale.ENGLISH); + return Long.toString(random.nextLong() ^ System.currentTimeMillis(), 36).toUpperCase(Locale.ENGLISH); } } diff --git a/jetty-maven-plugin/src/main/java/org/eclipse/jetty/maven/plugin/JettyRunMojo.java b/jetty-maven-plugin/src/main/java/org/eclipse/jetty/maven/plugin/JettyRunMojo.java index c90dd62e3f6..176fb6a7406 100644 --- a/jetty-maven-plugin/src/main/java/org/eclipse/jetty/maven/plugin/JettyRunMojo.java +++ b/jetty-maven-plugin/src/main/java/org/eclipse/jetty/maven/plugin/JettyRunMojo.java @@ -48,113 +48,96 @@ import org.eclipse.jetty.util.resource.Resource; import org.eclipse.jetty.util.resource.ResourceCollection; import org.eclipse.jetty.webapp.WebAppContext; - /** - * This goal is used in-situ on a Maven project without first requiring that the project - * is assembled into a war, saving time during the development cycle. - *

    - * The plugin forks a parallel lifecycle to ensure that the "compile" phase has been completed before invoking Jetty. This means - * that you do not need to explicitly execute a "mvn compile" first. It also means that a "mvn clean jetty:run" will ensure that - * a full fresh compile is done before invoking Jetty. - *

    - * Once invoked, the plugin can be configured to run continuously, scanning for changes in the project and automatically performing a - * hot redeploy when necessary. This allows the developer to concentrate on coding changes to the project using their IDE of choice and have those changes - * immediately and transparently reflected in the running web container, eliminating development time that is wasted on rebuilding, reassembling and redeploying. - *

    - * You may also specify the location of a jetty.xml file whose contents will be applied before any plugin configuration. - * This can be used, for example, to deploy a static webapp that is not part of your maven build. - *

    - * There is a reference guide to the configuration parameters for this plugin. - * - * Runs jetty directly from a maven project + * This goal is used in-situ on a Maven project without first requiring that the project + * is assembled into a war, saving time during the development cycle. + *

    + * The plugin forks a parallel lifecycle to ensure that the "compile" phase has been completed before invoking Jetty. This means + * that you do not need to explicitly execute a "mvn compile" first. It also means that a "mvn clean jetty:run" will ensure that + * a full fresh compile is done before invoking Jetty. + *

    + * Once invoked, the plugin can be configured to run continuously, scanning for changes in the project and automatically performing a + * hot redeploy when necessary. This allows the developer to concentrate on coding changes to the project using their IDE of choice and have those changes + * immediately and transparently reflected in the running web container, eliminating development time that is wasted on rebuilding, reassembling and redeploying. + *

    + * You may also specify the location of a jetty.xml file whose contents will be applied before any plugin configuration. + * This can be used, for example, to deploy a static webapp that is not part of your maven build. + *

    + * There is a reference guide to the configuration parameters for this plugin. + * + * Runs jetty directly from a maven project */ -@Mojo( name = "run", requiresDependencyResolution = ResolutionScope.TEST) +@Mojo(name = "run", requiresDependencyResolution = ResolutionScope.TEST) @Execute(phase = LifecyclePhase.TEST_COMPILE) public class JettyRunMojo extends AbstractJettyMojo { - public static final String DEFAULT_WEBAPP_SRC = "src"+File.separator+"main"+File.separator+"webapp"; + public static final String DEFAULT_WEBAPP_SRC = "src" + File.separator + "main" + File.separator + "webapp"; public static final String FAKE_WEBAPP = "webapp-tmp"; - - /** * If true, the <testOutputDirectory> * and the dependencies of <scope>test<scope> * will be put first on the runtime classpath. - * */ - @Parameter(alias="useTestClasspath", defaultValue="false") + @Parameter(alias = "useTestClasspath", defaultValue = "false") protected boolean useTestScope; - - + /** * The default location of the web.xml file. Will be used * if <webApp><descriptor> is not set. - * */ - @Parameter(defaultValue="${maven.war.webxml}", readonly = true) + @Parameter(defaultValue = "${maven.war.webxml}", readonly = true) protected String webXml; - - + /** * The directory containing generated classes. - * */ - @Parameter(defaultValue="${project.build.outputDirectory}", required = true) + @Parameter(defaultValue = "${project.build.outputDirectory}", required = true) protected File classesDirectory; - + /** * An optional pattern for includes/excludes of classes in the classesDirectory - * */ @Parameter protected ScanPattern scanClassesPattern; /** * The directory containing generated test classes. - * */ - @Parameter(defaultValue="${project.build.testOutputDirectory}", required = true) + @Parameter(defaultValue = "${project.build.testOutputDirectory}", required = true) protected File testClassesDirectory; - + /** * An optional pattern for includes/excludes of classes in the testClassesDirectory - * */ @Parameter protected ScanPattern scanTestClassesPattern; /** * Root directory for all html/jsp etc files - * */ - @Parameter(defaultValue="${maven.war.src}") + @Parameter(defaultValue = "${maven.war.src}") protected File webAppSourceDirectory; - - + /** * List of files or directories to additionally periodically scan for changes. Optional. */ @Parameter protected File[] scanTargets; - - + /** * List of directories with ant-style <include> and <exclude> patterns * for extra targets to periodically scan for changes. Can be used instead of, * or in conjunction with <scanTargets>.Optional. - * */ @Parameter protected ScanTargetPattern[] scanTargetPatterns; - /** * maven-war-plugin reference */ protected WarPluginInfo warPluginInfo; - - + /** * List of deps that are wars */ @@ -162,7 +145,7 @@ public class JettyRunMojo extends AbstractJettyMojo protected Resource originalBaseResource; - /** + /** * @see org.eclipse.jetty.maven.plugin.AbstractJettyMojo#execute() */ @Override @@ -174,48 +157,48 @@ public class JettyRunMojo extends AbstractJettyMojo /** * Verify the configuration given in the pom. - * + * * @see AbstractJettyMojo#checkPomConfiguration() */ @Override - public boolean checkPomConfiguration () throws MojoExecutionException + public boolean checkPomConfiguration() throws MojoExecutionException { // check the location of the static content/jsps etc try { if ((webAppSourceDirectory == null) || !webAppSourceDirectory.exists()) - { - getLog().info("webAppSourceDirectory"+(webAppSourceDirectory == null ? " not set." : (webAppSourceDirectory.getAbsolutePath()+" does not exist."))+" Trying "+DEFAULT_WEBAPP_SRC); - webAppSourceDirectory = new File (project.getBasedir(), DEFAULT_WEBAPP_SRC); + { + getLog().info("webAppSourceDirectory" + (webAppSourceDirectory == null ? " not set." : (webAppSourceDirectory.getAbsolutePath() + " does not exist.")) + " Trying " + DEFAULT_WEBAPP_SRC); + webAppSourceDirectory = new File(project.getBasedir(), DEFAULT_WEBAPP_SRC); if (!webAppSourceDirectory.exists()) { - getLog().info("webAppSourceDirectory "+webAppSourceDirectory.getAbsolutePath()+" does not exist. Trying "+project.getBuild().getDirectory()+File.separator+FAKE_WEBAPP); - + getLog().info("webAppSourceDirectory " + webAppSourceDirectory.getAbsolutePath() + " does not exist. Trying " + project.getBuild().getDirectory() + File.separator + FAKE_WEBAPP); + //try last resort of making a fake empty dir File target = new File(project.getBuild().getDirectory()); webAppSourceDirectory = new File(target, FAKE_WEBAPP); if (!webAppSourceDirectory.exists()) - webAppSourceDirectory.mkdirs(); + webAppSourceDirectory.mkdirs(); } } else - getLog().info( "Webapp source directory = " + webAppSourceDirectory.getCanonicalPath()); + getLog().info("Webapp source directory = " + webAppSourceDirectory.getCanonicalPath()); } catch (IOException e) { throw new MojoExecutionException("Webapp source directory does not exist", e); } - + // check reload mechanic - if ( !"automatic".equalsIgnoreCase( reload ) && !"manual".equalsIgnoreCase( reload ) ) + if (!"automatic".equalsIgnoreCase(reload) && !"manual".equalsIgnoreCase(reload)) { - throw new MojoExecutionException( "invalid reload mechanic specified, must be 'automatic' or 'manual'" ); + throw new MojoExecutionException("invalid reload mechanic specified, must be 'automatic' or 'manual'"); } else { - getLog().info("Reload Mechanic: " + reload ); + getLog().info("Reload Mechanic: " + reload); } - getLog().info( "nonBlocking:" + nonBlocking ); + getLog().info("nonBlocking:" + nonBlocking); // check the classes to form a classpath with try @@ -224,12 +207,12 @@ public class JettyRunMojo extends AbstractJettyMojo if (classesDirectory != null) { if (!classesDirectory.exists()) - getLog().info( "Classes directory "+ classesDirectory.getCanonicalPath()+ " does not exist"); + getLog().info("Classes directory " + classesDirectory.getCanonicalPath() + " does not exist"); else getLog().info("Classes = " + classesDirectory.getCanonicalPath()); } else - getLog().info("Classes directory not set"); + getLog().info("Classes directory not set"); } catch (IOException e) { @@ -239,9 +222,6 @@ public class JettyRunMojo extends AbstractJettyMojo return true; } - - - @Override public void finishConfigurationBeforeStart() throws Exception { @@ -249,59 +229,57 @@ public class JettyRunMojo extends AbstractJettyMojo super.finishConfigurationBeforeStart(); } - - - - /** + /** * @see org.eclipse.jetty.maven.plugin.AbstractJettyMojo#configureWebApplication() */ @Override public void configureWebApplication() throws Exception { - super.configureWebApplication(); - - //Set up the location of the webapp. - //There are 2 parts to this: setWar() and setBaseResource(). On standalone jetty, - //the former could be the location of a packed war, while the latter is the location - //after any unpacking. With this mojo, you are running an unpacked, unassembled webapp, - //so the two locations should be equal. - Resource webAppSourceDirectoryResource = Resource.newResource(webAppSourceDirectory.getCanonicalPath()); - if (webApp.getWar() == null) - webApp.setWar(webAppSourceDirectoryResource.toString()); + super.configureWebApplication(); - //The first time we run, remember the original base dir - if (originalBaseResource == null) - { - if (webApp.getBaseResource() == null) - originalBaseResource = webAppSourceDirectoryResource; - else - originalBaseResource = webApp.getBaseResource(); - } + //Set up the location of the webapp. + //There are 2 parts to this: setWar() and setBaseResource(). On standalone jetty, + //the former could be the location of a packed war, while the latter is the location + //after any unpacking. With this mojo, you are running an unpacked, unassembled webapp, + //so the two locations should be equal. + Resource webAppSourceDirectoryResource = Resource.newResource(webAppSourceDirectory.getCanonicalPath()); + if (webApp.getWar() == null) + webApp.setWar(webAppSourceDirectoryResource.toString()); - //On every subsequent re-run set it back to the original base dir before - //we might have applied any war overlays onto it - webApp.setBaseResource(originalBaseResource); + //The first time we run, remember the original base dir + if (originalBaseResource == null) + { + if (webApp.getBaseResource() == null) + originalBaseResource = webAppSourceDirectoryResource; + else + originalBaseResource = webApp.getBaseResource(); + } - if (classesDirectory != null) - webApp.setClasses (classesDirectory); - if (useTestScope && (testClassesDirectory != null)) - webApp.setTestClasses (testClassesDirectory); + //On every subsequent re-run set it back to the original base dir before + //we might have applied any war overlays onto it + webApp.setBaseResource(originalBaseResource); + + if (classesDirectory != null) + webApp.setClasses(classesDirectory); + if (useTestScope && (testClassesDirectory != null)) + webApp.setTestClasses(testClassesDirectory); MavenProjectHelper mavenProjectHelper = new MavenProjectHelper(project); List webInfLibs = getWebInfLibArtifacts(project).stream() - .map(a -> { - Path p = mavenProjectHelper.getArtifactPath(a); - getLog().debug("Artifact " + a.getId() + " loaded from " + p + " added to WEB-INF/lib"); - return p.toFile(); - }).collect(Collectors.toList()); + .map(a -> + { + Path p = mavenProjectHelper.getArtifactPath(a); + getLog().debug("Artifact " + a.getId() + " loaded from " + p + " added to WEB-INF/lib"); + return p.toFile(); + }).collect(Collectors.toList()); getLog().debug("WEB-INF/lib initialized (at root)"); webApp.setWebInfLib(webInfLibs); - //if we have not already set web.xml location, need to set one up - if (webApp.getDescriptor() == null) - { - //Has an explicit web.xml file been configured to use? - if (webXml != null) + //if we have not already set web.xml location, need to set one up + if (webApp.getDescriptor() == null) + { + //Has an explicit web.xml file been configured to use? + if (webXml != null) { Resource r = Resource.newResource(webXml); if (r.exists() && !r.isDirectory()) @@ -309,7 +287,7 @@ public class JettyRunMojo extends AbstractJettyMojo webApp.setDescriptor(r.toString()); } } - + //Still don't have a web.xml file: try the resourceBase of the webapp, if it is set if (webApp.getDescriptor() == null && webApp.getBaseResource() != null) { @@ -319,32 +297,32 @@ public class JettyRunMojo extends AbstractJettyMojo webApp.setDescriptor(r.toString()); } } - + //Still don't have a web.xml file: finally try the configured static resource directory if there is one if (webApp.getDescriptor() == null && (webAppSourceDirectory != null)) { - File f = new File (new File (webAppSourceDirectory, "WEB-INF"), "web.xml"); + File f = new File(new File(webAppSourceDirectory, "WEB-INF"), "web.xml"); if (f.exists() && f.isFile()) { - webApp.setDescriptor(f.getCanonicalPath()); + webApp.setDescriptor(f.getCanonicalPath()); } } - } + } - //process any overlays and the war type artifacts - List overlays = getOverlays(); - unpackOverlays(overlays); //this sets up the base resource collection + //process any overlays and the war type artifacts + List overlays = getOverlays(); + unpackOverlays(overlays); //this sets up the base resource collection - getLog().info( "web.xml file = "+webApp.getDescriptor()); - getLog().info("Webapp directory = " + webAppSourceDirectory.getCanonicalPath()); + getLog().info("web.xml file = " + webApp.getDescriptor()); + getLog().info("Webapp directory = " + webAppSourceDirectory.getCanonicalPath()); } - /** + /** * @see org.eclipse.jetty.maven.plugin.AbstractJettyMojo#configureScanner() */ @Override - public void configureScanner () - throws MojoExecutionException + public void configureScanner() + throws MojoExecutionException { try { @@ -355,7 +333,7 @@ public class JettyRunMojo extends AbstractJettyMojo throw new MojoExecutionException("Error forming scan list", e); } - scanner.addListener( new PathWatcher.EventListListener() + scanner.addListener(new PathWatcher.EventListListener() { @Override @@ -366,7 +344,7 @@ public class JettyRunMojo extends AbstractJettyMojo boolean reconfigure = false; if (events != null) { - for (PathWatchEvent e:events) + for (PathWatchEvent e : events) { if (e.getPath().equals(project.getFile().toPath())) { @@ -380,13 +358,12 @@ public class JettyRunMojo extends AbstractJettyMojo } catch (Exception e) { - getLog().error("Error reconfiguring/restarting webapp after change in watched files",e); + getLog().error("Error reconfiguring/restarting webapp after change in watched files", e); } } }); } - public void gatherScannables() throws Exception { if (webApp.getDescriptor() != null) @@ -394,7 +371,7 @@ public class JettyRunMojo extends AbstractJettyMojo Resource r = Resource.newResource(webApp.getDescriptor()); scanner.watch(r.getFile().toPath()); } - + if (webApp.getJettyEnvXml() != null) scanner.watch(new File(webApp.getJettyEnvXml()).toPath()); @@ -408,23 +385,23 @@ public class JettyRunMojo extends AbstractJettyMojo { scanner.watch(new File(webApp.getOverrideDescriptor()).toPath()); } - - File jettyWebXmlFile = findJettyWebXmlFile(new File(webAppSourceDirectory,"WEB-INF")); + + File jettyWebXmlFile = findJettyWebXmlFile(new File(webAppSourceDirectory, "WEB-INF")); if (jettyWebXmlFile != null) { scanner.watch(jettyWebXmlFile.toPath()); } - + //make sure each of the war artifacts is added to the scanner - for (Artifact a:getWarArtifacts()) + for (Artifact a : getWarArtifacts()) { scanner.watch(a.getFile().toPath()); } - + //handle the explicit extra scan targets if (scanTargets != null) { - for (File f:scanTargets) + for (File f : scanTargets) { if (f.isDirectory()) { @@ -436,58 +413,68 @@ public class JettyRunMojo extends AbstractJettyMojo scanner.watch(f.toPath()); } } - + //handle the extra scan patterns if (scanTargetPatterns != null) { - for (ScanTargetPattern p:scanTargetPatterns) + for (ScanTargetPattern p : scanTargetPatterns) { PathWatcher.Config config = new PathWatcher.Config(p.getDirectory().toPath()); config.setRecurseDepth(PathWatcher.Config.UNLIMITED_DEPTH); - for (String pattern:p.getExcludes()) + for (String pattern : p.getExcludes()) + { config.addExcludeGlobRelative(pattern); - for (String pattern:p.getIncludes()) + } + for (String pattern : p.getIncludes()) + { config.addIncludeGlobRelative(pattern); + } scanner.watch(config); } } - scanner.watch(project.getFile().toPath()); if (webApp.getTestClasses() != null && webApp.getTestClasses().exists()) { PathWatcher.Config config = new PathWatcher.Config(webApp.getTestClasses().toPath()); - config.setRecurseDepth(PathWatcher.Config.UNLIMITED_DEPTH); + config.setRecurseDepth(PathWatcher.Config.UNLIMITED_DEPTH); if (scanTestClassesPattern != null) { - for (String p:scanTestClassesPattern.getExcludes()) + for (String p : scanTestClassesPattern.getExcludes()) + { config.addExcludeGlobRelative(p); - for (String p:scanTestClassesPattern.getIncludes()) + } + for (String p : scanTestClassesPattern.getIncludes()) + { config.addIncludeGlobRelative(p); + } } scanner.watch(config); } - + if (webApp.getClasses() != null && webApp.getClasses().exists()) { PathWatcher.Config config = new PathWatcher.Config(webApp.getClasses().toPath()); config.setRecurseDepth(PathWatcher.Config.UNLIMITED_DEPTH); if (scanClassesPattern != null) { - for (String p:scanClassesPattern.getExcludes()) + for (String p : scanClassesPattern.getExcludes()) + { config.addExcludeGlobRelative(p); + } - for (String p:scanClassesPattern.getIncludes()) + for (String p : scanClassesPattern.getIncludes()) + { config.addIncludeGlobRelative(p); - + } } scanner.watch(config); } if (webApp.getWebInfLib() != null) { - for (File f:webApp.getWebInfLib()) + for (File f : webApp.getWebInfLib()) { PathWatcher.Config config = new PathWatcher.Config(f.toPath()); config.setRecurseDepth(PathWatcher.Config.UNLIMITED_DEPTH); @@ -496,20 +483,19 @@ public class JettyRunMojo extends AbstractJettyMojo } } - - /** + /** * @see org.eclipse.jetty.maven.plugin.AbstractJettyMojo#restartWebApp(boolean) */ @Override - public void restartWebApp(boolean reconfigureScanner) throws Exception + public void restartWebApp(boolean reconfigureScanner) throws Exception { - getLog().info("restarting "+webApp); + getLog().info("restarting " + webApp); getLog().debug("Stopping webapp ..."); stopScanner(); webApp.stop(); getLog().debug("Reconfiguring webapp ..."); - + checkPomConfiguration(); configureWebApplication(); @@ -526,14 +512,14 @@ public class JettyRunMojo extends AbstractJettyMojo getLog().debug("Restarting webapp ..."); webApp.start(); startScanner(); - getLog().info("Restart completed at "+new Date().toString()); + getLog().info("Restart completed at " + new Date().toString()); } private Collection getWebInfLibArtifacts(Set artifacts) { return artifacts.stream() - .filter(this::canPutArtifactInWebInfLib) - .collect(Collectors.toList()); + .filter(this::canPutArtifactInWebInfLib) + .collect(Collectors.toList()); } private Collection getWebInfLibArtifacts(MavenProject mavenProject) @@ -564,12 +550,12 @@ public class JettyRunMojo extends AbstractJettyMojo } private List getOverlays() - throws Exception + throws Exception { //get copy of a list of war artifacts Set matchedWarArtifacts = new HashSet<>(); List overlays = new ArrayList<>(); - for (OverlayConfig config:warPluginInfo.getMavenWarOverlayConfigs()) + for (OverlayConfig config : warPluginInfo.getMavenWarOverlayConfigs()) { //overlays can be individually skipped if (config.isSkip()) @@ -588,7 +574,7 @@ public class JettyRunMojo extends AbstractJettyMojo if (a != null) { matchedWarArtifacts.add(a); - SelectiveJarResource r = new SelectiveJarResource(new URL("jar:"+Resource.toURL(a.getFile()).toString()+"!/")); + SelectiveJarResource r = new SelectiveJarResource(new URL("jar:" + Resource.toURL(a.getFile()).toString() + "!/")); r.setIncludes(config.getIncludes()); r.setExcludes(config.getExcludes()); Overlay overlay = new Overlay(config, r); @@ -597,32 +583,31 @@ public class JettyRunMojo extends AbstractJettyMojo } //iterate over the left over war artifacts and unpack them (without include/exclude processing) as necessary - for (Artifact a: getWarArtifacts()) + for (Artifact a : getWarArtifacts()) { if (!matchedWarArtifacts.contains(a)) { - Overlay overlay = new Overlay(null, Resource.newResource(new URL("jar:"+Resource.toURL(a.getFile()).toString()+"!/"))); + Overlay overlay = new Overlay(null, Resource.newResource(new URL("jar:" + Resource.toURL(a.getFile()).toString() + "!/"))); overlays.add(overlay); } } return overlays; } - - public void unpackOverlays (List overlays) - throws Exception + public void unpackOverlays(List overlays) + throws Exception { if (overlays == null || overlays.isEmpty()) return; List resourceBaseCollection = new ArrayList<>(); - for (Overlay o:overlays) + for (Overlay o : overlays) { //can refer to the current project in list of overlays for ordering purposes if (o.getConfig() != null && o.getConfig().isCurrentProject() && webApp.getBaseResource().exists()) { - resourceBaseCollection.add(webApp.getBaseResource()); + resourceBaseCollection.add(webApp.getBaseResource()); continue; } @@ -644,64 +629,61 @@ public class JettyRunMojo extends AbstractJettyMojo } webApp.setBaseResource(new ResourceCollection(resourceBaseCollection.toArray(new Resource[resourceBaseCollection.size()]))); } - - - - public Resource unpackOverlay (Overlay overlay) - throws IOException - { + public Resource unpackOverlay(Overlay overlay) + throws IOException + { if (overlay.getResource() == null) return null; //nothing to unpack - + //Get the name of the overlayed war and unpack it to a dir of the //same name in the temporary directory String name = overlay.getResource().getName(); if (name.endsWith("!/")) - name = name.substring(0,name.length()-2); + name = name.substring(0, name.length() - 2); int i = name.lastIndexOf('/'); - if (i>0) - name = name.substring(i+1,name.length()); + if (i > 0) + name = name.substring(i + 1, name.length()); name = StringUtil.replace(name, '.', '_'); //name = name+(++COUNTER); //add some digits to ensure uniqueness - File overlaysDir = new File (project.getBuild().getDirectory(), "jetty_overlays"); + File overlaysDir = new File(project.getBuild().getDirectory(), "jetty_overlays"); File dir = new File(overlaysDir, name); //if specified targetPath, unpack to that subdir instead File unpackDir = dir; if (overlay.getConfig() != null && overlay.getConfig().getTargetPath() != null) - unpackDir = new File (dir, overlay.getConfig().getTargetPath()); + unpackDir = new File(dir, overlay.getConfig().getTargetPath()); //only unpack if the overlay is newer if (!unpackDir.exists() || (overlay.getResource().lastModified() > unpackDir.lastModified())) { - boolean made=unpackDir.mkdirs(); + boolean made = unpackDir.mkdirs(); overlay.getResource().copyTo(unpackDir); } //use top level of unpacked content - return Resource.newResource(dir.getCanonicalPath()); + return Resource.newResource(dir.getCanonicalPath()); } - + /** - * @return + * */ - private List getWarArtifacts () + private List getWarArtifacts() { if (warArtifacts != null) - return warArtifacts; - + return warArtifacts; + warArtifacts = new ArrayList<>(); - for ( Artifact artifact : projectArtifacts) + for (Artifact artifact : projectArtifacts) { if (artifact.getType().equals("war") || artifact.getType().equals("zip")) { try - { + { warArtifacts.add(artifact); - getLog().info("Dependent war artifact "+artifact.getId()); + getLog().info("Dependent war artifact " + artifact.getId()); } - catch(Exception e) + catch (Exception e) { throw new RuntimeException(e); } @@ -710,36 +692,33 @@ public class JettyRunMojo extends AbstractJettyMojo return warArtifacts; } - protected Artifact getArtifactForOverlay (OverlayConfig o, List warArtifacts) + protected Artifact getArtifactForOverlay(OverlayConfig o, List warArtifacts) { if (o == null || warArtifacts == null || warArtifacts.isEmpty()) return null; - - for (Artifact a:warArtifacts) + + for (Artifact a : warArtifacts) { - if (o.matchesArtifact (a.getGroupId(), a.getArtifactId(), a.getClassifier())) + if (o.matchesArtifact(a.getGroupId(), a.getArtifactId(), a.getClassifier())) { - return a; + return a; } } - + return null; } - - /** - * @return + * */ protected String getJavaBin() { - String javaexes[] = new String[] - { "java", "java.exe" }; + String[] javaexes = {"java", "java.exe"}; File javaHomeDir = new File(System.getProperty("java.home")); for (String javaexe : javaexes) { - File javabin = new File(javaHomeDir,fileSeparators("bin/" + javaexe)); + File javabin = new File(javaHomeDir, fileSeparators("bin/" + javaexe)); if (javabin.exists() && javabin.isFile()) { return javabin.getAbsolutePath(); diff --git a/jetty-maven-plugin/src/main/java/org/eclipse/jetty/maven/plugin/JettyRunWarExplodedMojo.java b/jetty-maven-plugin/src/main/java/org/eclipse/jetty/maven/plugin/JettyRunWarExplodedMojo.java index 78405efc199..e41aa04f7ee 100644 --- a/jetty-maven-plugin/src/main/java/org/eclipse/jetty/maven/plugin/JettyRunWarExplodedMojo.java +++ b/jetty-maven-plugin/src/main/java/org/eclipse/jetty/maven/plugin/JettyRunWarExplodedMojo.java @@ -32,40 +32,37 @@ import org.eclipse.jetty.util.PathWatcher; import org.eclipse.jetty.util.PathWatcher.PathWatchEvent; /** - * - *

    - * This goal is used to assemble your webapp into an exploded war and automatically deploy it to Jetty. - *

    - *

    - * Once invoked, the plugin runs continuously, and can be configured to scan for changes in the pom.xml and - * to WEB-INF/web.xml, WEB-INF/classes or WEB-INF/lib and hot redeploy when a change is detected. - *

    - *

    - * You may also specify the location of a jetty.xml file whose contents will be applied before any plugin configuration. - * This can be used, for example, to deploy a static webapp that is not part of your maven build. - *

    + *

    + * This goal is used to assemble your webapp into an exploded war and automatically deploy it to Jetty. + *

    + *

    + * Once invoked, the plugin runs continuously, and can be configured to scan for changes in the pom.xml and + * to WEB-INF/web.xml, WEB-INF/classes or WEB-INF/lib and hot redeploy when a change is detected. + *

    + *

    + * You may also specify the location of a jetty.xml file whose contents will be applied before any plugin configuration. + * This can be used, for example, to deploy a static webapp that is not part of your maven build. + *

    */ -@Mojo( name = "run-exploded", requiresDependencyResolution = ResolutionScope.COMPILE_PLUS_RUNTIME) +@Mojo(name = "run-exploded", requiresDependencyResolution = ResolutionScope.COMPILE_PLUS_RUNTIME) @Execute(phase = LifecyclePhase.PACKAGE) public class JettyRunWarExplodedMojo extends AbstractJettyMojo { - + /** * The location of the war file. */ - @Parameter(defaultValue="${project.build.directory}/${project.build.finalName}", required = true) + @Parameter(defaultValue = "${project.build.directory}/${project.build.finalName}", required = true) private File war; - /** + /** * @see org.eclipse.jetty.maven.plugin.AbstractJettyMojo#execute() */ @Override - public void execute () throws MojoExecutionException, MojoFailureException + public void execute() throws MojoExecutionException, MojoFailureException { super.execute(); } - - @Override public void finishConfigurationBeforeStart() throws Exception @@ -73,7 +70,6 @@ public class JettyRunWarExplodedMojo extends AbstractJettyMojo server.setStopAtShutdown(true); //as we will normally be stopped with a cntrl-c, ensure server stopped super.finishConfigurationBeforeStart(); } - /** * @see AbstractJettyMojo#configureScanner() @@ -82,7 +78,7 @@ public class JettyRunWarExplodedMojo extends AbstractJettyMojo public void configureScanner() throws MojoExecutionException { scanner.watch(project.getFile().toPath()); - File webInfDir = new File(war,"WEB-INF"); + File webInfDir = new File(war, "WEB-INF"); File webXml = new File(webInfDir, "web.xml"); if (webXml.exists()) scanner.watch(webXml.toPath()); @@ -106,7 +102,7 @@ public class JettyRunWarExplodedMojo extends AbstractJettyMojo { PathWatcher.Config libConfig = new PathWatcher.Config(lib.toPath()); libConfig.setRecurseDepth(PathWatcher.Config.UNLIMITED_DEPTH); - scanner.watch(libConfig); + scanner.watch(libConfig); } scanner.addListener(new PathWatcher.EventListListener() @@ -118,7 +114,7 @@ public class JettyRunWarExplodedMojo extends AbstractJettyMojo try { boolean reconfigure = false; - for (PathWatchEvent e:events) + for (PathWatchEvent e : events) { if (e.getPath().equals(project.getFile().toPath())) { @@ -130,20 +126,17 @@ public class JettyRunWarExplodedMojo extends AbstractJettyMojo } catch (Exception e) { - getLog().error("Error reconfiguring/restarting webapp after change in watched files",e); + getLog().error("Error reconfiguring/restarting webapp after change in watched files", e); } } }); } - - - - /** + /** * @see org.eclipse.jetty.maven.plugin.AbstractJettyMojo#restartWebApp(boolean) */ @Override - public void restartWebApp(boolean reconfigureScanner) throws Exception + public void restartWebApp(boolean reconfigureScanner) throws Exception { getLog().info("Restarting webapp"); getLog().debug("Stopping webapp ..."); @@ -168,16 +161,13 @@ public class JettyRunWarExplodedMojo extends AbstractJettyMojo getLog().info("Restart completed."); } - - - - /** + /** * @see org.eclipse.jetty.maven.plugin.AbstractJettyMojo#configureWebApplication() */ @Override - public void configureWebApplication () throws Exception + public void configureWebApplication() throws Exception { - super.configureWebApplication(); + super.configureWebApplication(); webApp.setWar(war.getCanonicalPath()); } } diff --git a/jetty-maven-plugin/src/main/java/org/eclipse/jetty/maven/plugin/JettyRunWarMojo.java b/jetty-maven-plugin/src/main/java/org/eclipse/jetty/maven/plugin/JettyRunWarMojo.java index b91d877a262..df69738a26a 100644 --- a/jetty-maven-plugin/src/main/java/org/eclipse/jetty/maven/plugin/JettyRunWarMojo.java +++ b/jetty-maven-plugin/src/main/java/org/eclipse/jetty/maven/plugin/JettyRunWarMojo.java @@ -33,28 +33,27 @@ import org.eclipse.jetty.util.PathWatcher.PathWatchEvent; /** *

    - * This goal is used to assemble your webapp into a war and automatically deploy it to Jetty. - *

    - *

    - * Once invoked, the plugin runs continuously and can be configured to scan for changes in the project and to the - * war file and automatically perform a hot redeploy when necessary. - *

    - *

    - * You may also specify the location of a jetty.xml file whose contents will be applied before any plugin configuration. - * This can be used, for example, to deploy a static webapp that is not part of your maven build. - *

    - * Runs jetty on a war file + * This goal is used to assemble your webapp into a war and automatically deploy it to Jetty. + *

    + *

    + * Once invoked, the plugin runs continuously and can be configured to scan for changes in the project and to the + * war file and automatically perform a hot redeploy when necessary. + *

    + *

    + * You may also specify the location of a jetty.xml file whose contents will be applied before any plugin configuration. + * This can be used, for example, to deploy a static webapp that is not part of your maven build. + *

    + * Runs jetty on a war file */ -@Mojo( name = "run-war", requiresDependencyResolution = ResolutionScope.COMPILE_PLUS_RUNTIME) +@Mojo(name = "run-war", requiresDependencyResolution = ResolutionScope.COMPILE_PLUS_RUNTIME) @Execute(phase = LifecyclePhase.PACKAGE) public class JettyRunWarMojo extends AbstractJettyMojo { /** * The location of the war file. - * */ - @Parameter(defaultValue="${project.build.directory}/${project.build.finalName}.war", required = true) + @Parameter(defaultValue = "${project.build.directory}/${project.build.finalName}.war", required = true) private File war; /** @@ -63,10 +62,9 @@ public class JettyRunWarMojo extends AbstractJettyMojo @Override public void execute() throws MojoExecutionException, MojoFailureException { - super.execute(); + super.execute(); } - @Override public void finishConfigurationBeforeStart() throws Exception { @@ -74,17 +72,13 @@ public class JettyRunWarMojo extends AbstractJettyMojo super.finishConfigurationBeforeStart(); } - - @Override - public void configureWebApplication () throws Exception + public void configureWebApplication() throws Exception { super.configureWebApplication(); - + webApp.setWar(war.getCanonicalPath()); } - - /** * @see AbstractJettyMojo#configureScanner() @@ -104,7 +98,7 @@ public class JettyRunWarMojo extends AbstractJettyMojo try { boolean reconfigure = false; - for (PathWatchEvent e:events) + for (PathWatchEvent e : events) { if (e.getPath().equals(project.getFile().toPath())) { @@ -116,20 +110,17 @@ public class JettyRunWarMojo extends AbstractJettyMojo } catch (Exception e) { - getLog().error("Error reconfiguring/restarting webapp after change in watched files",e); + getLog().error("Error reconfiguring/restarting webapp after change in watched files", e); } } }); } - - - - /** + /** * @see org.eclipse.jetty.maven.plugin.AbstractJettyMojo#restartWebApp(boolean) */ @Override - public void restartWebApp(boolean reconfigureScanner) throws Exception + public void restartWebApp(boolean reconfigureScanner) throws Exception { getLog().info("Restarting webapp ..."); getLog().debug("Stopping webapp ..."); @@ -153,5 +144,4 @@ public class JettyRunWarMojo extends AbstractJettyMojo startScanner(); getLog().info("Restart completed."); } - } diff --git a/jetty-maven-plugin/src/main/java/org/eclipse/jetty/maven/plugin/JettyStartMojo.java b/jetty-maven-plugin/src/main/java/org/eclipse/jetty/maven/plugin/JettyStartMojo.java index a503f041eb2..239a6d3389c 100644 --- a/jetty-maven-plugin/src/main/java/org/eclipse/jetty/maven/plugin/JettyStartMojo.java +++ b/jetty-maven-plugin/src/main/java/org/eclipse/jetty/maven/plugin/JettyStartMojo.java @@ -25,21 +25,20 @@ import org.apache.maven.plugins.annotations.LifecyclePhase; import org.apache.maven.plugins.annotations.Mojo; import org.apache.maven.plugins.annotations.ResolutionScope; - /** - *

    - * This goal is similar to the jetty:run goal, EXCEPT that it is designed to be bound to an execution inside your pom, rather - * than being run from the command line. - *

    - *

    - * When using it, be careful to ensure that you bind it to a phase in which all necessary generated files and classes for the webapp - * will have been created. If you run it from the command line, then also ensure that all necessary generated files and classes for - * the webapp already exist. - *

    - * - * Runs jetty directly from a maven project from a binding to an execution in your pom + *

    + * This goal is similar to the jetty:run goal, EXCEPT that it is designed to be bound to an execution inside your pom, rather + * than being run from the command line. + *

    + *

    + * When using it, be careful to ensure that you bind it to a phase in which all necessary generated files and classes for the webapp + * will have been created. If you run it from the command line, then also ensure that all necessary generated files and classes for + * the webapp already exist. + *

    + * + * Runs jetty directly from a maven project from a binding to an execution in your pom */ -@Mojo( name = "start", requiresDependencyResolution = ResolutionScope.TEST) +@Mojo(name = "start", requiresDependencyResolution = ResolutionScope.TEST) @Execute(phase = LifecyclePhase.VALIDATE) public class JettyStartMojo extends JettyRunMojo { @@ -50,12 +49,11 @@ public class JettyStartMojo extends JettyRunMojo nonBlocking = true; //ensure that starting jetty won't hold up the thread super.execute(); } - + @Override public void finishConfigurationBeforeStart() throws Exception { super.finishConfigurationBeforeStart(); server.setStopAtShutdown(false); //as we will normally be stopped with a cntrl-c, ensure server stopped } - } diff --git a/jetty-maven-plugin/src/main/java/org/eclipse/jetty/maven/plugin/JettyStopMojo.java b/jetty-maven-plugin/src/main/java/org/eclipse/jetty/maven/plugin/JettyStopMojo.java index 0f832162861..c1a6f4c8be0 100644 --- a/jetty-maven-plugin/src/main/java/org/eclipse/jetty/maven/plugin/JettyStopMojo.java +++ b/jetty-maven-plugin/src/main/java/org/eclipse/jetty/maven/plugin/JettyStopMojo.java @@ -33,62 +33,59 @@ import org.apache.maven.plugins.annotations.Parameter; /** * This goal stops a running instance of jetty. - * + * * The stopPort and stopKey parameters can be used to * configure which jetty to stop. - * + * * Stops jetty that is configured with <stopKey> and <stopPort>. */ -@Mojo( name = "stop") +@Mojo(name = "stop") public class JettyStopMojo extends AbstractMojo { - + /** * Port to listen to stop jetty on sending stop command */ @Parameter(required = true) protected int stopPort; - + /** - * Key to provide when stopping jetty on executing java -DSTOP.KEY=<stopKey> + * Key to provide when stopping jetty on executing java -DSTOP.KEY=<stopKey> * -DSTOP.PORT=<stopPort> -jar start.jar --stop */ @Parameter(required = true) protected String stopKey; - + /** * Max time in seconds that the plugin will wait for confirmation that jetty has stopped. */ @Parameter protected int stopWait; - - - @Override - public void execute() throws MojoExecutionException, MojoFailureException + public void execute() throws MojoExecutionException, MojoFailureException { if (stopPort <= 0) - throw new MojoExecutionException("Please specify a valid port"); + throw new MojoExecutionException("Please specify a valid port"); if (stopKey == null) - throw new MojoExecutionException("Please specify a valid stopKey"); + throw new MojoExecutionException("Please specify a valid stopKey"); //Ensure jetty Server instance stops. Whether or not the remote process //also stops depends whether or not it was started with ShutdownMonitor.exitVm=true - String command = "forcestop"; - - try(Socket s=new Socket(InetAddress.getByName("127.0.0.1"),stopPort);) - { - OutputStream out=s.getOutputStream(); - out.write((stopKey+"\r\n"+command+"\r\n").getBytes()); + String command = "forcestop"; + + try (Socket s = new Socket(InetAddress.getByName("127.0.0.1"), stopPort);) + { + OutputStream out = s.getOutputStream(); + out.write((stopKey + "\r\n" + command + "\r\n").getBytes()); out.flush(); if (stopWait > 0) - { + { s.setSoTimeout(stopWait * 1000); s.getInputStream(); - getLog().info("Waiting "+stopWait+" seconds for jetty to stop"); + getLog().info("Waiting " + stopWait + " seconds for jetty to stop"); LineNumberReader lin = new LineNumberReader(new InputStreamReader(s.getInputStream())); String response; boolean stopped = false; @@ -98,7 +95,7 @@ public class JettyStopMojo extends AbstractMojo { stopped = true; getLog().info("Server reports itself as stopped"); - } + } } } } @@ -112,19 +109,23 @@ public class JettyStopMojo extends AbstractMojo } } - public int getStopPort() { + public int getStopPort() + { return stopPort; } - public void setStopPort(int stopPort) { + public void setStopPort(int stopPort) + { this.stopPort = stopPort; } - public String getStopKey() { + public String getStopKey() + { return stopKey; } - public void setStopKey(String stopKey) { + public void setStopKey(String stopKey) + { this.stopKey = stopKey; } } diff --git a/jetty-maven-plugin/src/main/java/org/eclipse/jetty/maven/plugin/JettyWebAppContext.java b/jetty-maven-plugin/src/main/java/org/eclipse/jetty/maven/plugin/JettyWebAppContext.java index 2e925d215df..79c8509ad70 100644 --- a/jetty-maven-plugin/src/main/java/org/eclipse/jetty/maven/plugin/JettyWebAppContext.java +++ b/jetty-maven-plugin/src/main/java/org/eclipse/jetty/maven/plugin/JettyWebAppContext.java @@ -52,12 +52,11 @@ import org.eclipse.jetty.webapp.WebAppContext; /** * JettyWebAppContext - * + * * Extends the WebAppContext to specialize for the maven environment. We pass in * the list of files that should form the classpath for the webapp when * executing in the plugin, and any jetty-env.xml file that may have been * configured. - * */ public class JettyWebAppContext extends WebAppContext { @@ -216,7 +215,7 @@ public class JettyWebAppContext extends WebAppContext * xml. * * @param generateOrigin if true then the origin of each xml element is - * added, otherwise it is omitted. + * added, otherwise it is omitted. */ public void setGenerateOrigin(boolean generateOrigin) { @@ -251,7 +250,6 @@ public class JettyWebAppContext extends WebAppContext * Set the file to use into which to generate the quickstart output. * * @param quickStartWebXml the full path to the file to use - * @throws Exception */ public void setQuickStartWebDescriptor(String quickStartWebXml) throws Exception { @@ -260,8 +258,6 @@ public class JettyWebAppContext extends WebAppContext /** * Set the Resource to use into which to generate the quickstart output. - * - * @param quickStartWebXml */ protected void setQuickStartWebDescriptor(Resource quickStartWebXml) { @@ -274,9 +270,9 @@ public class JettyWebAppContext extends WebAppContext if (o == null) return null; else if (o instanceof Resource) - return (Resource) o; + return (Resource)o; else - return Resource.newResource((String) o); + return Resource.newResource((String)o); } /** @@ -284,8 +280,8 @@ public class JettyWebAppContext extends WebAppContext * configuration * * @param resourceBases Array of resources strings to set as a - * {@link ResourceCollection}. Each resource string may be a - * comma separated list of resources + * {@link ResourceCollection}. Each resource string may be a + * comma separated list of resources */ public void setResourceBases(String[] resourceBases) { @@ -294,7 +290,9 @@ public class JettyWebAppContext extends WebAppContext { String[] rs = StringUtil.csvSplit(rl); for (String r : rs) + { resources.add(r); + } } setBaseResource(new ResourceCollection(resources.toArray(new String[resources.size()]))); } @@ -351,7 +349,8 @@ public class JettyWebAppContext extends WebAppContext // classpath // that will be scanned - note that by default NO jars are scanned String tmp = _containerIncludeJarPattern; - if (tmp == null || "".equals(tmp)) tmp = (String) getAttribute(MetaInfConfiguration.CONTAINER_JAR_PATTERN); + if (tmp == null || "".equals(tmp)) + tmp = (String)getAttribute(MetaInfConfiguration.CONTAINER_JAR_PATTERN); tmp = addPattern(tmp, DEFAULT_CONTAINER_INCLUDE_JAR_PATTERN); setAttribute(MetaInfConfiguration.CONTAINER_JAR_PATTERN, tmp); @@ -361,12 +360,15 @@ public class JettyWebAppContext extends WebAppContext // Note that by default ALL jars considered to be in WEB-INF will be // scanned - setting // a pattern restricts scanning - if (_webInfIncludeJarPattern != null) setAttribute(MetaInfConfiguration.WEBINF_JAR_PATTERN, _webInfIncludeJarPattern); + if (_webInfIncludeJarPattern != null) + setAttribute(MetaInfConfiguration.WEBINF_JAR_PATTERN, _webInfIncludeJarPattern); // Set up the classes dirs that comprises the equivalent of // WEB-INF/classes - if (_testClasses != null) _webInfClasses.add(_testClasses); - if (_classes != null) _webInfClasses.add(_classes); + if (_testClasses != null) + _webInfClasses.add(_testClasses); + if (_classes != null) + _webInfClasses.add(_classes); // Set up the classpath _classpathFiles = new ArrayList<>(); @@ -379,7 +381,8 @@ public class JettyWebAppContext extends WebAppContext { // Return all jar files from class path String fileName = file.getName(); - if (fileName.endsWith(".jar")) _webInfJarMap.put(fileName, file); + if (fileName.endsWith(".jar")) + _webInfJarMap.put(fileName, file); } // check for CDI @@ -399,7 +402,7 @@ public class JettyWebAppContext extends WebAppContext for (Configuration c : getWebAppConfigurations()) { if (c instanceof EnvConfiguration && getJettyEnvXml() != null) - ((EnvConfiguration) c).setJettyEnvResource(new PathResource(new File(getJettyEnvXml()))); + ((EnvConfiguration)c).setJettyEnvResource(new PathResource(new File(getJettyEnvXml()))); } } catch (Exception e) @@ -411,13 +414,15 @@ public class JettyWebAppContext extends WebAppContext @Override public void doStop() throws Exception { - if (_classpathFiles != null) _classpathFiles.clear(); + if (_classpathFiles != null) + _classpathFiles.clear(); _classpathFiles = null; _classes = null; _testClasses = null; - if (_webInfJarMap != null) _webInfJarMap.clear(); + if (_webInfJarMap != null) + _webInfJarMap.clear(); _webInfClasses.clear(); _webInfJars.clear(); @@ -452,7 +457,8 @@ public class JettyWebAppContext extends WebAppContext if ((resource == null || !resource.exists()) && uriInContext != null && _classes != null) { String uri = URIUtil.canonicalPath(uriInContext); - if (uri == null) return null; + if (uri == null) + return null; try { @@ -466,7 +472,8 @@ public class JettyWebAppContext extends WebAppContext // rather than the test classes if (_classes != null) return Resource.newResource(_classes); - else if (_testClasses != null) return Resource.newResource(_testClasses); + else if (_testClasses != null) + return Resource.newResource(_testClasses); } else { @@ -491,12 +498,13 @@ public class JettyWebAppContext extends WebAppContext // Return the real jar file for all accesses to // /WEB-INF/lib/*.jar String jarName = StringUtil.strip(uri, WEB_INF_LIB_PREFIX); - if (jarName.startsWith("/") || jarName.startsWith("\\")) + if (jarName.startsWith("/") || jarName.startsWith("\\")) jarName = jarName.substring(1); - if (jarName.length()==0) + if (jarName.length() == 0) return null; File jarFile = _webInfJarMap.get(jarName); - if (jarFile != null) return Resource.newResource(jarFile.getPath()); + if (jarFile != null) + return Resource.newResource(jarFile.getPath()); return null; } @@ -559,7 +567,8 @@ public class JettyWebAppContext extends WebAppContext if (!s.contains(pattern)) { - if (s.length() != 0) s = s + "|"; + if (s.length() != 0) + s = s + "|"; s = s + pattern; } @@ -572,8 +581,8 @@ public class JettyWebAppContext extends WebAppContext try { cdiInitializer = Thread.currentThread().getContextClassLoader().loadClass("org.eclipse.jetty.cdi.servlet.JettyWeldInitializer"); - Method initWebAppMethod = cdiInitializer.getMethod("initWebApp", new Class[] { WebAppContext.class }); - initWebAppMethod.invoke(null, new Object[] { this }); + Method initWebAppMethod = cdiInitializer.getMethod("initWebApp", new Class[]{WebAppContext.class}); + initWebAppMethod.invoke(null, new Object[]{this}); } catch (ClassNotFoundException e) { diff --git a/jetty-maven-plugin/src/main/java/org/eclipse/jetty/maven/plugin/MavenMetaInfConfiguration.java b/jetty-maven-plugin/src/main/java/org/eclipse/jetty/maven/plugin/MavenMetaInfConfiguration.java index 21a2106034e..f70eda576db 100644 --- a/jetty-maven-plugin/src/main/java/org/eclipse/jetty/maven/plugin/MavenMetaInfConfiguration.java +++ b/jetty-maven-plugin/src/main/java/org/eclipse/jetty/maven/plugin/MavenMetaInfConfiguration.java @@ -30,11 +30,9 @@ import org.eclipse.jetty.webapp.Configuration; import org.eclipse.jetty.webapp.MetaInfConfiguration; import org.eclipse.jetty.webapp.WebAppContext; - - /** * MavenWebInfConfiguration - * + * * WebInfConfiguration to take account of overlaid wars expressed as project dependencies and * potential configured via the maven-war-plugin. */ @@ -42,7 +40,7 @@ public class MavenMetaInfConfiguration extends MetaInfConfiguration { private static final Logger LOG = Log.getLogger(MavenMetaInfConfiguration.class); - protected static int COUNTER = 0; + protected static int COUNTER = 0; @Override public Class replaces() @@ -54,25 +52,26 @@ public class MavenMetaInfConfiguration extends MetaInfConfiguration * Get the jars to examine from the files from which we have * synthesized the classpath. Note that the classpath is not * set at this point, so we cannot get them from the classpath. + * * @param context the web app context * @return the list of jars found */ @Override - protected List findJars (WebAppContext context) - throws Exception + protected List findJars(WebAppContext context) + throws Exception { List list = new ArrayList<>(); JettyWebAppContext jwac = (JettyWebAppContext)context; List files = jwac.getWebInfLib(); if (files != null) { - files.forEach( file -> { - if (file.getName().toLowerCase(Locale.ENGLISH).endsWith(".jar") - || file.isDirectory()) + files.forEach(file -> + { + if (file.getName().toLowerCase(Locale.ENGLISH).endsWith(".jar") || file.isDirectory()) { try { - LOG.debug( " add resource to resources to examine {}", file ); + LOG.debug(" add resource to resources to examine {}", file); list.add(Resource.newResource(file.toURI())); } catch (Exception e) @@ -80,32 +79,31 @@ public class MavenMetaInfConfiguration extends MetaInfConfiguration LOG.warn("Bad url ", e); } } - } ); + }); } List superList = super.findJars(context); if (superList != null) list.addAll(superList); - return list; + return list; } - - - - /** + /** * Add in the classes dirs from test/classes and target/classes + * * @see org.eclipse.jetty.webapp.MetaInfConfiguration#findClassDirs(org.eclipse.jetty.webapp.WebAppContext) */ @Override protected List findClassDirs(WebAppContext context) throws Exception - { + { List list = new ArrayList<>(); - + JettyWebAppContext jwac = (JettyWebAppContext)context; List files = jwac.getWebInfClasses(); if (files != null) { - files.forEach( file -> { + files.forEach(file -> + { if (file.exists() && file.isDirectory()) { try @@ -117,10 +115,9 @@ public class MavenMetaInfConfiguration extends MetaInfConfiguration LOG.warn("Bad url ", e); } } - } ); - + }); } - + List classesDirs = super.findClassDirs(context); if (classesDirs != null) list.addAll(classesDirs); diff --git a/jetty-maven-plugin/src/main/java/org/eclipse/jetty/maven/plugin/MavenQuickStartConfiguration.java b/jetty-maven-plugin/src/main/java/org/eclipse/jetty/maven/plugin/MavenQuickStartConfiguration.java index 2903901f1f7..597c313555e 100644 --- a/jetty-maven-plugin/src/main/java/org/eclipse/jetty/maven/plugin/MavenQuickStartConfiguration.java +++ b/jetty-maven-plugin/src/main/java/org/eclipse/jetty/maven/plugin/MavenQuickStartConfiguration.java @@ -16,11 +16,9 @@ // ======================================================================== // - package org.eclipse.jetty.maven.plugin; import java.io.File; -import java.util.Iterator; import org.eclipse.jetty.quickstart.QuickStartConfiguration; import org.eclipse.jetty.util.IO; @@ -33,61 +31,61 @@ import org.eclipse.jetty.webapp.WebAppContext; /** * MavenQuickStartConfiguration - * - * */ public class MavenQuickStartConfiguration extends QuickStartConfiguration { private static final Logger LOG = Log.getLogger(QuickStartConfiguration.class); - + private Resource _quickStartWebXml; //the descriptor to use for starting/generating quickstart public void setQuickStartWebXml(Resource quickStartWebXml) { _quickStartWebXml = quickStartWebXml; } - - + @Override public Resource getQuickStartWebXml(WebAppContext context) throws Exception { if (_quickStartWebXml == null) return super.getQuickStartWebXml(context); - + return _quickStartWebXml; } @Override public void preConfigure(WebAppContext context) throws Exception - { + { //check that webapp is suitable for quick start if (context.getBaseResource() == null) - throw new IllegalStateException ("No location for webapp"); + throw new IllegalStateException("No location for webapp"); - //look for quickstart-web.xml in WEB-INF of webapp Resource quickStartWebXml = getQuickStartWebXml(context); - if (LOG.isDebugEnabled()) LOG.debug("quickStartWebXml={}",quickStartWebXml); + if (LOG.isDebugEnabled()) + LOG.debug("quickStartWebXml={}", quickStartWebXml); super.preConfigure(context); } @Override public void configure(WebAppContext context) throws Exception { - JettyWebAppContext jwac = (JettyWebAppContext)context; - + JettyWebAppContext jwac = (JettyWebAppContext)context; + //put the classes dir and all dependencies into the classpath if (jwac.getClassPathFiles() != null) { - if (LOG.isDebugEnabled()) LOG.debug("Setting up classpath ..."); - for(File classPathFile:jwac.getClassPathFiles()) + if (LOG.isDebugEnabled()) + LOG.debug("Setting up classpath ..."); + for (File classPathFile : jwac.getClassPathFiles()) + { ((WebAppClassLoader)context.getClassLoader()).addClassPath(classPathFile.getCanonicalPath()); + } } - + //Set up the quickstart environment for the context - super.configure(context); + super.configure(context); } - + @Override public void deconfigure(WebAppContext context) throws Exception { @@ -102,7 +100,7 @@ public class MavenQuickStartConfiguration extends QuickStartConfiguration Resource res = context.getBaseResource(); if (res instanceof ResourceCollection) { - for (Resource r:((ResourceCollection)res).getResources()) + for (Resource r : ((ResourceCollection)res).getResources()) { if (originalBaseStr.contains(r.toString())) continue; @@ -112,5 +110,4 @@ public class MavenQuickStartConfiguration extends QuickStartConfiguration } super.deconfigure(context); } - } diff --git a/jetty-maven-plugin/src/main/java/org/eclipse/jetty/maven/plugin/MavenServerConnector.java b/jetty-maven-plugin/src/main/java/org/eclipse/jetty/maven/plugin/MavenServerConnector.java index 904a0d6987a..4cb641a379a 100644 --- a/jetty-maven-plugin/src/main/java/org/eclipse/jetty/maven/plugin/MavenServerConnector.java +++ b/jetty-maven-plugin/src/main/java/org/eclipse/jetty/maven/plugin/MavenServerConnector.java @@ -16,7 +16,6 @@ // ======================================================================== // - package org.eclipse.jetty.maven.plugin; import java.util.Collection; @@ -34,9 +33,6 @@ import org.eclipse.jetty.util.annotation.ManagedAttribute; import org.eclipse.jetty.util.component.ContainerLifeCycle; import org.eclipse.jetty.util.thread.Scheduler; - - - /** * MavenServerConnector * @@ -48,11 +44,11 @@ import org.eclipse.jetty.util.thread.Scheduler; public class MavenServerConnector extends ContainerLifeCycle implements Connector { public static String PORT_SYSPROPERTY = "jetty.http.port"; - + public static final int DEFAULT_PORT = 8080; public static final String DEFAULT_PORT_STR = String.valueOf(DEFAULT_PORT); public static final int DEFAULT_MAX_IDLE_TIME = 30000; - + private Server server; private volatile ServerConnector delegate; private String host; @@ -63,7 +59,7 @@ public class MavenServerConnector extends ContainerLifeCycle implements Connecto public MavenServerConnector() { } - + public void setServer(Server server) { this.server = server; @@ -73,7 +69,7 @@ public class MavenServerConnector extends ContainerLifeCycle implements Connecto { this.host = host; } - + public String getHost() { return this.host; @@ -83,17 +79,17 @@ public class MavenServerConnector extends ContainerLifeCycle implements Connecto { this.port = port; } - - public int getPort () + + public int getPort() { return this.port; } - public void setName (String name) + public void setName(String name) { this.name = name; } - + public void setIdleTimeout(long idleTimeout) { this.idleTimeout = idleTimeout; @@ -129,7 +125,7 @@ public class MavenServerConnector extends ContainerLifeCycle implements Connecto { return checkDelegate().shutdown(); } - + @Override public boolean isShutdown() { @@ -148,7 +144,7 @@ public class MavenServerConnector extends ContainerLifeCycle implements Connecto return checkDelegate().getExecutor(); } - /** + /** * @see org.eclipse.jetty.server.Connector#getScheduler() */ @Override @@ -157,7 +153,7 @@ public class MavenServerConnector extends ContainerLifeCycle implements Connecto return checkDelegate().getScheduler(); } - /** + /** * @see org.eclipse.jetty.server.Connector#getByteBufferPool() */ @Override @@ -166,7 +162,7 @@ public class MavenServerConnector extends ContainerLifeCycle implements Connecto return checkDelegate().getByteBufferPool(); } - /** + /** * @see org.eclipse.jetty.server.Connector#getConnectionFactory(java.lang.String) */ @Override @@ -175,7 +171,7 @@ public class MavenServerConnector extends ContainerLifeCycle implements Connecto return checkDelegate().getConnectionFactory(nextProtocol); } - /** + /** * @see org.eclipse.jetty.server.Connector#getConnectionFactory(java.lang.Class) */ @Override @@ -184,7 +180,7 @@ public class MavenServerConnector extends ContainerLifeCycle implements Connecto return checkDelegate().getConnectionFactory(factoryType); } - /** + /** * @see org.eclipse.jetty.server.Connector#getDefaultConnectionFactory() */ @Override @@ -193,7 +189,7 @@ public class MavenServerConnector extends ContainerLifeCycle implements Connecto return checkDelegate().getDefaultConnectionFactory(); } - /** + /** * @see org.eclipse.jetty.server.Connector#getConnectionFactories() */ @Override @@ -202,7 +198,7 @@ public class MavenServerConnector extends ContainerLifeCycle implements Connecto return checkDelegate().getConnectionFactories(); } - /** + /** * @see org.eclipse.jetty.server.Connector#getProtocols() */ @Override @@ -211,7 +207,7 @@ public class MavenServerConnector extends ContainerLifeCycle implements Connecto return checkDelegate().getProtocols(); } - /** + /** * @see org.eclipse.jetty.server.Connector#getIdleTimeout() */ @Override @@ -221,7 +217,7 @@ public class MavenServerConnector extends ContainerLifeCycle implements Connecto return checkDelegate().getIdleTimeout(); } - /** + /** * @see org.eclipse.jetty.server.Connector#getTransport() */ @Override @@ -230,7 +226,7 @@ public class MavenServerConnector extends ContainerLifeCycle implements Connecto return checkDelegate().getTransport(); } - /** + /** * @see org.eclipse.jetty.server.Connector#getConnectedEndPoints() */ @Override @@ -239,7 +235,7 @@ public class MavenServerConnector extends ContainerLifeCycle implements Connecto return checkDelegate().getConnectedEndPoints(); } - /** + /** * @see org.eclipse.jetty.server.Connector#getName() */ @Override @@ -252,12 +248,12 @@ public class MavenServerConnector extends ContainerLifeCycle implements Connecto { return this.delegate.getLocalPort(); } - + private ServerConnector checkDelegate() throws IllegalStateException { ServerConnector d = this.delegate; if (d == null) - throw new IllegalStateException ("MavenServerConnector delegate not ready"); + throw new IllegalStateException("MavenServerConnector delegate not ready"); return d; } } diff --git a/jetty-maven-plugin/src/main/java/org/eclipse/jetty/maven/plugin/MavenWebInfConfiguration.java b/jetty-maven-plugin/src/main/java/org/eclipse/jetty/maven/plugin/MavenWebInfConfiguration.java index 2d8156d5f3f..d580e4842a6 100644 --- a/jetty-maven-plugin/src/main/java/org/eclipse/jetty/maven/plugin/MavenWebInfConfiguration.java +++ b/jetty-maven-plugin/src/main/java/org/eclipse/jetty/maven/plugin/MavenWebInfConfiguration.java @@ -19,34 +19,30 @@ package org.eclipse.jetty.maven.plugin; import java.io.File; -import java.util.ArrayList; -import java.util.List; + import org.eclipse.jetty.util.log.Log; import org.eclipse.jetty.util.log.Logger; -import org.eclipse.jetty.util.resource.Resource; import org.eclipse.jetty.webapp.Configuration; import org.eclipse.jetty.webapp.WebAppClassLoader; import org.eclipse.jetty.webapp.WebAppContext; import org.eclipse.jetty.webapp.WebInfConfiguration; - /** * MavenWebInfConfiguration - * + * * WebInfConfiguration to take account of overlaid wars expressed as project dependencies and * potential configured via the maven-war-plugin. */ public class MavenWebInfConfiguration extends WebInfConfiguration { private static final Logger LOG = Log.getLogger(MavenWebInfConfiguration.class); - public MavenWebInfConfiguration() { hide("org.apache.maven.", - "org.codehaus.plexus.", - "javax.enterprise.", - "javax.decorator."); + "org.codehaus.plexus.", + "javax.enterprise.", + "javax.decorator."); } @Override @@ -62,22 +58,19 @@ public class MavenWebInfConfiguration extends WebInfConfiguration public void configure(WebAppContext context) throws Exception { JettyWebAppContext jwac = (JettyWebAppContext)context; - + //put the classes dir and all dependencies into the classpath if (jwac.getClassPathFiles() != null && context.getClassLoader() instanceof WebAppClassLoader) { if (LOG.isDebugEnabled()) LOG.debug("Setting up classpath ..."); - WebAppClassLoader loader=(WebAppClassLoader)context.getClassLoader(); - for (File classpath:jwac.getClassPathFiles()) + WebAppClassLoader loader = (WebAppClassLoader)context.getClassLoader(); + for (File classpath : jwac.getClassPathFiles()) + { loader.addClassPath(classpath.getCanonicalPath()); + } } super.configure(context); } - - - - - } diff --git a/jetty-maven-plugin/src/main/java/org/eclipse/jetty/maven/plugin/Overlay.java b/jetty-maven-plugin/src/main/java/org/eclipse/jetty/maven/plugin/Overlay.java index 96dc527ff59..0378897af24 100644 --- a/jetty-maven-plugin/src/main/java/org/eclipse/jetty/maven/plugin/Overlay.java +++ b/jetty-maven-plugin/src/main/java/org/eclipse/jetty/maven/plugin/Overlay.java @@ -16,48 +16,44 @@ // ======================================================================== // - package org.eclipse.jetty.maven.plugin; import org.eclipse.jetty.util.resource.Resource; /** * Overlay - * - * */ public class Overlay { private OverlayConfig _config; private Resource _resource; - - public Overlay (OverlayConfig config, Resource resource) + + public Overlay(OverlayConfig config, Resource resource) { _config = config; _resource = resource; } - public Overlay (OverlayConfig config) + public Overlay(OverlayConfig config) { _config = config; } - - - public void setResource (Resource r) + + public void setResource(Resource r) { _resource = r; } - - public Resource getResource () + + public Resource getResource() { return _resource; } - - public OverlayConfig getConfig () + + public OverlayConfig getConfig() { return _config; } - + @Override public String toString() { diff --git a/jetty-maven-plugin/src/main/java/org/eclipse/jetty/maven/plugin/OverlayConfig.java b/jetty-maven-plugin/src/main/java/org/eclipse/jetty/maven/plugin/OverlayConfig.java index e288a1c19e8..364835925be 100644 --- a/jetty-maven-plugin/src/main/java/org/eclipse/jetty/maven/plugin/OverlayConfig.java +++ b/jetty-maven-plugin/src/main/java/org/eclipse/jetty/maven/plugin/OverlayConfig.java @@ -16,7 +16,6 @@ // ======================================================================== // - package org.eclipse.jetty.maven.plugin; import java.util.ArrayList; @@ -40,20 +39,22 @@ public class OverlayConfig private List excludes; private boolean skip; private boolean filtered; - - public OverlayConfig() {} - + + public OverlayConfig() + { + } + public OverlayConfig(String fmt, List defaultIncludes, List defaultExcludes) { if (fmt == null) return; String[] atoms = StringUtil.csvSplit(fmt); - for (int i=0;i defaultIncludes, List defaultExcludes) { Xpp3Dom node = root.getChild("groupId"); - setGroupId(node==null?null:node.getValue()); - + setGroupId(node == null ? null : node.getValue()); + node = root.getChild("artifactId"); - setArtifactId(node==null?null:node.getValue()); - + setArtifactId(node == null ? null : node.getValue()); + node = root.getChild("classifier"); - setClassifier(node==null?null:node.getValue()); - + setClassifier(node == null ? null : node.getValue()); + node = root.getChild("targetPath"); - setTargetPath(node==null?null:node.getValue()); - + setTargetPath(node == null ? null : node.getValue()); + node = root.getChild("skip"); - setSkip(node==null?false:Boolean.valueOf(node.getValue())); + setSkip(node == null ? false : Boolean.valueOf(node.getValue())); node = root.getChild("filtered"); - setFiltered(node==null?false:Boolean.valueOf(node.getValue())); + setFiltered(node == null ? false : Boolean.valueOf(node.getValue())); node = root.getChild("includes"); List includes = null; if (node != null && node.getChildCount() > 0) { Xpp3Dom[] list = node.getChildren("include"); - for (int j=0; list != null && j < list.length;j++) + for (int j = 0; list != null && j < list.length; j++) { if (includes == null) includes = new ArrayList<>(); @@ -153,14 +154,13 @@ public class OverlayConfig includes.addAll(defaultIncludes); } setIncludes(includes); - - + node = root.getChild("excludes"); List excludes = null; if (node != null && node.getChildCount() > 0) { Xpp3Dom[] list = node.getChildren("exclude"); - for (int j=0; list != null && j < list.length;j++) + for (int j = 0; list != null && j < list.length; j++) { if (excludes == null) excludes = new ArrayList<>(); @@ -174,7 +174,7 @@ public class OverlayConfig } setExcludes(excludes); } - + public String getTargetPath() { return targetPath; @@ -254,60 +254,59 @@ public class OverlayConfig { this.filtered = filtered; } - + public boolean isCurrentProject() { if (this.groupId == null && this.artifactId == null) return true; return false; } - /** * Check if this overlay configuration matches an Artifact's info - * + * * @param gid Artifact groupId * @param aid Artifact artifactId * @param cls Artifact classifier * @return true if matched */ - public boolean matchesArtifact (String gid, String aid, String cls) + public boolean matchesArtifact(String gid, String aid, String cls) { - if (((getGroupId() == null && gid == null) || (getGroupId() != null && getGroupId().equals(gid))) - &&((getArtifactId() == null && aid == null) || (getArtifactId() != null && getArtifactId().equals(aid))) - &&((getClassifier() == null) || (getClassifier().equals(cls)))) + if (((getGroupId() == null && gid == null) || (getGroupId() != null && getGroupId().equals(gid))) && + ((getArtifactId() == null && aid == null) || (getArtifactId() != null && getArtifactId().equals(aid))) && + ((getClassifier() == null) || (getClassifier().equals(cls)))) return true; return false; } - + /** * Check if this overlay configuration matches an Artifact's info - * + * * @param gid the group id * @param aid the artifact id * @return true if matched */ - public boolean matchesArtifact (String gid, String aid) + public boolean matchesArtifact(String gid, String aid) { - if (((getGroupId() == null && gid == null) || (getGroupId() != null && getGroupId().equals(gid))) - &&((getArtifactId() == null && aid == null) || (getArtifactId() != null && getArtifactId().equals(aid)))) + if (((getGroupId() == null && gid == null) || (getGroupId() != null && getGroupId().equals(gid))) && + ((getArtifactId() == null && aid == null) || (getArtifactId() != null && getArtifactId().equals(aid)))) return true; return false; } - + @Override public String toString() { StringBuilder strbuff = new StringBuilder(); - strbuff.append((groupId != null ? groupId : "")+","); - strbuff.append((artifactId != null ? artifactId : "")+","); - strbuff.append((classifier != null ? classifier : "")+","); - strbuff.append((targetPath != null ? targetPath : "")+","); - strbuff.append(""+skip+","); - strbuff.append(""+filtered+","); - + strbuff.append((groupId != null ? groupId : "") + ","); + strbuff.append((artifactId != null ? artifactId : "") + ","); + strbuff.append((classifier != null ? classifier : "") + ","); + strbuff.append((targetPath != null ? targetPath : "") + ","); + strbuff.append("" + skip + ","); + strbuff.append("" + filtered + ","); + if (includes != null) { Iterator itor = includes.iterator(); @@ -318,7 +317,7 @@ public class OverlayConfig strbuff.append(";"); } } - + strbuff.append(", "); if (excludes != null) @@ -331,7 +330,7 @@ public class OverlayConfig strbuff.append(";"); } } - + return strbuff.toString(); } } diff --git a/jetty-maven-plugin/src/main/java/org/eclipse/jetty/maven/plugin/PluginLog.java b/jetty-maven-plugin/src/main/java/org/eclipse/jetty/maven/plugin/PluginLog.java index ef3907b282a..0cd98fe0634 100644 --- a/jetty-maven-plugin/src/main/java/org/eclipse/jetty/maven/plugin/PluginLog.java +++ b/jetty-maven-plugin/src/main/java/org/eclipse/jetty/maven/plugin/PluginLog.java @@ -22,23 +22,21 @@ import org.apache.maven.plugin.logging.Log; /** * PluginLog - * + * * Convenience class to provide access to the plugin * Log for non-mojo classes. - * */ public class PluginLog { private static Log log = null; - + public static void setLog(Log l) { log = l; } - + public static Log getLog() { return log; } - } diff --git a/jetty-maven-plugin/src/main/java/org/eclipse/jetty/maven/plugin/ScanPattern.java b/jetty-maven-plugin/src/main/java/org/eclipse/jetty/maven/plugin/ScanPattern.java index 97e2a9142db..61fb6c166ac 100644 --- a/jetty-maven-plugin/src/main/java/org/eclipse/jetty/maven/plugin/ScanPattern.java +++ b/jetty-maven-plugin/src/main/java/org/eclipse/jetty/maven/plugin/ScanPattern.java @@ -30,22 +30,22 @@ public class ScanPattern { private List _includes = Collections.emptyList(); private List _excludes = Collections.emptyList(); - - public void setIncludes (List includes) + + public void setIncludes(List includes) { - _includes= includes; + _includes = includes; } - + public void setExcludes(List excludes) { _excludes = excludes; } - + public List getIncludes() { return _includes; } - + public List getExcludes() { return _excludes; diff --git a/jetty-maven-plugin/src/main/java/org/eclipse/jetty/maven/plugin/ScanTargetPattern.java b/jetty-maven-plugin/src/main/java/org/eclipse/jetty/maven/plugin/ScanTargetPattern.java index e1107b8b5c3..567a66113ba 100644 --- a/jetty-maven-plugin/src/main/java/org/eclipse/jetty/maven/plugin/ScanTargetPattern.java +++ b/jetty-maven-plugin/src/main/java/org/eclipse/jetty/maven/plugin/ScanTargetPattern.java @@ -25,22 +25,22 @@ import java.util.List; /** * ScanTargetPattern * - * Utility class to provide the ability for the mvn jetty:run - * mojo to be able to specify filesets of extra files to + * Utility class to provide the ability for the mvn jetty:run + * mojo to be able to specify filesets of extra files to * regularly scan for changes in order to redeploy the webapp. - * + * * For example: - * + * * <scanTargetPattern> - * <directory>/some/place</directory> - * <includes> - * <include>some ant pattern here </include> - * <include>some ant pattern here </include> - * </includes> - * <excludes> - * <exclude>some ant pattern here </exclude> - * <exclude>some ant pattern here </exclude> - * </excludes> + * <directory>/some/place</directory> + * <includes> + * <include>some ant pattern here </include> + * <include>some ant pattern here </include> + * </includes> + * <excludes> + * <exclude>some ant pattern here </exclude> + * <exclude>some ant pattern here </exclude> + * </excludes> * </scanTargetPattern> */ public class ScanTargetPattern @@ -63,29 +63,28 @@ public class ScanTargetPattern { this._directory = directory; } - - public void setIncludes (List includes) + + public void setIncludes(List includes) { if (_pattern == null) _pattern = new ScanPattern(); _pattern.setIncludes(includes); } - + public void setExcludes(List excludes) { if (_pattern == null) _pattern = new ScanPattern(); _pattern.setExcludes(excludes); } - + public List getIncludes() { - return (_pattern == null? Collections.emptyList() : _pattern.getIncludes()); - } - - public List getExcludes() - { - return (_pattern == null? Collections.emptyList() : _pattern.getExcludes()); + return (_pattern == null ? Collections.emptyList() : _pattern.getIncludes()); } + public List getExcludes() + { + return (_pattern == null ? Collections.emptyList() : _pattern.getExcludes()); + } } diff --git a/jetty-maven-plugin/src/main/java/org/eclipse/jetty/maven/plugin/SelectiveJarResource.java b/jetty-maven-plugin/src/main/java/org/eclipse/jetty/maven/plugin/SelectiveJarResource.java index 506758cad96..5b96ce16f8f 100644 --- a/jetty-maven-plugin/src/main/java/org/eclipse/jetty/maven/plugin/SelectiveJarResource.java +++ b/jetty-maven-plugin/src/main/java/org/eclipse/jetty/maven/plugin/SelectiveJarResource.java @@ -39,54 +39,51 @@ import org.eclipse.jetty.util.log.Log; import org.eclipse.jetty.util.log.Logger; import org.eclipse.jetty.util.resource.JarResource; - - /** * SelectiveJarResource * * Selectively copies resources from a jar file based on includes/excludes. - * */ public class SelectiveJarResource extends JarResource -{ +{ private static final Logger LOG = Log.getLogger(SelectiveJarResource.class); - public static final List DEFAULT_INCLUDES = Arrays.asList(new String[]{"**"});// No includes supplied, so set it to 'matches all' + public static final List DEFAULT_INCLUDES = Arrays.asList(new String[]{ + "**" + });// No includes supplied, so set it to 'matches all' public static final List DEFAULT_EXCLUDES = Collections.emptyList(); //No includes, set to no exclusions List _includes = null; List _excludes = null; boolean _caseSensitive = false; - + public SelectiveJarResource(URL url) { super(url); } - + public SelectiveJarResource(URL url, boolean useCaches) { super(url, useCaches); } - - public void setCaseSensitive (boolean caseSensitive) + + public void setCaseSensitive(boolean caseSensitive) { _caseSensitive = caseSensitive; } - - public void setIncludes (List patterns) + + public void setIncludes(List patterns) { _includes = patterns; } - - - public void setExcludes (List patterns) + + public void setExcludes(List patterns) { _excludes = patterns; } - - - protected boolean isIncluded (String name) - { - for (String include:_includes) + + protected boolean isIncluded(String name) + { + for (String include : _includes) { if (SelectorUtils.matchPath(include, name, _caseSensitive)) { @@ -95,23 +92,20 @@ public class SelectiveJarResource extends JarResource } return false; } - - protected boolean isExcluded (String name) + + protected boolean isExcluded(String name) { - for (String exclude:_excludes) + for (String exclude : _excludes) { - if (SelectorUtils.matchPath (exclude, name, _caseSensitive)) + if (SelectorUtils.matchPath(exclude, name, _caseSensitive)) { return true; } } return false; } - - - - /** + /** * @see org.eclipse.jetty.util.resource.JarResource#copyTo(java.io.File) */ @Override @@ -121,41 +115,41 @@ public class SelectiveJarResource extends JarResource _includes = DEFAULT_INCLUDES; if (_excludes == null) _excludes = DEFAULT_EXCLUDES; - + //Copy contents of the jar file to the given directory, //using the includes and excludes patterns to control which //parts of the jar file are copied if (!exists()) return; - + String urlString = this.getURI().toASCIIString().trim(); int endOfJarUrl = urlString.indexOf("!/"); - int startOfJarUrl = (endOfJarUrl >= 0?4:0); - + int startOfJarUrl = (endOfJarUrl >= 0 ? 4 : 0); + if (endOfJarUrl < 0) - throw new IOException("Not a valid jar url: "+urlString); - + throw new IOException("Not a valid jar url: " + urlString); + URL jarFileURL = new URL(urlString.substring(startOfJarUrl, endOfJarUrl)); - + try (InputStream is = jarFileURL.openConnection().getInputStream(); - JarInputStream jin = new JarInputStream(is)) + JarInputStream jin = new JarInputStream(is)) { JarEntry entry; - while((entry=jin.getNextJarEntry())!=null) + while ((entry = jin.getNextJarEntry()) != null) { String entryName = entry.getName(); - LOG.debug("Looking at "+entryName); + LOG.debug("Looking at " + entryName); String dotCheck = StringUtil.replace(entryName, '\\', '/'); dotCheck = URIUtil.canonicalPath(dotCheck); if (dotCheck == null) { - LOG.info("Invalid entry: "+entryName); + LOG.info("Invalid entry: " + entryName); continue; } - File file=new File(directory,entryName); + File file = new File(directory, entryName); if (entry.isDirectory()) { @@ -188,11 +182,11 @@ public class SelectiveJarResource extends JarResource // Make file try (OutputStream fout = new FileOutputStream(file)) { - IO.copy(jin,fout); + IO.copy(jin, fout); } // touch the file. - if (entry.getTime()>=0) + if (entry.getTime() >= 0) file.setLastModified(entry.getTime()); } else @@ -208,7 +202,7 @@ public class SelectiveJarResource extends JarResource { if (isIncluded("META-INF") && !isExcluded("META-INF")) { - File metaInf = new File (directory, "META-INF"); + File metaInf = new File(directory, "META-INF"); metaInf.mkdir(); File f = new File(metaInf, "MANIFEST.MF"); try (OutputStream fout = new FileOutputStream(f)) @@ -219,5 +213,4 @@ public class SelectiveJarResource extends JarResource } } } - } diff --git a/jetty-maven-plugin/src/main/java/org/eclipse/jetty/maven/plugin/ServerConnectorListener.java b/jetty-maven-plugin/src/main/java/org/eclipse/jetty/maven/plugin/ServerConnectorListener.java index df71c8b9494..48e913e3bb4 100644 --- a/jetty-maven-plugin/src/main/java/org/eclipse/jetty/maven/plugin/ServerConnectorListener.java +++ b/jetty-maven-plugin/src/main/java/org/eclipse/jetty/maven/plugin/ServerConnectorListener.java @@ -16,13 +16,8 @@ // ======================================================================== // - package org.eclipse.jetty.maven.plugin; -import org.eclipse.jetty.server.ServerConnector; -import org.eclipse.jetty.util.component.AbstractLifeCycle.AbstractLifeCycleListener; -import org.eclipse.jetty.util.component.LifeCycle; - import java.io.Writer; import java.nio.file.AtomicMoveNotSupportedException; import java.nio.file.Files; @@ -30,10 +25,14 @@ import java.nio.file.Path; import java.nio.file.Paths; import java.nio.file.StandardCopyOption; +import org.eclipse.jetty.server.ServerConnector; +import org.eclipse.jetty.util.component.AbstractLifeCycle.AbstractLifeCycleListener; +import org.eclipse.jetty.util.component.LifeCycle; + /** * ServerConnectorListener * - * This is for test support, where we need jetty to run on a random port, and we need + * This is for test support, where we need jetty to run on a random port, and we need * a client to be able to find out which port was picked. */ public class ServerConnectorListener extends AbstractLifeCycleListener @@ -42,9 +41,7 @@ public class ServerConnectorListener extends AbstractLifeCycleListener private String _fileName; private String _sysPropertyName; - - - /** + /** * @see org.eclipse.jetty.util.component.AbstractLifeCycle.AbstractLifeCycleListener#lifeCycleStarted(org.eclipse.jetty.util.component.LifeCycle) */ @Override @@ -54,32 +51,32 @@ public class ServerConnectorListener extends AbstractLifeCycleListener { try { - Path tmp = Files.createTempFile( "jettyport", ".tmp" ); - try (Writer writer = Files.newBufferedWriter( tmp )) + Path tmp = Files.createTempFile("jettyport", ".tmp"); + try (Writer writer = Files.newBufferedWriter(tmp)) { - writer.write( String.valueOf( ( (ServerConnector) event ).getLocalPort() ) ); + writer.write(String.valueOf(((ServerConnector)event).getLocalPort())); } Path path = Paths.get(getFileName()); Files.deleteIfExists(path); try { - Files.move( tmp, path, StandardCopyOption.ATOMIC_MOVE ); + Files.move(tmp, path, StandardCopyOption.ATOMIC_MOVE); } - catch ( AtomicMoveNotSupportedException e ) // can append on some os (windows).. so try again without the option + catch (AtomicMoveNotSupportedException e) // can append on some os (windows).. so try again without the option { - Files.move( tmp, path); + Files.move(tmp, path); } } catch (Exception e) { - throw new RuntimeException (e); + throw new RuntimeException(e); } } - + if (getSysPropertyName() != null) { - System.setProperty(_sysPropertyName,String.valueOf(((ServerConnector)event).getLocalPort())); + System.setProperty(_sysPropertyName, String.valueOf(((ServerConnector)event).getLocalPort())); } super.lifeCycleStarted(event); } @@ -116,6 +113,4 @@ public class ServerConnectorListener extends AbstractLifeCycleListener { _sysPropertyName = sysPropertyName; } - - } diff --git a/jetty-maven-plugin/src/main/java/org/eclipse/jetty/maven/plugin/ServerListener.java b/jetty-maven-plugin/src/main/java/org/eclipse/jetty/maven/plugin/ServerListener.java index f9c337ea858..0037e4f6cdf 100644 --- a/jetty-maven-plugin/src/main/java/org/eclipse/jetty/maven/plugin/ServerListener.java +++ b/jetty-maven-plugin/src/main/java/org/eclipse/jetty/maven/plugin/ServerListener.java @@ -16,7 +16,6 @@ // ======================================================================== // - package org.eclipse.jetty.maven.plugin; import org.eclipse.jetty.util.component.LifeCycle; @@ -31,29 +30,29 @@ import org.eclipse.jetty.util.resource.Resource; */ public class ServerListener implements LifeCycle.Listener { - + private String _tokenFile; - + public void setTokenFile(String file) { - _tokenFile = file; + _tokenFile = file; } - - public String getTokenFile () + public String getTokenFile() { return _tokenFile; } - /** + + /** * @see org.eclipse.jetty.util.component.LifeCycle.Listener#lifeCycleStarting(org.eclipse.jetty.util.component.LifeCycle) */ @Override public void lifeCycleStarting(LifeCycle event) { - + } - /** + /** * @see org.eclipse.jetty.util.component.LifeCycle.Listener#lifeCycleStarted(org.eclipse.jetty.util.component.LifeCycle) */ @Override @@ -71,35 +70,32 @@ public class ServerListener implements LifeCycle.Listener throw new IllegalStateException(e); } } - } - /** + /** * @see org.eclipse.jetty.util.component.LifeCycle.Listener#lifeCycleFailure(org.eclipse.jetty.util.component.LifeCycle, java.lang.Throwable) */ @Override public void lifeCycleFailure(LifeCycle event, Throwable cause) { - + } - /** + /** * @see org.eclipse.jetty.util.component.LifeCycle.Listener#lifeCycleStopping(org.eclipse.jetty.util.component.LifeCycle) */ @Override public void lifeCycleStopping(LifeCycle event) { - + } - /** + /** * @see org.eclipse.jetty.util.component.LifeCycle.Listener#lifeCycleStopped(org.eclipse.jetty.util.component.LifeCycle) */ @Override public void lifeCycleStopped(LifeCycle event) { - + } - - } diff --git a/jetty-maven-plugin/src/main/java/org/eclipse/jetty/maven/plugin/ServerSupport.java b/jetty-maven-plugin/src/main/java/org/eclipse/jetty/maven/plugin/ServerSupport.java index 338427e3e90..48447c19303 100644 --- a/jetty-maven-plugin/src/main/java/org/eclipse/jetty/maven/plugin/ServerSupport.java +++ b/jetty-maven-plugin/src/main/java/org/eclipse/jetty/maven/plugin/ServerSupport.java @@ -16,7 +16,6 @@ // ======================================================================== // - package org.eclipse.jetty.maven.plugin; import java.io.File; @@ -42,30 +41,29 @@ import org.eclipse.jetty.xml.XmlConfiguration; * ServerSupport * * Helps configure the Server instance. - * */ public class ServerSupport { - - public static void configureDefaultConfigurationClasses (Server server) + + public static void configureDefaultConfigurationClasses(Server server) { Configurations.setServerDefault(server); } - - + /** * Set up the handler structure to receive a webapp. * Also put in a DefaultHandler so we get a nice page * than a 404 if we hit the root and the webapp's * context isn't at root. + * * @param server the server * @param requestLog the request log * @throws Exception if unable to configure the handlers */ - public static void configureHandlers (Server server, RequestLog requestLog) throws Exception + public static void configureHandlers(Server server, RequestLog requestLog) throws Exception { if (server == null) - throw new IllegalArgumentException ("Server is null"); + throw new IllegalArgumentException("Server is null"); DefaultHandler defaultHandler = new DefaultHandler(); if (requestLog != null) @@ -73,91 +71,86 @@ public class ServerSupport ContextHandlerCollection contexts = findContextHandlerCollection(server); if (contexts == null) - { + { contexts = new ContextHandlerCollection(); HandlerCollection handlers = (HandlerCollection)server.getChildHandlerByClass(HandlerCollection.class); if (handlers == null) { - handlers = new HandlerCollection(); - server.setHandler(handlers); + handlers = new HandlerCollection(); + server.setHandler(handlers); handlers.setHandlers(new Handler[]{contexts, defaultHandler}); } else { handlers.addHandler(contexts); } - } + } } - /** * Configure at least one connector for the server - * + * * @param server the server * @param connector the connector */ - public static void configureConnectors (Server server, Connector connector) + public static void configureConnectors(Server server, Connector connector) { if (server == null) throw new IllegalArgumentException("Server is null"); - + //if a connector is provided, use it if (connector != null) { server.addConnector(connector); return; } - - // if the user hasn't configured the connectors in a jetty.xml file so use a default one Connector[] connectors = server.getConnectors(); if (connectors == null || connectors.length == 0) { //Make a new default connector - MavenServerConnector tmp = new MavenServerConnector(); + MavenServerConnector tmp = new MavenServerConnector(); //use any jetty.http.port settings provided String port = System.getProperty(MavenServerConnector.PORT_SYSPROPERTY, System.getProperty("jetty.port", MavenServerConnector.DEFAULT_PORT_STR)); tmp.setPort(Integer.parseInt(port.trim())); tmp.setServer(server); - server.setConnectors(new Connector[] {tmp}); + server.setConnectors(new Connector[]{tmp}); } } - - + /** * Set up any security LoginServices provided. - * + * * @param server the server * @param loginServices the login services */ - public static void configureLoginServices (Server server, LoginService[] loginServices) + public static void configureLoginServices(Server server, LoginService[] loginServices) { if (server == null) - throw new IllegalArgumentException ("Server is null"); + throw new IllegalArgumentException("Server is null"); if (loginServices != null) { - for (LoginService loginService:loginServices) + for (LoginService loginService : loginServices) { - PluginLog.getLog().debug(loginService.getClass().getName() + ": "+ loginService.toString()); + PluginLog.getLog().debug(loginService.getClass().getName() + ": " + loginService.toString()); server.addBean(loginService); } } } - - public static void addWebApplication(Server server, WebAppContext webapp) throws Exception - { - if (server == null) - throw new IllegalArgumentException ("Server is null"); - ContextHandlerCollection contexts = findContextHandlerCollection(server); - if (contexts == null) - throw new IllegalStateException("ContextHandlerCollection is null"); - contexts.addHandler (webapp); - } - - public static ContextHandlerCollection findContextHandlerCollection (Server server) + public static void addWebApplication(Server server, WebAppContext webapp) throws Exception + { + if (server == null) + throw new IllegalArgumentException("Server is null"); + ContextHandlerCollection contexts = findContextHandlerCollection(server); + if (contexts == null) + throw new IllegalStateException("ContextHandlerCollection is null"); + contexts.addHandler(webapp); + } + + public static ContextHandlerCollection findContextHandlerCollection(Server server) { if (server == null) return null; @@ -165,40 +158,37 @@ public class ServerSupport return server.getChildHandlerByClass(ContextHandlerCollection.class); } - /** * Apply xml files to server instance. - * + * * @param server the server to apply the xml to * @param files the list of xml files * @param properties list of jetty properties * @return the Server implementation, after the xml is applied * @throws Exception if unable to apply the xml configuration */ - public static Server applyXmlConfigurations (Server server, List files, Map properties) - throws Exception + public static Server applyXmlConfigurations(Server server, List files, Map properties) + throws Exception { if (files == null || files.isEmpty()) return server; - Map lastMap = new HashMap<>(); + Map lastMap = new HashMap<>(); if (server != null) lastMap.put("Server", server); - - for ( File xmlFile : files ) + for (File xmlFile : files) { if (PluginLog.getLog() != null) - PluginLog.getLog().info( "Configuring Jetty from xml configuration file = " + xmlFile.getCanonicalPath() ); - + PluginLog.getLog().info("Configuring Jetty from xml configuration file = " + xmlFile.getCanonicalPath()); XmlConfiguration xmlConfiguration = new XmlConfiguration(new PathResource(xmlFile)); - + //add in any properties if (properties != null) { - for (Map.Entry e:properties.entrySet()) + for (Map.Entry e : properties.entrySet()) { xmlConfiguration.getProperties().put(e.getKey(), e.getValue()); } @@ -206,35 +196,33 @@ public class ServerSupport //chain ids from one config file to another if (lastMap != null) - xmlConfiguration.getIdMap().putAll(lastMap); + xmlConfiguration.getIdMap().putAll(lastMap); //Set the system properties each time in case the config file set a new one Enumeration ensysprop = System.getProperties().propertyNames(); while (ensysprop.hasMoreElements()) { String name = (String)ensysprop.nextElement(); - xmlConfiguration.getProperties().put(name,System.getProperty(name)); + xmlConfiguration.getProperties().put(name, System.getProperty(name)); } - xmlConfiguration.configure(); + xmlConfiguration.configure(); lastMap = xmlConfiguration.getIdMap(); } - + return (Server)lastMap.get("Server"); } /** * Apply xml files to server instance. - * + * * @param server the Server instance to configure * @param files the xml configs to apply * @return the Server after application of configs - * * @throws Exception if unable to apply the xml configuration */ - public static Server applyXmlConfigurations (Server server, List files) - throws Exception + public static Server applyXmlConfigurations(Server server, List files) + throws Exception { return applyXmlConfigurations(server, files, null); } - } diff --git a/jetty-maven-plugin/src/main/java/org/eclipse/jetty/maven/plugin/Starter.java b/jetty-maven-plugin/src/main/java/org/eclipse/jetty/maven/plugin/Starter.java index be9f1f9ebf4..7d76d8124a5 100644 --- a/jetty-maven-plugin/src/main/java/org/eclipse/jetty/maven/plugin/Starter.java +++ b/jetty-maven-plugin/src/main/java/org/eclipse/jetty/maven/plugin/Starter.java @@ -33,61 +33,56 @@ import org.eclipse.jetty.util.log.Log; import org.eclipse.jetty.util.log.Logger; import org.eclipse.jetty.util.resource.Resource; - - /** * Starter Class which is exec'ed to create a new jetty process. Used by the JettyRunForked mojo. */ public class Starter -{ +{ private static final Logger LOG = Log.getLogger(Starter.class); private List jettyXmls; // list of jetty.xml config files to apply private Server server; private JettyWebAppContext webApp; - private Map jettyProperties; //optional list of jetty properties to set - - private int stopPort=0; - private String stopKey=null; + private Map jettyProperties; //optional list of jetty properties to set + + private int stopPort = 0; + private String stopKey = null; private File propsFile; private String token; - - - - public void configureJetty () throws Exception + public void configureJetty() throws Exception { LOG.debug("Starting Jetty Server ..."); Resource.setDefaultUseCaches(false); - + //apply any configs from jetty.xml files first - applyJettyXml (); + applyJettyXml(); //ensure there's a connector ServerSupport.configureConnectors(server, null); //check if contexts already configured, create if not ServerSupport.configureHandlers(server, null); - + //Set up list of default Configurations to apply to a webapp ServerSupport.configureDefaultConfigurationClasses(server); - + webApp = new JettyWebAppContext(); - + //configure webapp from properties file describing unassembled webapp configureWebApp(); - + //make it a quickstart if the quickstart-web.xml file exists if (webApp.getTempDirectory() != null) { - File qs = new File (webApp.getTempDirectory(), "quickstart-web.xml"); + File qs = new File(webApp.getTempDirectory(), "quickstart-web.xml"); if (qs.exists() && qs.isFile()) webApp.setQuickStartWebDescriptor(Resource.newResource(qs)); } - + ServerSupport.addWebApplication(server, webApp); - if(stopPort>0 && stopKey!=null) + if (stopPort > 0 && stopKey != null) { ShutdownMonitor monitor = ShutdownMonitor.getInstance(); monitor.setPort(stopPort); @@ -96,20 +91,20 @@ public class Starter } } - public void configureWebApp () - throws Exception + public void configureWebApp() + throws Exception { if (propsFile == null) return; //apply a properties file that defines the things that we configure in the jetty:run plugin - WebAppPropertyConverter.fromProperties(webApp, propsFile, server, jettyProperties); + WebAppPropertyConverter.fromProperties(webApp, propsFile, server, jettyProperties); } - public void getConfiguration (String[] args) - throws Exception + public void getConfiguration(String[] args) + throws Exception { - for (int i=0; i(); String[] names = StringUtil.csvSplit(args[++i]); - for (int j=0; names!= null && j < names.length; j++) + for (int j = 0; names != null && j < names.length; j++) { jettyXmls.add(new File(names[j].trim())); } @@ -143,14 +138,13 @@ public class Starter propsFile = new File(args[++i].trim()); continue; } - + //--token if ("--token".equals(args[i])) { token = args[++i].trim(); continue; } - //assume everything else is a jetty property to be passed in if (jettyProperties == null) @@ -162,21 +156,18 @@ public class Starter } } - public void run() throws Exception { LOG.info("Started Jetty Server"); - server.start(); + server.start(); } - - public void join () throws Exception + public void join() throws Exception { server.join(); } - - public void communicateStartupResult () + public void communicateStartupResult() { if (token != null) { @@ -187,14 +178,14 @@ public class Starter } catch (Exception x) { - throw new IllegalStateException (x); + throw new IllegalStateException(x); } } } - - + /** * Apply any jetty xml files given + * * @throws Exception if unable to apply the xml */ public void applyJettyXml() throws Exception @@ -202,15 +193,12 @@ public class Starter Server tmp = ServerSupport.applyXmlConfigurations(server, jettyXmls, jettyProperties); if (server == null) server = tmp; - + if (server == null) server = new Server(); } - - - - protected void prependHandler (Handler handler, HandlerCollection handlers) + protected void prependHandler(Handler handler, HandlerCollection handlers) { if (handler == null || handlers == null) return; @@ -223,45 +211,43 @@ public class Starter } /** - * @param csv - * @return + * */ - private List fromCSV (String csv) + private List fromCSV(String csv) { if (csv == null || "".equals(csv.trim())) return null; String[] atoms = StringUtil.csvSplit(csv); List list = new ArrayList(); - for (String a:atoms) + for (String a : atoms) { list.add(a.trim()); } return list; } - + /** * @param args Starter arguments */ public static final void main(String[] args) { if (args == null) - System.exit(1); - - Starter starter = null; - try - { - starter = new Starter(); - starter.getConfiguration(args); - starter.configureJetty(); - starter.run(); - starter.communicateStartupResult(); - starter.join(); - } - catch (Exception e) - { - e.printStackTrace(); - System.exit(1); - } + System.exit(1); + Starter starter = null; + try + { + starter = new Starter(); + starter.getConfiguration(args); + starter.configureJetty(); + starter.run(); + starter.communicateStartupResult(); + starter.join(); + } + catch (Exception e) + { + e.printStackTrace(); + System.exit(1); + } } } diff --git a/jetty-maven-plugin/src/main/java/org/eclipse/jetty/maven/plugin/SystemProperties.java b/jetty-maven-plugin/src/main/java/org/eclipse/jetty/maven/plugin/SystemProperties.java index d6a114c6561..ada9c59824b 100644 --- a/jetty-maven-plugin/src/main/java/org/eclipse/jetty/maven/plugin/SystemProperties.java +++ b/jetty-maven-plugin/src/main/java/org/eclipse/jetty/maven/plugin/SystemProperties.java @@ -27,7 +27,7 @@ import java.util.Map; * SystemProperties * * Map of name to SystemProperty. - * + * * When a SystemProperty instance is added, if it has not * been already set (eg via the command line java system property) * then it will be set. @@ -36,24 +36,23 @@ public class SystemProperties { private final Map properties; private boolean force; - + public SystemProperties() { properties = new HashMap<>(); } - - public void setForce (boolean force) + + public void setForce(boolean force) { this.force = force; } - - public boolean getForce () + + public boolean getForce() { return this.force; } - - - public void setSystemProperty (SystemProperty prop) + + public void setSystemProperty(SystemProperty prop) { properties.put(prop.getName(), prop); if (!force) @@ -61,18 +60,18 @@ public class SystemProperties else prop.setAnyway(); } - + public SystemProperty getSystemProperty(String name) { return properties.get(name); } - + public boolean containsSystemProperty(String name) { - return properties.containsKey(name); + return properties.containsKey(name); } - - public List getSystemProperties () + + public List getSystemProperties() { return new ArrayList<>(properties.values()); } diff --git a/jetty-maven-plugin/src/main/java/org/eclipse/jetty/maven/plugin/SystemProperty.java b/jetty-maven-plugin/src/main/java/org/eclipse/jetty/maven/plugin/SystemProperty.java index 72d80248d78..73e83a67af6 100644 --- a/jetty-maven-plugin/src/main/java/org/eclipse/jetty/maven/plugin/SystemProperty.java +++ b/jetty-maven-plugin/src/main/java/org/eclipse/jetty/maven/plugin/SystemProperty.java @@ -20,23 +20,21 @@ package org.eclipse.jetty.maven.plugin; /** * SystemProperty - * + * * Provides the ability to set System properties - * for the mojo execution. A value will only + * for the mojo execution. A value will only * be set if it is not set already. That is, if * it was set on the command line or by the system, - * it won't be overridden by settings in the + * it won't be overridden by settings in the * plugin's configuration. - * */ public class SystemProperty { - private String name; private String value; private boolean isSet; - + /** * @return Returns the name. */ @@ -44,6 +42,7 @@ public class SystemProperty { return this.name; } + /** * @param name The name to set. */ @@ -57,10 +56,11 @@ public class SystemProperty return this.name; } - public void setKey (String name) + public void setKey(String name) { this.name = name; } + /** * @return Returns the value. */ @@ -68,6 +68,7 @@ public class SystemProperty { return this.value; } + /** * @param value The value to set. */ @@ -76,28 +77,27 @@ public class SystemProperty this.value = value; } - - public boolean isSet () + public boolean isSet() { return isSet; } - - /** Set a System.property with this value + + /** + * Set a System.property with this value * if it is not already set. */ void setIfNotSetAlready() { if (System.getProperty(getName()) == null) { - System.setProperty(getName(), (getValue()==null?"":getValue())); - isSet=true; + System.setProperty(getName(), (getValue() == null ? "" : getValue())); + isSet = true; } } - + void setAnyway() { - System.setProperty(getName(), (getValue()==null?"":getValue())); - isSet=true; + System.setProperty(getName(), (getValue() == null ? "" : getValue())); + isSet = true; } - } diff --git a/jetty-maven-plugin/src/main/java/org/eclipse/jetty/maven/plugin/WarPluginInfo.java b/jetty-maven-plugin/src/main/java/org/eclipse/jetty/maven/plugin/WarPluginInfo.java index b61d7903998..24026f87692 100644 --- a/jetty-maven-plugin/src/main/java/org/eclipse/jetty/maven/plugin/WarPluginInfo.java +++ b/jetty-maven-plugin/src/main/java/org/eclipse/jetty/maven/plugin/WarPluginInfo.java @@ -16,7 +16,6 @@ // ======================================================================== // - package org.eclipse.jetty.maven.plugin; import java.util.ArrayList; @@ -41,18 +40,15 @@ public class WarPluginInfo private List _dependentMavenWarIncludes; private List _dependentMavenWarExcludes; private List _overlayConfigs; - - - public WarPluginInfo (MavenProject project) + + public WarPluginInfo(MavenProject project) { _project = project; } - - - /** * Find the maven-war-plugin, if one is configured + * * @return the plugin */ public Plugin getPlugin() @@ -63,9 +59,8 @@ public class WarPluginInfo if (plugins == null) return null; - Iterator itor = plugins.iterator(); - while (itor.hasNext() && _plugin==null) + while (itor.hasNext() && _plugin == null) { Plugin plugin = (Plugin)itor.next(); if ("maven-war-plugin".equals(plugin.getArtifactId())) @@ -75,11 +70,9 @@ public class WarPluginInfo return _plugin; } - - - /** * Get value of dependentWarIncludes for maven-war-plugin + * * @return the list of dependent war includes */ public List getDependentMavenWarIncludes() @@ -99,16 +92,14 @@ public class WarPluginInfo if (node == null) return null; String val = node.getValue(); - _dependentMavenWarIncludes = StringUtil.csvSplit(null,val,0,val.length()); + _dependentMavenWarIncludes = StringUtil.csvSplit(null, val, 0, val.length()); } return _dependentMavenWarIncludes; } - - - /** * Get value of dependentWarExcludes for maven-war-plugin + * * @return the list of dependent war excludes */ public List getDependentMavenWarExcludes() @@ -128,20 +119,17 @@ public class WarPluginInfo if (node == null) return null; String val = node.getValue(); - _dependentMavenWarExcludes = StringUtil.csvSplit(null,val,0,val.length()); + _dependentMavenWarExcludes = StringUtil.csvSplit(null, val, 0, val.length()); } return _dependentMavenWarExcludes; } - - - /** * Get config for any overlays that have been declared for the maven-war-plugin. - * + * * @return the list of overlay configs */ - public List getMavenWarOverlayConfigs () + public List getMavenWarOverlayConfigs() { if (_overlayConfigs == null) { @@ -166,7 +154,7 @@ public class WarPluginInfo return Collections.emptyList(); _overlayConfigs = new ArrayList(); - for (int i=0;i deps = webApp.getWebInfLib(); StringBuilder strbuff = new StringBuilder(); if (deps != null) { - for (int i=0; i jettyProperties) - throws Exception + public static void fromProperties(JettyWebAppContext webApp, String resource, Server server, Map jettyProperties) + throws Exception { if (resource == null) throw new IllegalStateException("No resource"); - + fromProperties(webApp, Resource.newResource(resource).getFile(), server, jettyProperties); } - - + /** * Configure a webapp from a properties file + * * @param webApp the webapp to configure * @param propsFile the properties to apply * @param server the Server instance to use if there is a context xml file to apply * @param jettyProperties jetty properties to use if there is a context xml file to apply * @throws Exception if any I/O exception occurs */ - public static void fromProperties (JettyWebAppContext webApp, File propsFile, Server server, Map jettyProperties) - throws Exception + public static void fromProperties(JettyWebAppContext webApp, File propsFile, Server server, Map jettyProperties) + throws Exception { if (webApp == null) throw new IllegalArgumentException("No webapp"); if (propsFile == null) throw new IllegalArgumentException("No properties file"); - + if (!propsFile.exists()) - throw new IllegalArgumentException (propsFile.getCanonicalPath()+" does not exist"); - + throw new IllegalArgumentException(propsFile.getCanonicalPath() + " does not exist"); + Properties props = new Properties(); try (InputStream in = Files.newInputStream(propsFile.toPath())) { props.load(in); } - String str = props.getProperty("context.path"); if (!StringUtil.isBlank(str)) webApp.setContextPath(str); - // - web.xml str = props.getProperty("web.xml"); if (!StringUtil.isBlank(str)) - webApp.setDescriptor(str); + webApp.setDescriptor(str); //TODO the WebAppStarter class doesn't set up the QUICKSTART_CONFIGURATION_CLASSES, but the Starter class does!!! str = props.getProperty("quickstart.web.xml"); @@ -199,13 +192,13 @@ public class WebAppPropertyConverter // - the tmp directory str = props.getProperty("tmp.dir"); - if (!StringUtil.isBlank(str)) + if (!StringUtil.isBlank(str)) webApp.setTempDirectory(new File(str.trim())); str = props.getProperty("tmp.dir.persist"); if (!StringUtil.isBlank(str)) webApp.setPersistTempDirectory(Boolean.valueOf(str)); - + //Get the calculated base dirs which includes the overlays str = props.getProperty("base.dirs"); if (!StringUtil.isBlank(str)) @@ -213,7 +206,7 @@ public class WebAppPropertyConverter ResourceCollection bases = new ResourceCollection(StringUtil.csvSplit(str)); webApp.setWar(null); webApp.setBaseResource(bases); - } + } // - the equivalent of web-inf classes str = props.getProperty("classes.dir"); @@ -221,7 +214,7 @@ public class WebAppPropertyConverter { webApp.setClasses(new File(str)); } - + str = props.getProperty("testClasses.dir"); if (!StringUtil.isBlank(str)) { @@ -234,12 +227,13 @@ public class WebAppPropertyConverter { List jars = new ArrayList(); String[] names = StringUtil.csvSplit(str); - for (int j=0; names != null && j < names.length; j++) + for (int j = 0; names != null && j < names.length; j++) + { jars.add(new File(names[j].trim())); + } webApp.setWebInfLib(jars); } - - + //set up the webapp from the context xml file provided //NOTE: just like jetty:run mojo this means that the context file can //potentially override settings made in the pom. Ideally, we'd like @@ -250,11 +244,11 @@ public class WebAppPropertyConverter if (!StringUtil.isBlank(str)) { XmlConfiguration xmlConfiguration = new XmlConfiguration(Resource.newResource(str)); - xmlConfiguration.getIdMap().put("Server",server); + xmlConfiguration.getIdMap().put("Server", server); //add in any properties if (jettyProperties != null) { - for (Map.Entry prop:jettyProperties.entrySet()) + for (Map.Entry prop : jettyProperties.entrySet()) { xmlConfiguration.getProperties().put(prop.getKey(), prop.getValue()); } @@ -263,23 +257,22 @@ public class WebAppPropertyConverter } } - /** * Convert an array of Resources to csv file names - * + * * @param resources the resources to convert - * * @return csv string of resource filenames */ - private static String toCSV (Resource[] resources) + private static String toCSV(Resource[] resources) { StringBuilder rb = new StringBuilder(); - for (Resource r:resources) + for (Resource r : resources) { - if (rb.length() > 0) rb.append(","); + if (rb.length() > 0) + rb.append(","); rb.append(r.toString()); - } + } return rb.toString(); } diff --git a/jetty-maven-plugin/src/main/java/org/eclipse/jetty/maven/plugin/utils/MavenProjectHelper.java b/jetty-maven-plugin/src/main/java/org/eclipse/jetty/maven/plugin/utils/MavenProjectHelper.java index cdae1dc7a01..b705500278d 100644 --- a/jetty-maven-plugin/src/main/java/org/eclipse/jetty/maven/plugin/utils/MavenProjectHelper.java +++ b/jetty-maven-plugin/src/main/java/org/eclipse/jetty/maven/plugin/utils/MavenProjectHelper.java @@ -39,12 +39,13 @@ public class MavenProjectHelper { Set mavenProjects = resolveProjectDependencies(project, new HashSet<>()); artifactToLocalProjectMap = mavenProjects.stream() - .collect(Collectors.toMap(MavenProject::getId, Function.identity())); + .collect(Collectors.toMap(MavenProject::getId, Function.identity())); artifactToLocalProjectMap.put(project.getArtifact().getId(), project); } /** * Gets maven project if referenced in reactor + * * @param artifact - maven artifact * @return {@link MavenProject} if artifact is referenced in reactor, otherwise null */ @@ -69,9 +70,12 @@ public class MavenProjectHelper MavenProject mavenProject = getMavenProject(artifact); if (mavenProject != null) { - if ( "test-jar".equals( artifact.getType() )) { + if ("test-jar".equals(artifact.getType())) + { path = Paths.get(mavenProject.getBuild().getTestOutputDirectory()); - } else { + } + else + { path = Paths.get(mavenProject.getBuild().getOutputDirectory()); } } @@ -92,5 +96,4 @@ public class MavenProjectHelper } return availableProjects; } - } diff --git a/jetty-maven-plugin/src/test/java/org/eclipse/jetty/maven/plugin/it/TestGetContent.java b/jetty-maven-plugin/src/test/java/org/eclipse/jetty/maven/plugin/it/TestGetContent.java index 6fffe96d0cc..2a09f98bc73 100644 --- a/jetty-maven-plugin/src/test/java/org/eclipse/jetty/maven/plugin/it/TestGetContent.java +++ b/jetty-maven-plugin/src/test/java/org/eclipse/jetty/maven/plugin/it/TestGetContent.java @@ -18,10 +18,6 @@ package org.eclipse.jetty.maven.plugin.it; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertNotNull; -import static org.junit.jupiter.api.Assertions.assertTrue; - import java.io.LineNumberReader; import java.io.Reader; import java.nio.file.Files; @@ -32,6 +28,10 @@ import org.apache.commons.lang3.StringUtils; import org.eclipse.jetty.client.HttpClient; import org.junit.jupiter.api.Test; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertTrue; + /** * */ @@ -42,48 +42,48 @@ public class TestGetContent throws Exception { int port = getPort(); - assertTrue( port > 0 ); + assertTrue(port > 0); HttpClient httpClient = new HttpClient(); try { httpClient.start(); - if (Boolean.getBoolean( "helloServlet" )) + if (Boolean.getBoolean("helloServlet")) { - String response = httpClient.GET( "http://localhost:" + port + "/hello?name=beer" ).getContentAsString(); - assertEquals( "Hello beer", response.trim(), "it test " + System.getProperty( "maven.it.name" ) ); - response = httpClient.GET( "http://localhost:" + port + "/hello?name=foo" ).getContentAsString(); - assertEquals( "Hello foo", response.trim(), "it test " + System.getProperty( "maven.it.name" ) ); - System.out.println( "helloServlet" ); + String response = httpClient.GET("http://localhost:" + port + "/hello?name=beer").getContentAsString(); + assertEquals("Hello beer", response.trim(), "it test " + System.getProperty("maven.it.name")); + response = httpClient.GET("http://localhost:" + port + "/hello?name=foo").getContentAsString(); + assertEquals("Hello foo", response.trim(), "it test " + System.getProperty("maven.it.name")); + System.out.println("helloServlet"); } - if (Boolean.getBoolean( "pingServlet" )) + if (Boolean.getBoolean("pingServlet")) { - System.out.println( "pingServlet" ); - String response = httpClient.GET( "http://localhost:" + port + "/ping?name=beer" ).getContentAsString(); - assertEquals( "pong beer", response.trim(), "it test " + System.getProperty( "maven.it.name" ) ); - System.out.println( "pingServlet ok" ); + System.out.println("pingServlet"); + String response = httpClient.GET("http://localhost:" + port + "/ping?name=beer").getContentAsString(); + assertEquals("pong beer", response.trim(), "it test " + System.getProperty("maven.it.name")); + System.out.println("pingServlet ok"); } - String contentCheck = System.getProperty( "contentCheck" ); - String pathToCheck = System.getProperty( "pathToCheck" ); - if(StringUtils.isNotBlank( contentCheck ) ) + String contentCheck = System.getProperty("contentCheck"); + String pathToCheck = System.getProperty("pathToCheck"); + if (StringUtils.isNotBlank(contentCheck)) { String url = "http://localhost:" + port; - if(pathToCheck!=null) + if (pathToCheck != null) { url += pathToCheck; } - String response = httpClient.GET( url ).getContentAsString(); - assertTrue(response.contains(contentCheck), "it test " + System.getProperty( "maven.it.name" ) + String response = httpClient.GET(url).getContentAsString(); + assertTrue(response.contains(contentCheck), "it test " + System.getProperty("maven.it.name") + ", response not contentCheck: " + contentCheck + ", response:" + response); - System.out.println( "contentCheck" ); + System.out.println("contentCheck"); } - if (Boolean.getBoolean( "helloTestServlet" )) + if (Boolean.getBoolean("helloTestServlet")) { - String response = httpClient.GET( "http://localhost:" + port + "/testhello?name=beer" ).getContentAsString(); - assertEquals( "Hello from test beer", response.trim(), "it test " + System.getProperty( "maven.it.name" ) ); - response = httpClient.GET( "http://localhost:" + port + "/testhello?name=foo" ).getContentAsString(); - assertEquals( "Hello from test foo", response.trim(), "it test " + System.getProperty( "maven.it.name" ) ); - System.out.println( "helloServlet" ); + String response = httpClient.GET("http://localhost:" + port + "/testhello?name=beer").getContentAsString(); + assertEquals("Hello from test beer", response.trim(), "it test " + System.getProperty("maven.it.name")); + response = httpClient.GET("http://localhost:" + port + "/testhello?name=foo").getContentAsString(); + assertEquals("Hello from test foo", response.trim(), "it test " + System.getProperty("maven.it.name")); + System.out.println("helloServlet"); } } finally @@ -92,36 +92,36 @@ public class TestGetContent } } - public static int getPort() throws Exception { int attempts = 70; int port = -1; - String s = System.getProperty( "jetty.port.file" ); - assertNotNull( s ); - Path p = Paths.get( s ); - while ( true ) + String s = System.getProperty("jetty.port.file"); + assertNotNull(s); + Path p = Paths.get(s); + while (true) { - if ( Files.exists(p) ) + if (Files.exists(p)) { - try (Reader r = Files.newBufferedReader( p ); LineNumberReader lnr = new LineNumberReader( r );) + try (Reader r = Files.newBufferedReader(p); + LineNumberReader lnr = new LineNumberReader(r);) { s = lnr.readLine(); - assertNotNull( s ); - port = Integer.parseInt( s.trim() ); + assertNotNull(s); + port = Integer.parseInt(s.trim()); } break; } else { - if ( --attempts < 0 ) + if (--attempts < 0) { break; } else { - Thread.currentThread().sleep( 1000 ); + Thread.currentThread().sleep(1000); } } } diff --git a/jetty-memcached/jetty-memcached-sessions/pom.xml b/jetty-memcached/jetty-memcached-sessions/pom.xml index 1b889901d19..ca218096903 100644 --- a/jetty-memcached/jetty-memcached-sessions/pom.xml +++ b/jetty-memcached/jetty-memcached-sessions/pom.xml @@ -46,42 +46,42 @@
    - - ${project.groupId}.session - + + ${project.groupId}.session + - + org.apache.maven.plugins maven-surefire-plugin true - + - - memcached - - - memcached.enabled - true - - - - - - org.apache.maven.plugins - maven-surefire-plugin - - false - - - - - + + memcached + + + memcached.enabled + true + + + + + + org.apache.maven.plugins + maven-surefire-plugin + + false + + + + +
    diff --git a/jetty-memcached/jetty-memcached-sessions/src/main/java/org/eclipse/jetty/memcached/session/MemcachedSessionDataMap.java b/jetty-memcached/jetty-memcached-sessions/src/main/java/org/eclipse/jetty/memcached/session/MemcachedSessionDataMap.java index daaee207e6a..2198a822934 100644 --- a/jetty-memcached/jetty-memcached-sessions/src/main/java/org/eclipse/jetty/memcached/session/MemcachedSessionDataMap.java +++ b/jetty-memcached/jetty-memcached-sessions/src/main/java/org/eclipse/jetty/memcached/session/MemcachedSessionDataMap.java @@ -23,6 +23,9 @@ import java.io.IOException; import java.net.InetSocketAddress; import java.util.List; +import net.rubyeye.xmemcached.MemcachedClient; +import net.rubyeye.xmemcached.XMemcachedClientBuilder; +import net.rubyeye.xmemcached.transcoders.SerializingTranscoder; import org.eclipse.jetty.server.session.SessionContext; import org.eclipse.jetty.server.session.SessionData; import org.eclipse.jetty.server.session.SessionDataMap; @@ -31,12 +34,6 @@ import org.eclipse.jetty.util.annotation.ManagedAttribute; import org.eclipse.jetty.util.annotation.ManagedObject; import org.eclipse.jetty.util.component.AbstractLifeCycle; -import net.rubyeye.xmemcached.MemcachedClient; -import net.rubyeye.xmemcached.XMemcachedClientBuilder; -import net.rubyeye.xmemcached.transcoders.SerializingTranscoder; - - - /** * MemcachedSessionDataMap * @@ -52,7 +49,6 @@ public class MemcachedSessionDataMap extends AbstractLifeCycle implements Sessio protected boolean _heartbeats = true; protected XMemcachedClientBuilder _builder; - /** * SessionDataTranscoder * @@ -70,7 +66,7 @@ public class MemcachedSessionDataMap extends AbstractLifeCycle implements Sessio if (in != null) { try (ByteArrayInputStream bis = new ByteArrayInputStream(in); - ClassLoadingObjectInputStream is = new ClassLoadingObjectInputStream(bis)) + ClassLoadingObjectInputStream is = new ClassLoadingObjectInputStream(bis)) { rv = is.readObject(); } @@ -86,7 +82,6 @@ public class MemcachedSessionDataMap extends AbstractLifeCycle implements Sessio return rv; } } - /** * @param host address of memcache server @@ -95,22 +90,20 @@ public class MemcachedSessionDataMap extends AbstractLifeCycle implements Sessio public MemcachedSessionDataMap(String host, String port) { if (host == null || port == null) - throw new IllegalArgumentException("Host: "+host+" port: "+port); - _builder = new XMemcachedClientBuilder(host+":"+port); + throw new IllegalArgumentException("Host: " + host + " port: " + port); + _builder = new XMemcachedClientBuilder(host + ":" + port); } - - - public MemcachedSessionDataMap (List addresses) + + public MemcachedSessionDataMap(List addresses) { _builder = new XMemcachedClientBuilder(addresses); } - - - public MemcachedSessionDataMap (List addresses, int[] weights) + + public MemcachedSessionDataMap(List addresses, int[] weights) { _builder = new XMemcachedClientBuilder(addresses, weights); } - + /** * @return the builder */ @@ -119,46 +112,42 @@ public class MemcachedSessionDataMap extends AbstractLifeCycle implements Sessio return _builder; } - - - /** * @param sec the expiry to use in seconds */ - public void setExpirySec (int sec) + public void setExpirySec(int sec) { _expirySec = sec; } - + /** * Expiry time for memached entries. + * * @return memcached expiry time in sec */ - @ManagedAttribute(value="memcached expiry time in sec", readonly=true) - public int getExpirySec () + @ManagedAttribute(value = "memcached expiry time in sec", readonly = true) + public int getExpirySec() { return _expirySec; } - @ManagedAttribute(value="enable memcached heartbeats", readonly=true) + @ManagedAttribute(value = "enable memcached heartbeats", readonly = true) public boolean isHeartbeats() { return _heartbeats; } - public void setHeartbeats(boolean heartbeats) { _heartbeats = heartbeats; } - @Override public void initialize(SessionContext context) { try { - _builder.setTranscoder(new SessionDataTranscoder ()); + _builder.setTranscoder(new SessionDataTranscoder()); _client = _builder.build(); _client.setEnableHeartBeat(isHeartbeats()); } @@ -168,7 +157,6 @@ public class MemcachedSessionDataMap extends AbstractLifeCycle implements Sessio } } - @Override public SessionData load(String id) throws Exception { @@ -176,13 +164,11 @@ public class MemcachedSessionDataMap extends AbstractLifeCycle implements Sessio return data; } - @Override public void store(String id, SessionData data) throws Exception { _client.set(id, _expirySec, data); - } - + } @Override public boolean delete(String id) throws Exception @@ -191,8 +177,6 @@ public class MemcachedSessionDataMap extends AbstractLifeCycle implements Sessio return true; //delete returns false if the value didn't exist } - - @Override protected void doStop() throws Exception { @@ -202,6 +186,5 @@ public class MemcachedSessionDataMap extends AbstractLifeCycle implements Sessio _client.shutdown(); _client = null; } - } - + } } diff --git a/jetty-memcached/jetty-memcached-sessions/src/main/java/org/eclipse/jetty/memcached/session/MemcachedSessionDataMapFactory.java b/jetty-memcached/jetty-memcached-sessions/src/main/java/org/eclipse/jetty/memcached/session/MemcachedSessionDataMapFactory.java index 0c4dd20fe14..c1714bd7e87 100644 --- a/jetty-memcached/jetty-memcached-sessions/src/main/java/org/eclipse/jetty/memcached/session/MemcachedSessionDataMapFactory.java +++ b/jetty-memcached/jetty-memcached-sessions/src/main/java/org/eclipse/jetty/memcached/session/MemcachedSessionDataMapFactory.java @@ -27,16 +27,14 @@ import org.eclipse.jetty.server.session.SessionDataMapFactory; /** * MemcachedSessionDataMapFactory - * - * */ public class MemcachedSessionDataMapFactory implements SessionDataMapFactory { protected int _expiry; protected boolean _heartbeats = true; - protected int[] _weights; + protected int[] _weights; protected List _addresses; - + /** * @param addresses host and port address of memcached servers */ @@ -47,11 +45,13 @@ public class MemcachedSessionDataMapFactory implements SessionDataMapFactory else { _addresses = new ArrayList<>(); - for (InetSocketAddress a:addresses) + for (InetSocketAddress a : addresses) + { _addresses.add(a); + } } } - + /** * @param weights the relative weight to give each server in the list of addresses */ @@ -60,13 +60,11 @@ public class MemcachedSessionDataMapFactory implements SessionDataMapFactory _weights = weights; } - public int getExpirySec() { return _expiry; } - /** * @param expiry time in secs that memcached item remains valid */ @@ -74,7 +72,7 @@ public class MemcachedSessionDataMapFactory implements SessionDataMapFactory { _expiry = expiry; } - + public boolean isHeartbeats() { return _heartbeats; @@ -85,7 +83,7 @@ public class MemcachedSessionDataMapFactory implements SessionDataMapFactory _heartbeats = heartbeats; } - /** + /** * @see org.eclipse.jetty.server.session.SessionDataMapFactory#getSessionDataMap() */ @Override @@ -96,6 +94,4 @@ public class MemcachedSessionDataMapFactory implements SessionDataMapFactory m.setHeartbeats(isHeartbeats()); return m; } - - } diff --git a/jetty-memcached/jetty-memcached-sessions/src/test/java/org/eclipse/jetty/memcached/session/TestMemcachedSessions.java b/jetty-memcached/jetty-memcached-sessions/src/test/java/org/eclipse/jetty/memcached/session/TestMemcachedSessions.java index 6d1cd331fe9..ffc3d8d68f8 100644 --- a/jetty-memcached/jetty-memcached-sessions/src/test/java/org/eclipse/jetty/memcached/session/TestMemcachedSessions.java +++ b/jetty-memcached/jetty-memcached-sessions/src/test/java/org/eclipse/jetty/memcached/session/TestMemcachedSessions.java @@ -18,15 +18,8 @@ package org.eclipse.jetty.memcached.session; - - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertNotNull; -import static org.junit.jupiter.api.Assertions.assertTrue; - import java.io.IOException; import java.io.PrintWriter; - import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; @@ -48,10 +41,12 @@ import org.eclipse.jetty.servlet.ServletContextHandler; import org.eclipse.jetty.servlet.ServletHolder; import org.junit.jupiter.api.Test; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertTrue; + /** * TestMemcachedSessions - * - * */ public class TestMemcachedSessions { @@ -74,7 +69,7 @@ public class TestMemcachedSessions else if ("get".equals(arg)) { s = req.getSession(false); - System.err.println("GET: s="+s); + System.err.println("GET: s=" + s); } else if ("del".equals(arg)) { @@ -83,7 +78,7 @@ public class TestMemcachedSessions s.invalidate(); s = null; } - + resp.setContentType("text/html"); PrintWriter w = resp.getWriter(); if (s == null) @@ -91,10 +86,8 @@ public class TestMemcachedSessions else w.write((String)s.getAttribute("val")); } - } - - + public static class NullSessionCache extends AbstractSessionCache { @@ -143,12 +136,11 @@ public class TestMemcachedSessions { return null; } - } - + @Test - public void testMemcached () throws Exception - { + public void testMemcached() throws Exception + { String contextPath = "/"; Server server = new Server(0); @@ -173,40 +165,38 @@ public class TestMemcachedSessions client.start(); try { - + int value = 42; ContentResponse response = client.GET("http://localhost:" + port + contextPath + "?action=set&value=" + value); - assertEquals(HttpServletResponse.SC_OK,response.getStatus()); + assertEquals(HttpServletResponse.SC_OK, response.getStatus()); String sessionCookie = response.getHeaders().get("Set-Cookie"); assertTrue(sessionCookie != null); // Mangle the cookie, replacing Path with $Path, etc. sessionCookie = sessionCookie.replaceFirst("(\\W)(P|p)ath=", "$1\\$Path="); String resp = response.getContentAsString(); - assertEquals(resp.trim(),String.valueOf(value)); + assertEquals(resp.trim(), String.valueOf(value)); // Be sure the session value is still there - Request request = client.newRequest("http://localhost:" + port + contextPath + "?action=get"); + Request request = client.newRequest("http://localhost:" + port + contextPath + "?action=get"); request.header("Cookie", sessionCookie); response = request.send(); - assertEquals(HttpServletResponse.SC_OK,response.getStatus()); - + assertEquals(HttpServletResponse.SC_OK, response.getStatus()); + resp = response.getContentAsString(); - assertEquals(String.valueOf(value),resp.trim()); - - + assertEquals(String.valueOf(value), resp.trim()); + //Delete the session - request = client.newRequest("http://localhost:" + port + contextPath + "?action=del"); + request = client.newRequest("http://localhost:" + port + contextPath + "?action=del"); request.header("Cookie", sessionCookie); response = request.send(); - assertEquals(HttpServletResponse.SC_OK,response.getStatus()); - - + assertEquals(HttpServletResponse.SC_OK, response.getStatus()); + //Check that the session is gone - request = client.newRequest("http://localhost:" + port + contextPath + "?action=get"); + request = client.newRequest("http://localhost:" + port + contextPath + "?action=get"); request.header("Cookie", sessionCookie); response = request.send(); - assertEquals(HttpServletResponse.SC_OK,response.getStatus()); + assertEquals(HttpServletResponse.SC_OK, response.getStatus()); resp = response.getContentAsString(); assertEquals("No session", resp.trim()); } @@ -219,7 +209,5 @@ public class TestMemcachedSessions { server.stop(); } - } - } diff --git a/jetty-memcached/pom.xml b/jetty-memcached/pom.xml index 006f612485d..a672294c41a 100644 --- a/jetty-memcached/pom.xml +++ b/jetty-memcached/pom.xml @@ -12,7 +12,6 @@ pom Jetty :: Memcached - jetty-memcached-sessions diff --git a/jetty-nosql/pom.xml b/jetty-nosql/pom.xml index 8f32ffcd8bd..1d3f099c606 100644 --- a/jetty-nosql/pom.xml +++ b/jetty-nosql/pom.xml @@ -13,8 +13,7 @@ install - - + diff --git a/jetty-nosql/src/main/java/org/eclipse/jetty/nosql/NoSqlSessionDataStore.java b/jetty-nosql/src/main/java/org/eclipse/jetty/nosql/NoSqlSessionDataStore.java index 8c98bec8a9b..e9536d4fd28 100644 --- a/jetty-nosql/src/main/java/org/eclipse/jetty/nosql/NoSqlSessionDataStore.java +++ b/jetty-nosql/src/main/java/org/eclipse/jetty/nosql/NoSqlSessionDataStore.java @@ -16,7 +16,6 @@ // ======================================================================== // - package org.eclipse.jetty.nosql; import java.util.HashSet; @@ -25,33 +24,29 @@ import java.util.Set; import org.eclipse.jetty.server.session.AbstractSessionDataStore; import org.eclipse.jetty.server.session.SessionData; - /** * NoSqlSessionDataStore - * - * */ public abstract class NoSqlSessionDataStore extends AbstractSessionDataStore { - + public class NoSqlSessionData extends SessionData { private Object _version; private Set _dirtyAttributes = new HashSet<>(); - public NoSqlSessionData(String id, String cpath, String vhost, long created, long accessed, long lastAccessed, long maxInactiveMs) { super(id, cpath, vhost, created, accessed, lastAccessed, maxInactiveMs); - setVersion (0L); + setVersion(0L); } - - public void setVersion (Object v) + + public void setVersion(Object v) { _version = v; } - - public Object getVersion () + + public Object getVersion() { return _version; } @@ -62,29 +57,23 @@ public abstract class NoSqlSessionDataStore extends AbstractSessionDataStore super.setDirty(name); _dirtyAttributes.add(name); } - - + public Set takeDirtyAttributes() { Set copy = new HashSet<>(_dirtyAttributes); _dirtyAttributes.clear(); return copy; - } - - public Set getAllAttributeNames () + + public Set getAllAttributeNames() { return new HashSet(_attributes.keySet()); } } - @Override public SessionData newSessionData(String id, long created, long accessed, long lastAccessed, long maxInactiveMs) { return new NoSqlSessionData(id, _context.getCanonicalContextPath(), _context.getVhost(), created, accessed, lastAccessed, maxInactiveMs); } - - - } diff --git a/jetty-nosql/src/main/java/org/eclipse/jetty/nosql/mongodb/MongoSessionDataStore.java b/jetty-nosql/src/main/java/org/eclipse/jetty/nosql/mongodb/MongoSessionDataStore.java index ae58ab77882..f44cdd0ad88 100644 --- a/jetty-nosql/src/main/java/org/eclipse/jetty/nosql/mongodb/MongoSessionDataStore.java +++ b/jetty-nosql/src/main/java/org/eclipse/jetty/nosql/mongodb/MongoSessionDataStore.java @@ -16,7 +16,6 @@ // ======================================================================== // - package org.eclipse.jetty.nosql.mongodb; import java.io.ByteArrayInputStream; @@ -50,140 +49,130 @@ import org.eclipse.jetty.util.log.Logger; /** * MongoSessionDataStore * - * The document model is an outer object that contains the elements: + * The document model is an outer object that contains the elements: *
      - *
    • "id" : session_id
    • - *
    • "created" : create_time
    • - *
    • "accessed": last_access_time
    • - *
    • "maxIdle" : max_idle_time setting as session was created
    • - *
    • "expiry" : time at which session should expire
    • - *
    • "valid" : session_valid
    • - *
    • "context" : a nested object containing 1 nested object per context for which the session id is in use + *
    • "id" : session_id
    • + *
    • "created" : create_time
    • + *
    • "accessed": last_access_time
    • + *
    • "maxIdle" : max_idle_time setting as session was created
    • + *
    • "expiry" : time at which session should expire
    • + *
    • "valid" : session_valid
    • + *
    • "context" : a nested object containing 1 nested object per context for which the session id is in use *
    * Each of the nested objects inside the "context" element contains: *
      - *
    • unique_context_name : nested object containing name:value pairs of the session attributes for that context
    • - *
    • unique_context_name: vhost:contextpath, where no vhosts="0_0_0_0", root context = "", contextpath "/" replaced by "_" + *
    • unique_context_name : nested object containing name:value pairs of the session attributes for that context
    • + *
    • unique_context_name: vhost:contextpath, where no vhosts="0_0_0_0", root context = "", contextpath "/" replaced by "_" *
    *

    - * One of the name:value attribute pairs will always be the special attribute "__metadata__". The value + * One of the name:value attribute pairs will always be the special attribute "__metadata__". The value * is an object representing a version counter which is incremented every time the attributes change. *

    *

    * For example: *

    - * { "_id"       : ObjectId("52845534a40b66410f228f23"), 
    - *    "accessed" :  NumberLong("1384818548903"), 
    + * { "_id"       : ObjectId("52845534a40b66410f228f23"),
    + *    "accessed" :  NumberLong("1384818548903"),
      *    "maxIdle"  : 1,
    - *    "context"  : { "0_0_0_0:_testA" : { "A"            : "A", 
    - *                                     "__metadata__" : { "version" : NumberLong(2) } 
    + *    "context"  : { "0_0_0_0:_testA" : { "A"            : "A",
    + *                                     "__metadata__" : { "version" : NumberLong(2) }
      *                                   },
    - *                   "0_0_0_0:_testB" : { "B"            : "B", 
    - *                                     "__metadata__" : { "version" : NumberLong(1) } 
    - *                                   } 
    - *                 }, 
    + *                   "0_0_0_0:_testB" : { "B"            : "B",
    + *                                     "__metadata__" : { "version" : NumberLong(1) }
    + *                                   }
    + *                 },
      *    "created"  : NumberLong("1384818548903"),
      *    "expiry"   : NumberLong("1384818549903"),
    - *    "id"       : "w01ijx2vnalgv1sqrpjwuirprp7", 
    - *    "valid"    : true 
    + *    "id"       : "w01ijx2vnalgv1sqrpjwuirprp7",
    + *    "valid"    : true
      * }
      * 
    *

    * In MongoDB, the nesting level is indicated by "." separators for the key name. Thus to * interact with session fields, the key is composed of: * "context".unique_context_name.field_name - * Eg "context"."0_0_0_0:_testA"."lastSaved" - * - * + * Eg "context"."0_0_0_0:_testA"."lastSaved" */ @ManagedObject public class MongoSessionDataStore extends NoSqlSessionDataStore { - - private final static Logger LOG = Log.getLogger("org.eclipse.jetty.server.session"); - - + + private static final Logger LOG = Log.getLogger("org.eclipse.jetty.server.session"); + /** * Special attribute for a session that is context-specific */ - public final static String __METADATA = "__metadata__"; + public static final String __METADATA = "__metadata__"; /** * Name of nested document field containing 1 sub document per context for which the session id is in use */ - public final static String __CONTEXT = "context"; - + public static final String __CONTEXT = "context"; + /** * Special attribute per session per context, incremented each time attributes are modified */ - public final static String __VERSION = __METADATA + ".version"; - - - public final static String __LASTSAVED = __METADATA + ".lastSaved"; - - - public final static String __LASTNODE = __METADATA + ".lastNode"; - + public static final String __VERSION = __METADATA + ".version"; + + public static final String __LASTSAVED = __METADATA + ".lastSaved"; + + public static final String __LASTNODE = __METADATA + ".lastNode"; + /** * Last access time of session */ - public final static String __ACCESSED = "accessed"; - - - public final static String __LAST_ACCESSED = "lastAccessed"; - - public final static String __ATTRIBUTES = "attributes"; - + public static final String __ACCESSED = "accessed"; + + public static final String __LAST_ACCESSED = "lastAccessed"; + + public static final String __ATTRIBUTES = "attributes"; + /** * Time this session will expire, based on last access time and maxIdle */ - public final static String __EXPIRY = "expiry"; - + public static final String __EXPIRY = "expiry"; + /** * The max idle time of a session (smallest value across all contexts which has a session with the same id) */ - public final static String __MAX_IDLE = "maxIdle"; - + public static final String __MAX_IDLE = "maxIdle"; + /** * Time of session creation */ - public final static String __CREATED = "created"; - + public static final String __CREATED = "created"; + /** * Whether or not session is valid */ - public final static String __VALID = "valid"; - + public static final String __VALID = "valid"; + /** * Session id */ - public final static String __ID = "id"; - - - + public static final String __ID = "id"; + /** * Utility value of 1 for a session version for this context */ - private DBObject _version_1; - + private DBObject _version1; + /** * Access to MongoDB */ private DBCollection _dbSessions; - - - public void setDBCollection (DBCollection collection) + + public void setDBCollection(DBCollection collection) { _dbSessions = collection; } - - @ManagedAttribute(value="DBCollection", readonly=true) - public DBCollection getDBCollection () + + @ManagedAttribute(value = "DBCollection", readonly = true) + public DBCollection getDBCollection() { return _dbSessions; } - - + @Override public SessionData doLoad(String id) throws Exception { @@ -197,7 +186,7 @@ public class MongoSessionDataStore extends NoSqlSessionDataStore if (sessionDocument == null) return null; - Boolean valid = (Boolean)sessionDocument.get(__VALID); + Boolean valid = (Boolean)sessionDocument.get(__VALID); if (LOG.isDebugEnabled()) LOG.debug("id={} valid={}", id, valid); @@ -213,14 +202,15 @@ public class MongoSessionDataStore extends NoSqlSessionDataStore Long accessed = (Long)sessionDocument.get(__ACCESSED); Long lastAccessed = (Long)sessionDocument.get(__LAST_ACCESSED); Long maxInactive = (Long)sessionDocument.get(__MAX_IDLE); - Long expiry = (Long)sessionDocument.get(__EXPIRY); + Long expiry = (Long)sessionDocument.get(__EXPIRY); NoSqlSessionData data = null; // get the session for the context - DBObject sessionSubDocumentForContext = (DBObject)MongoUtils.getNestedValue(sessionDocument,getContextField()); + DBObject sessionSubDocumentForContext = (DBObject)MongoUtils.getNestedValue(sessionDocument, getContextField()); - if (LOG.isDebugEnabled()) LOG.debug("attrs {}", sessionSubDocumentForContext); + if (LOG.isDebugEnabled()) + LOG.debug("attrs {}", sessionSubDocumentForContext); if (sessionSubDocumentForContext != null) { @@ -228,14 +218,14 @@ public class MongoSessionDataStore extends NoSqlSessionDataStore LOG.debug("Session {} present for context {}", id, _context); //only load a session if it exists for this context - data = (NoSqlSessionData)newSessionData(id, created, accessed, (lastAccessed == null? accessed:lastAccessed), maxInactive); + data = (NoSqlSessionData)newSessionData(id, created, accessed, (lastAccessed == null ? accessed : lastAccessed), maxInactive); data.setVersion(version); data.setExpiry(expiry); data.setContextPath(_context.getCanonicalContextPath()); data.setVhost(_context.getVhost()); data.setLastSaved(lastSaved); data.setLastNode(lastNode); - + if (attributes == null) { //legacy attribute storage format: the attributes are all fields in the document @@ -243,11 +233,11 @@ public class MongoSessionDataStore extends NoSqlSessionDataStore for (String name : sessionSubDocumentForContext.keySet()) { //skip special metadata attribute which is not one of the actual session attributes - if ( __METADATA.equals(name) ) - continue; + if (__METADATA.equals(name)) + continue; String attr = MongoUtils.decodeName(name); Object value = MongoUtils.decodeValue(sessionSubDocumentForContext.get(name)); - map.put(attr,value); + map.put(attr, value); } data.putAllAttributes(map); } @@ -264,7 +254,7 @@ public class MongoSessionDataStore extends NoSqlSessionDataStore else { if (LOG.isDebugEnabled()) - LOG.debug("Session {} not present for context {}", id, _context); + LOG.debug("Session {} not present for context {}", id, _context); } return data; @@ -275,12 +265,11 @@ public class MongoSessionDataStore extends NoSqlSessionDataStore } } - @Override public boolean delete(String id) throws Exception { if (LOG.isDebugEnabled()) - LOG.debug("Remove:session {} for context ",id, _context); + LOG.debug("Remove:session {} for context ", id, _context); /* * Check if the session exists and if it does remove the context @@ -288,7 +277,7 @@ public class MongoSessionDataStore extends NoSqlSessionDataStore */ BasicDBObject mongoKey = new BasicDBObject(__ID, id); - //DBObject sessionDocument = _dbSessions.findOne(mongoKey,_version_1); + //DBObject sessionDocument = _dbSessions.findOne(mongoKey,_version1); DBObject sessionDocument = _dbSessions.findOne(new BasicDBObject(__ID, id)); if (sessionDocument != null) @@ -315,23 +304,20 @@ public class MongoSessionDataStore extends NoSqlSessionDataStore _dbSessions.remove(new BasicDBObject(__ID, id), WriteConcern.SAFE); return true; } - + //just remove entry for my context BasicDBObject remove = new BasicDBObject(); BasicDBObject unsets = new BasicDBObject(); - unsets.put(getContextField(),1); - remove.put("$unset",unsets); - _dbSessions.update(mongoKey,remove,false,false,WriteConcern.SAFE); + unsets.put(getContextField(), 1); + remove.put("$unset", unsets); + _dbSessions.update(mongoKey, remove, false, false, WriteConcern.SAFE); return true; } else { return false; } - } - - @Override public boolean exists(String id) throws Exception @@ -340,70 +326,71 @@ public class MongoSessionDataStore extends NoSqlSessionDataStore fields.put(__EXPIRY, 1); fields.put(__VALID, 1); fields.put(getContextSubfield(__VERSION), 1); - + DBObject sessionDocument = _dbSessions.findOne(new BasicDBObject(__ID, id), fields); - + if (sessionDocument == null) return false; //doesn't exist Boolean valid = (Boolean)sessionDocument.get(__VALID); if (!valid) return false; //invalid - nb should not happen - + Long expiry = (Long)sessionDocument.get(__EXPIRY); - + //expired? if (expiry.longValue() > 0 && expiry.longValue() < System.currentTimeMillis()) return false; //it's expired - + //does it exist for this context? Object version = MongoUtils.getNestedValue(sessionDocument, getContextSubfield(__VERSION)); if (version == null) return false; - + return true; } - @Override public Set doGetExpired(Set candidates) { long now = System.currentTimeMillis(); long upperBound = now; Set expiredSessions = new HashSet<>(); - + //firstly ask mongo to verify if these candidate ids have expired - all of //these candidates will be for our node - BasicDBObject query = new BasicDBObject(); - query.append(__ID,new BasicDBObject("$in", candidates)); - query.append(__EXPIRY, new BasicDBObject("$gt", 0).append("$lt", upperBound)); + BasicDBObject query = new BasicDBObject(); + query.append(__ID, new BasicDBObject("$in", candidates)); + query.append(__EXPIRY, new BasicDBObject("$gt", 0).append("$lt", upperBound)); DBCursor verifiedExpiredSessions = null; - try + try { verifiedExpiredSessions = _dbSessions.find(query, new BasicDBObject(__ID, 1)); - for ( DBObject session : verifiedExpiredSessions ) + for (DBObject session : verifiedExpiredSessions) { String id = (String)session.get(__ID); - if (LOG.isDebugEnabled()) LOG.debug("{} Mongo confirmed expired session {}", _context,id); + if (LOG.isDebugEnabled()) + LOG.debug("{} Mongo confirmed expired session {}", _context, id); expiredSessions.add(id); - } + } } finally { - if (verifiedExpiredSessions != null) verifiedExpiredSessions.close(); + if (verifiedExpiredSessions != null) + verifiedExpiredSessions.close(); } //now ask mongo to find sessions last managed by any nodes that expired a while ago //if this is our first expiry check, make sure that we only grab really old sessions if (_lastExpiryCheckTime <= 0) - upperBound = (now - (3*(1000L * _gracePeriodSec))); + upperBound = (now - (3 * (1000L * _gracePeriodSec))); else - upperBound = _lastExpiryCheckTime - (1000L * _gracePeriodSec); - + upperBound = _lastExpiryCheckTime - (1000L * _gracePeriodSec); + query = new BasicDBObject(); BasicDBObject gt = new BasicDBObject(__EXPIRY, new BasicDBObject("$gt", 0)); - BasicDBObject lt = new BasicDBObject (__EXPIRY, new BasicDBObject("$lt", upperBound)); + BasicDBObject lt = new BasicDBObject(__EXPIRY, new BasicDBObject("$lt", upperBound)); BasicDBList list = new BasicDBList(); list.add(gt); list.add(lt); @@ -414,12 +401,13 @@ public class MongoSessionDataStore extends NoSqlSessionDataStore { BasicDBObject bo = new BasicDBObject(__ID, 1); bo.append(__EXPIRY, 1); - + oldExpiredSessions = _dbSessions.find(query, bo); for (DBObject session : oldExpiredSessions) { String id = (String)session.get(__ID); - if (LOG.isDebugEnabled()) LOG.debug("{} Mongo found old expired session {}", _context, id+" exp="+session.get(__EXPIRY)); + if (LOG.isDebugEnabled()) + LOG.debug("{} Mongo found old expired session {}", _context, id + " exp=" + session.get(__EXPIRY)); expiredSessions.add(id); } } @@ -429,10 +417,9 @@ public class MongoSessionDataStore extends NoSqlSessionDataStore oldExpiredSessions.close(); } - - //check through sessions that were candidates, but not found as expired. + //check through sessions that were candidates, but not found as expired. //they may no longer be persisted, in which case they are treated as expired. - for (String c:candidates) + for (String c : candidates) { if (!expiredSessions.contains(c)) { @@ -450,8 +437,7 @@ public class MongoSessionDataStore extends NoSqlSessionDataStore return expiredSessions; } - - public void initialize (SessionContext context) throws Exception + public void initialize(SessionContext context) throws Exception { if (isStarted()) throw new IllegalStateException("Context set after SessionDataStore started"); @@ -459,10 +445,9 @@ public class MongoSessionDataStore extends NoSqlSessionDataStore ensureIndexes(); } - @Override public void doStore(String id, SessionData data, long lastSaveTime) throws Exception - { + { // Form query for upsert BasicDBObject key = new BasicDBObject(__ID, id); @@ -470,18 +455,17 @@ public class MongoSessionDataStore extends NoSqlSessionDataStore BasicDBObject update = new BasicDBObject(); boolean upsert = false; BasicDBObject sets = new BasicDBObject(); - - + Object version = ((NoSqlSessionData)data).getVersion(); - + // New session if (lastSaveTime <= 0) { upsert = true; version = 1L; - sets.put(__CREATED,data.getCreated()); - sets.put(__VALID,true); - sets.put(getContextSubfield(__VERSION),version); + sets.put(__CREATED, data.getCreated()); + sets.put(__VALID, true); + sets.put(getContextSubfield(__VERSION), version); sets.put(getContextSubfield(__LASTSAVED), data.getLastSaved()); sets.put(getContextSubfield(__LASTNODE), data.getLastNode()); sets.put(__MAX_IDLE, data.getMaxInactiveMs()); @@ -494,7 +478,7 @@ public class MongoSessionDataStore extends NoSqlSessionDataStore sets.put(getContextSubfield(__LASTNODE), data.getLastNode()); version = ((Number)version).longValue() + 1L; ((NoSqlSessionData)data).setVersion(version); - update.put("$inc",_version_1); + update.put("$inc", _version1); //if max idle time and/or expiry is smaller for this context, then choose that for the whole session doc BasicDBObject fields = new BasicDBObject(); fields.append(__MAX_IDLE, true); @@ -503,9 +487,9 @@ public class MongoSessionDataStore extends NoSqlSessionDataStore if (o != null) { Long tmpLong = (Long)o.get(__MAX_IDLE); - long currentMaxIdle = (tmpLong == null? 0:tmpLong.longValue()); + long currentMaxIdle = (tmpLong == null ? 0 : tmpLong.longValue()); tmpLong = (Long)o.get(__EXPIRY); - long currentExpiry = (tmpLong == null? 0 : tmpLong.longValue()); + long currentExpiry = (tmpLong == null ? 0 : tmpLong.longValue()); if (currentMaxIdle != data.getMaxInactiveMs()) sets.put(__MAX_IDLE, data.getMaxInactiveMs()); @@ -519,85 +503,79 @@ public class MongoSessionDataStore extends NoSqlSessionDataStore sets.put(__ACCESSED, data.getAccessed()); sets.put(__LAST_ACCESSED, data.getLastAccessed()); - + try (ByteArrayOutputStream baos = new ByteArrayOutputStream(); ObjectOutputStream oos = new ObjectOutputStream(baos);) { - SessionData.serializeAttributes(data, oos); + SessionData.serializeAttributes(data, oos); sets.put(getContextSubfield(__ATTRIBUTES), baos.toByteArray()); } // Do the upsert if (!sets.isEmpty()) - update.put("$set",sets); + update.put("$set", sets); - WriteResult res = _dbSessions.update(key,update,upsert,false,WriteConcern.SAFE); + WriteResult res = _dbSessions.update(key, update, upsert, false, WriteConcern.SAFE); if (LOG.isDebugEnabled()) - LOG.debug("Save:db.sessions.update( {}, {},{} )", key, update, res); + LOG.debug("Save:db.sessions.update( {}, {},{} )", key, update, res); } protected void ensureIndexes() throws MongoException { - _version_1 = new BasicDBObject(getContextSubfield(__VERSION),1); + _version1 = new BasicDBObject(getContextSubfield(__VERSION), 1); DBObject idKey = BasicDBObjectBuilder.start().add("id", 1).get(); _dbSessions.createIndex(idKey, - BasicDBObjectBuilder.start() - .add("name", "id_1") - .add("ns", _dbSessions.getFullName()) - .add("sparse", false) - .add("unique", true) - .get()); + BasicDBObjectBuilder.start() + .add("name", "id_1") + .add("ns", _dbSessions.getFullName()) + .add("sparse", false) + .add("unique", true) + .get()); DBObject versionKey = BasicDBObjectBuilder.start().add("id", 1).add("version", 1).get(); _dbSessions.createIndex(versionKey, BasicDBObjectBuilder.start() - .add("name", "id_1_version_1") - .add("ns", _dbSessions.getFullName()) - .add("sparse", false) - .add("unique", true) - .get()); - LOG.debug( "done ensure Mongodb indexes existing" ); + .add("name", "id_1_version_1") + .add("ns", _dbSessions.getFullName()) + .add("sparse", false) + .add("unique", true) + .get()); + LOG.debug("done ensure Mongodb indexes existing"); //TODO perhaps index on expiry time? } - private String getContextField () + private String getContextField() { return __CONTEXT + "." + getCanonicalContextId(); } - - - private String getCanonicalContextId () + + private String getCanonicalContextId() { return canonicalizeVHost(_context.getVhost()) + ":" + _context.getCanonicalContextPath(); } - - private String canonicalizeVHost (String vhost) + + private String canonicalizeVHost(String vhost) { if (vhost == null) return ""; return StringUtil.replace(vhost, '.', '_'); } - - - private String getContextSubfield (String attr) - { - return getContextField () +"."+ attr; - } - - @ManagedAttribute(value="does store serialize sessions", readonly=true) + private String getContextSubfield(String attr) + { + return getContextField() + "." + attr; + } + + @ManagedAttribute(value = "does store serialize sessions", readonly = true) @Override public boolean isPassivating() { return true; } - - @Override public String toString() { - return String.format("%s[collection=%s]", super.toString(),getDBCollection()); + return String.format("%s[collection=%s]", super.toString(), getDBCollection()); } - } diff --git a/jetty-nosql/src/main/java/org/eclipse/jetty/nosql/mongodb/MongoSessionDataStoreFactory.java b/jetty-nosql/src/main/java/org/eclipse/jetty/nosql/mongodb/MongoSessionDataStoreFactory.java index cf0200d0829..c0c8696301b 100644 --- a/jetty-nosql/src/main/java/org/eclipse/jetty/nosql/mongodb/MongoSessionDataStoreFactory.java +++ b/jetty-nosql/src/main/java/org/eclipse/jetty/nosql/mongodb/MongoSessionDataStoreFactory.java @@ -16,7 +16,6 @@ // ======================================================================== // - package org.eclipse.jetty.nosql.mongodb; import java.net.UnknownHostException; @@ -30,8 +29,6 @@ import org.eclipse.jetty.util.StringUtil; /** * MongoSessionDataStoreFactory - * - * */ public class MongoSessionDataStoreFactory extends AbstractSessionDataStoreFactory { @@ -98,7 +95,7 @@ public class MongoSessionDataStoreFactory extends AbstractSessionDataStoreFactor } /** - * @param connectionString the connection string to set. This has priority over dbHost and port + * @param connectionString the connection string to set. This has priority over dbHost and port */ public void setConnectionString(String connectionString) { @@ -121,9 +118,8 @@ public class MongoSessionDataStoreFactory extends AbstractSessionDataStoreFactor _collectionName = collectionName; } - /** - * @throws Exception {@link UnknownHostException} if any issue while resolving MongoDB Host + * @throws Exception {@link UnknownHostException} if any issue while resolving MongoDB Host * @see org.eclipse.jetty.server.session.SessionDataStoreFactory#getSessionDataStore(org.eclipse.jetty.server.session.SessionHandler) */ @Override @@ -145,7 +141,4 @@ public class MongoSessionDataStoreFactory extends AbstractSessionDataStoreFactor store.setDBCollection(mongo.getDB(getDbName()).getCollection(getCollectionName())); return store; } - - - } diff --git a/jetty-nosql/src/main/java/org/eclipse/jetty/nosql/mongodb/MongoUtils.java b/jetty-nosql/src/main/java/org/eclipse/jetty/nosql/mongodb/MongoUtils.java index afe3c76f984..94de6c5785c 100644 --- a/jetty-nosql/src/main/java/org/eclipse/jetty/nosql/mongodb/MongoUtils.java +++ b/jetty-nosql/src/main/java/org/eclipse/jetty/nosql/mongodb/MongoUtils.java @@ -16,7 +16,6 @@ // ======================================================================== // - package org.eclipse.jetty.nosql.mongodb; import java.io.ByteArrayInputStream; @@ -36,11 +35,10 @@ import org.eclipse.jetty.util.URIUtil; * MongoUtils * * Some utility methods for manipulating mongo data. This class facilitates testing. - * */ public class MongoUtils { - + public static Object decodeValue(final Object valueToDecode) throws IOException, ClassNotFoundException { if (valueToDecode == null || valueToDecode instanceof Number || valueToDecode instanceof String || valueToDecode instanceof Boolean || valueToDecode instanceof Date) @@ -60,7 +58,7 @@ public class MongoUtils for (String name : ((DBObject)valueToDecode).keySet()) { String attr = decodeName(name); - map.put(attr,decodeValue(((DBObject)valueToDecode).get(name))); + map.put(attr, decodeValue(((DBObject)valueToDecode).get(name))); } return map; } @@ -96,13 +94,13 @@ public class MongoUtils o = null; break; } - o.append(encodeName(entry.getKey().toString()),encodeName(entry.getValue())); + o.append(encodeName(entry.getKey().toString()), encodeName(entry.getValue())); } if (o != null) return o; } - + ByteArrayOutputStream bout = new ByteArrayOutputStream(); ObjectOutputStream out = new ObjectOutputStream(bout); out.reset(); @@ -110,15 +108,12 @@ public class MongoUtils out.flush(); return bout.toByteArray(); } - - /** * Dig through a given dbObject for the nested value - * + * * @param dbObject the mongo object to search * @param nestedKey the field key to find - * * @return the value of the field key */ public static Object getNestedValue(DBObject dbObject, String nestedKey) @@ -131,7 +126,7 @@ public class MongoUtils { temp = (DBObject)temp.get(keyChain[i]); - if ( temp == null ) + if (temp == null) { return null; } @@ -139,6 +134,4 @@ public class MongoUtils return temp.get(keyChain[keyChain.length - 1]); } - - } diff --git a/jetty-osgi/jetty-osgi-alpn/pom.xml b/jetty-osgi/jetty-osgi-alpn/pom.xml index 4f11d832f14..0d18a508cd8 100644 --- a/jetty-osgi/jetty-osgi-alpn/pom.xml +++ b/jetty-osgi/jetty-osgi-alpn/pom.xml @@ -20,12 +20,12 @@ org.apache.felix maven-bundle-plugin - - ${bundle-symbolic-name};singleton:=true - Jetty OSGi ALPN Fragment - !javax.*;!org.eclipse.jetty.* - system.bundle;extension:=framework - + + ${bundle-symbolic-name};singleton:=true + Jetty OSGi ALPN Fragment + !javax.*;!org.eclipse.jetty.* + system.bundle;extension:=framework + diff --git a/jetty-osgi/jetty-osgi-boot-jsp/pom.xml b/jetty-osgi/jetty-osgi-boot-jsp/pom.xml index dff95f4c9dd..b8ebe520cab 100644 --- a/jetty-osgi/jetty-osgi-boot-jsp/pom.xml +++ b/jetty-osgi/jetty-osgi-boot-jsp/pom.xml @@ -47,82 +47,20 @@ - org.apache.felix - maven-bundle-plugin - true - - - Jetty-OSGi-Jasper Integration - - org.eclipse.jetty.osgi.boot - !org.eclipse.jetty.osgi.boot.* - org.eclipse.jdt.*;resolution:=optional, - org.eclipse.jdt.core.compiler.*;resolution:=optional, - com.sun.el;resolution:=optional, - com.sun.el.lang;resolution:=optional, - com.sun.el.parser;resolution:=optional, - com.sun.el.util;resolution:=optional, - javax.el;version="[3.0,3.1)", - javax.servlet;version="[3.1,4.1)", - javax.servlet.resources;version="[3.1,4.1)", - javax.servlet.jsp.resources;version="[2.3,4.1)", - javax.servlet.jsp;version="[2.3,2.4.1)", - javax.servlet.jsp.el;version="[2.3,2.4.1)", - javax.servlet.jsp.tagext;version="[2.3,2.4.1)", - javax.servlet.jsp.jstl.core;version="1.2";resolution:=optional, - javax.servlet.jsp.jstl.fmt;version="1.2";resolution:=optional, - javax.servlet.jsp.jstl.sql;version="1.2";resolution:=optional, - javax.servlet.jsp.jstl.tlv;version="1.2";resolution:=optional, - org.apache.el;version="[8.0.23,10)";resolution:=optional, - org.apache.el.lang;version="[8.0.23,10)";resolution:=optional, - org.apache.el.stream;version="[8.0.23,10)";resolution:=optional, - org.apache.el.util;version="[8.0.23,10)";resolution:=optional, - org.apache.el.parser;version="[8.0.23,10)";resolution:=optional, - org.apache.jasper;version="[8.0.23,10)";resolution:=optional, - org.apache.jasper.compiler;version="[8.0.23,10)";resolution:=optional, - org.apache.jasper.compiler.tagplugin;version="[8.0.23,10)";resolution:=optional, - org.apache.jasper.runtime;version="[8.0.23,10)";resolution:=optional, - org.apache.jasper.security;version="[8.0.23,10)";resolution:=optional, - org.apache.jasper.servlet;version="[8.0.23,10)";resolution:=optional, - org.apache.jasper.tagplugins.jstl;version="[8.0.23,10)";resolution:=optional, - org.apache.jasper.util;version="[8.0.23,10)";resolution:=optional, - org.apache.jasper.xmlparser;version="[8.0.23,10)";resolution:=optional, - org.apache.taglibs.standard;version="1.2";resolution:=optional, - org.apache.taglibs.standard.extra.spath;version="1.2";resolution:=optional, - org.apache.taglibs.standard.functions;version="1.2";resolution:=optional, - org.apache.taglibs.standard.lang.jstl;version="1.2";resolution:=optional, - org.apache.taglibs.standard.lang.jstl.parser;version="1.2";resolution:=optional, - org.apache.taglibs.standard.lang.jstl.test;version="1.2";resolution:=optional, - org.apache.taglibs.standard.lang.jstl.test.beans;version="1.2";resolution:=optional, - org.apache.taglibs.standard.lang.support;version="1.2";resolution:=optional, - org.apache.taglibs.standard.resources;version="1.2";resolution:=optional, - org.apache.taglibs.standard.tag.common.core;version="1.2";resolution:=optional, - org.apache.taglibs.standard.tag.common.fmt;version="1.2";resolution:=optional, - org.apache.taglibs.standard.tag.common.sql;version="1.2";resolution:=optional, - org.apache.taglibs.standard.tag.common.xml;version="1.2";resolution:=optional, - org.apache.taglibs.standard.tag.el.core;version="1.2";resolution:=optional, - org.apache.taglibs.standard.tag.el.fmt;version="1.2";resolution:=optional, - org.apache.taglibs.standard.tag.el.sql;version="1.2";resolution:=optional, - org.apache.taglibs.standard.tag.el.xml;version="1.2";resolution:=optional, - org.apache.taglibs.standard.tag.rt.core;version="1.2";resolution:=optional, - org.apache.taglibs.standard.tag.rt.fmt;version="1.2";resolution:=optional, - org.apache.taglibs.standard.tag.rt.sql;version="1.2";resolution:=optional, - org.apache.taglibs.standard.tag.rt.xml;version="1.2";resolution:=optional, - org.apache.taglibs.standard.tei;version="1.2";resolution:=optional, - org.apache.taglibs.standard.tlv;version="1.2";resolution:=optional, - org.apache.tomcat;version="[8.0.23,10)";resolution:=optional, - org.eclipse.jetty.jsp;version="[$(version;===;${parsedVersion.osgiVersion}),$(version;==+;${parsedVersion.osgiVersion}))";resolution:=optional, - org.osgi.*, - org.xml.*;resolution:=optional, - org.xml.sax.*;resolution:=optional, - javax.xml.*;resolution:=optional, - org.w3c.dom;resolution:=optional, - org.w3c.dom.ls;resolution:=optional, - javax.xml.parser;resolution:=optional - - org.eclipse.jetty.jsp.*;version="[$(version;===;${parsedVersion.osgiVersion}),$(version;==+;${parsedVersion.osgiVersion}))",org.apache.jasper.*;version="8.0.23",org.apache.el.*;version="8.0.23" - - + org.apache.felix + maven-bundle-plugin + true + + + Jetty-OSGi-Jasper Integration + + org.eclipse.jetty.osgi.boot + !org.eclipse.jetty.osgi.boot.* + org.eclipse.jdt.*;resolution:=optional, org.eclipse.jdt.core.compiler.*;resolution:=optional, com.sun.el;resolution:=optional, com.sun.el.lang;resolution:=optional, com.sun.el.parser;resolution:=optional, com.sun.el.util;resolution:=optional, javax.el;version="[3.0,3.1)", javax.servlet;version="[3.1,4.1)", javax.servlet.resources;version="[3.1,4.1)", javax.servlet.jsp.resources;version="[2.3,4.1)", javax.servlet.jsp;version="[2.3,2.4.1)", javax.servlet.jsp.el;version="[2.3,2.4.1)", javax.servlet.jsp.tagext;version="[2.3,2.4.1)", javax.servlet.jsp.jstl.core;version="1.2";resolution:=optional, javax.servlet.jsp.jstl.fmt;version="1.2";resolution:=optional, javax.servlet.jsp.jstl.sql;version="1.2";resolution:=optional, javax.servlet.jsp.jstl.tlv;version="1.2";resolution:=optional, org.apache.el;version="[8.0.23,10)";resolution:=optional, org.apache.el.lang;version="[8.0.23,10)";resolution:=optional, org.apache.el.stream;version="[8.0.23,10)";resolution:=optional, org.apache.el.util;version="[8.0.23,10)";resolution:=optional, org.apache.el.parser;version="[8.0.23,10)";resolution:=optional, org.apache.jasper;version="[8.0.23,10)";resolution:=optional, org.apache.jasper.compiler;version="[8.0.23,10)";resolution:=optional, org.apache.jasper.compiler.tagplugin;version="[8.0.23,10)";resolution:=optional, org.apache.jasper.runtime;version="[8.0.23,10)";resolution:=optional, org.apache.jasper.security;version="[8.0.23,10)";resolution:=optional, org.apache.jasper.servlet;version="[8.0.23,10)";resolution:=optional, org.apache.jasper.tagplugins.jstl;version="[8.0.23,10)";resolution:=optional, org.apache.jasper.util;version="[8.0.23,10)";resolution:=optional, org.apache.jasper.xmlparser;version="[8.0.23,10)";resolution:=optional, org.apache.taglibs.standard;version="1.2";resolution:=optional, org.apache.taglibs.standard.extra.spath;version="1.2";resolution:=optional, org.apache.taglibs.standard.functions;version="1.2";resolution:=optional, org.apache.taglibs.standard.lang.jstl;version="1.2";resolution:=optional, org.apache.taglibs.standard.lang.jstl.parser;version="1.2";resolution:=optional, org.apache.taglibs.standard.lang.jstl.test;version="1.2";resolution:=optional, org.apache.taglibs.standard.lang.jstl.test.beans;version="1.2";resolution:=optional, org.apache.taglibs.standard.lang.support;version="1.2";resolution:=optional, org.apache.taglibs.standard.resources;version="1.2";resolution:=optional, org.apache.taglibs.standard.tag.common.core;version="1.2";resolution:=optional, org.apache.taglibs.standard.tag.common.fmt;version="1.2";resolution:=optional, org.apache.taglibs.standard.tag.common.sql;version="1.2";resolution:=optional, org.apache.taglibs.standard.tag.common.xml;version="1.2";resolution:=optional, org.apache.taglibs.standard.tag.el.core;version="1.2";resolution:=optional, org.apache.taglibs.standard.tag.el.fmt;version="1.2";resolution:=optional, org.apache.taglibs.standard.tag.el.sql;version="1.2";resolution:=optional, org.apache.taglibs.standard.tag.el.xml;version="1.2";resolution:=optional, org.apache.taglibs.standard.tag.rt.core;version="1.2";resolution:=optional, org.apache.taglibs.standard.tag.rt.fmt;version="1.2";resolution:=optional, org.apache.taglibs.standard.tag.rt.sql;version="1.2";resolution:=optional, org.apache.taglibs.standard.tag.rt.xml;version="1.2";resolution:=optional, org.apache.taglibs.standard.tei;version="1.2";resolution:=optional, org.apache.taglibs.standard.tlv;version="1.2";resolution:=optional, org.apache.tomcat;version="[8.0.23,10)";resolution:=optional, org.eclipse.jetty.jsp;version="[$(version;===;${parsedVersion.osgiVersion}),$(version;==+;${parsedVersion.osgiVersion}))";resolution:=optional, org.osgi.*, org.xml.*;resolution:=optional, org.xml.sax.*;resolution:=optional, javax.xml.*;resolution:=optional, org.w3c.dom;resolution:=optional, org.w3c.dom.ls;resolution:=optional, javax.xml.parser;resolution:=optional + + org.eclipse.jetty.jsp.*;version="[$(version;===;${parsedVersion.osgiVersion}),$(version;==+;${parsedVersion.osgiVersion}))",org.apache.jasper.*;version="8.0.23",org.apache.el.*;version="8.0.23" + + org.codehaus.mojo diff --git a/jetty-osgi/jetty-osgi-boot-jsp/src/main/java/org/eclipse/jetty/osgi/boot/jasper/ContainerTldBundleDiscoverer.java b/jetty-osgi/jetty-osgi-boot-jsp/src/main/java/org/eclipse/jetty/osgi/boot/jasper/ContainerTldBundleDiscoverer.java index 0eced9fcd01..23a2de9ee8c 100644 --- a/jetty-osgi/jetty-osgi-boot-jsp/src/main/java/org/eclipse/jetty/osgi/boot/jasper/ContainerTldBundleDiscoverer.java +++ b/jetty-osgi/jetty-osgi-boot-jsp/src/main/java/org/eclipse/jetty/osgi/boot/jasper/ContainerTldBundleDiscoverer.java @@ -38,39 +38,35 @@ import org.eclipse.jetty.util.log.Logger; import org.osgi.framework.Bundle; import org.osgi.framework.FrameworkUtil; - - /** * ContainerTldBundleDiscoverer - * + * * Finds bundles that are considered as on the container classpath that * contain tlds. - * + * * The System property org.eclipse.jetty.osgi.tldbundles is a comma * separated list of exact symbolic names of bundles that have container classpath * tlds. - * + * * The DeploymentManager context attribute "org.eclipse.jetty.server.webapp.containerIncludeBundlePattern" - * can be used to define a pattern of symbolic names of bundles that contain container + * can be used to define a pattern of symbolic names of bundles that contain container * classpath tlds. - * + * * The matching bundles are converted to URLs that are put onto a special classloader that acts as the * parent classloader for contexts deployed by the jetty Server instance (see ServerInstanceWrapper). - * - * It also discovers the bundle that contains the jstl taglib and adds it into the + * + * It also discovers the bundle that contains the jstl taglib and adds it into the * "org.eclipse.jetty.server.webapp.containerIncludeBundlePattern" (if it is not already there) so * that the WebInfOSGiConfiguration class will add the jstl taglib bundle into the list of container * resources. - * + * * Eg: * -Dorg.eclipse.jetty.osgi.tldbundles=org.springframework.web.servlet,com.opensymphony.module.sitemesh - * */ public class ContainerTldBundleDiscoverer implements TldBundleDiscoverer { private static final Logger LOG = Log.getLogger(ContainerTldBundleDiscoverer.class); - private static String DEFAULT_JSP_FACTORY_IMPL_CLASS = "org.apache.jasper.runtime.JspFactoryImpl"; /** @@ -81,16 +77,16 @@ public class ContainerTldBundleDiscoverer implements TldBundleDiscoverer private static String DEFAULT_JSTL_BUNDLE_CLASS = "org.apache.taglibs.standard.tag.rt.core.WhenTag"; private Bundle jstlBundle = null; - + /** * Check the System property "org.eclipse.jetty.osgi.tldbundles" for names of * bundles that contain tlds and convert to URLs. - * + * * @return The location of the jars that contain tld files as URLs. */ @Override public URL[] getUrlsForBundlesWithTlds(DeploymentManager deploymentManager, BundleFileLocatorHelper locatorHelper) throws Exception - { + { if (!isJspAvailable()) { return new URL[0]; @@ -102,21 +98,23 @@ public class ContainerTldBundleDiscoverer implements TldBundleDiscoverer Bundle[] bundles = FrameworkUtil.getBundle(ContainerTldBundleDiscoverer.class).getBundleContext().getBundles(); HashSet urls = new HashSet(); String tmp = System.getProperty(OSGiMetaInfConfiguration.SYS_PROP_TLD_BUNDLES); //comma separated exact names - List sysNames = new ArrayList(); + List sysNames = new ArrayList(); if (tmp != null) { StringTokenizer tokenizer = new StringTokenizer(tmp, ", \n\r\t", false); while (tokenizer.hasMoreTokens()) + { sysNames.add(tokenizer.nextToken()); + } } - tmp = (String) deploymentManager.getContextAttribute(OSGiMetaInfConfiguration.CONTAINER_BUNDLE_PATTERN); //bundle name patterns - - Pattern pattern = (tmp==null? null : Pattern.compile(tmp)); - + tmp = (String)deploymentManager.getContextAttribute(OSGiMetaInfConfiguration.CONTAINER_BUNDLE_PATTERN); //bundle name patterns + + Pattern pattern = (tmp == null ? null : Pattern.compile(tmp)); + //check that the jstl bundle is not already included in the pattern, and include it if it is not because //subsequent classes such as OSGiWebInfConfiguration use this pattern to determine which jars are //considered to be on the container classpath - if (jstlBundle != null) + if (jstlBundle != null) { if (pattern == null) { @@ -125,27 +123,26 @@ public class ContainerTldBundleDiscoverer implements TldBundleDiscoverer } else if (!(pattern.matcher(jstlBundle.getSymbolicName()).matches())) { - String s = tmp+"|"+jstlBundle.getSymbolicName(); + String s = tmp + "|" + jstlBundle.getSymbolicName(); pattern = Pattern.compile(s); deploymentManager.setContextAttribute(OSGiMetaInfConfiguration.CONTAINER_BUNDLE_PATTERN, s); } } - for (Bundle bundle : bundles) { if (sysNames.contains(bundle.getSymbolicName())) - convertBundleLocationToURL(locatorHelper, bundle, urls); + convertBundleLocationToURL(locatorHelper, bundle, urls); else if (pattern != null && pattern.matcher(bundle.getSymbolicName()).matches()) convertBundleLocationToURL(locatorHelper, bundle, urls); } return urls.toArray(new URL[urls.size()]); - } /** * Check that jsp is on the classpath + * * @return true if jsp is available in the environment */ public boolean isJspAvailable() @@ -161,15 +158,13 @@ public class ContainerTldBundleDiscoverer implements TldBundleDiscoverer } return true; } - - + /** - * - * Some versions of JspFactory do Class.forName, which probably won't work in an + * Some versions of JspFactory do Class.forName, which probably won't work in an * OSGi environment. */ - public void fixJspFactory () - { + public void fixJspFactory() + { try { Class servletContextClass = javax.servlet.ServletContext.class; @@ -177,11 +172,11 @@ public class ContainerTldBundleDiscoverer implements TldBundleDiscoverer JspFactory fact = JspFactory.getDefaultFactory(); if (fact == null) { // bug #299733 - // JspFactory does a simple - // Class.getForName("org.apache.jasper.runtime.JspFactoryImpl") - // however its bundles does not import the jasper package - // so it fails. let's help things out: - fact = (JspFactory) JettyBootstrapActivator.class.getClassLoader() + // JspFactory does a simple + // Class.getForName("org.apache.jasper.runtime.JspFactoryImpl") + // however its bundles does not import the jasper package + // so it fails. let's help things out: + fact = (JspFactory)JettyBootstrapActivator.class.getClassLoader() .loadClass(DEFAULT_JSP_FACTORY_IMPL_CLASS).getDeclaredConstructor().newInstance(); JspFactory.setDefaultFactory(fact); } @@ -191,17 +186,17 @@ public class ContainerTldBundleDiscoverer implements TldBundleDiscoverer LOG.warn("Unable to set the JspFactory: jsp support incomplete.", e); } } - - + /** * Find the bundle that contains a jstl implementation class, which assumes that * the jstl taglibs will be inside the same bundle. + * * @return Bundle contains the jstl implementation class */ - public Bundle findJstlBundle () + public Bundle findJstlBundle() { Class jstlClass = null; - + try { jstlClass = JSTLBundleDiscoverer.class.getClassLoader().loadClass(DEFAULT_JSTL_BUNDLE_CLASS); @@ -210,27 +205,22 @@ public class ContainerTldBundleDiscoverer implements TldBundleDiscoverer { LOG.info("jstl not on classpath", e); } - + if (jstlClass != null) //get the bundle containing jstl return FrameworkUtil.getBundle(jstlClass); - + return null; } - + /** * Resolves a bundle that contains tld files as a URL. The URLs are * used by jasper to discover the tld files. - * + * * Support only 2 types of packaging for the bundle: - the bundle is a jar * (recommended for runtime.) - the bundle is a folder and contain jars in * the root and/or in the lib folder (nice for PDE development situations) * Unsupported: the bundle is a jar that embeds more jars. - * - * @param locatorHelper - * @param bundle - * @param urls - * @throws Exception */ private void convertBundleLocationToURL(BundleFileLocatorHelper locatorHelper, Bundle bundle, Set urls) throws Exception { diff --git a/jetty-osgi/jetty-osgi-boot-jsp/src/main/java/org/eclipse/jetty/osgi/boot/jasper/JSTLBundleDiscoverer.java b/jetty-osgi/jetty-osgi-boot-jsp/src/main/java/org/eclipse/jetty/osgi/boot/jasper/JSTLBundleDiscoverer.java index 57f946fa6b9..b702de34a53 100644 --- a/jetty-osgi/jetty-osgi-boot-jsp/src/main/java/org/eclipse/jetty/osgi/boot/jasper/JSTLBundleDiscoverer.java +++ b/jetty-osgi/jetty-osgi-boot-jsp/src/main/java/org/eclipse/jetty/osgi/boot/jasper/JSTLBundleDiscoverer.java @@ -23,7 +23,6 @@ import java.net.URL; import java.util.ArrayList; import java.util.HashSet; import java.util.Set; - import javax.servlet.jsp.JspFactory; import org.eclipse.jetty.deploy.DeploymentManager; @@ -36,9 +35,8 @@ import org.osgi.framework.Bundle; import org.osgi.framework.FrameworkUtil; /** - * * JSTLBundleDiscoverer - * + * * Fix various shortcomings with the way jasper parses the tld files. Plugs the * JSTL tlds assuming that they are packaged with the bundle that contains the * JSTL classes. @@ -50,7 +48,6 @@ import org.osgi.framework.FrameworkUtil; public class JSTLBundleDiscoverer implements TldBundleDiscoverer { private static final Logger LOG = Log.getLogger(JSTLBundleDiscoverer.class); - /** * Default name of a class that belongs to the jstl bundle. From that class @@ -59,15 +56,13 @@ public class JSTLBundleDiscoverer implements TldBundleDiscoverer */ private static String DEFAULT_JSTL_BUNDLE_CLASS = "org.apache.taglibs.standard.tag.el.core.WhenTag"; - - /** * Default jsp factory implementation. Idally jasper is osgified and we can * use services. In the mean time we statically set the jsp factory * implementation. bug #299733 */ private static String DEFAULT_JSP_FACTORY_IMPL_CLASS = "org.apache.jasper.runtime.JspFactoryImpl"; - + private static final Set __tldBundleCache = new HashSet(); public JSTLBundleDiscoverer() @@ -89,15 +84,14 @@ public class JSTLBundleDiscoverer implements TldBundleDiscoverer JspFactory fact = JspFactory.getDefaultFactory(); if (fact == null) { // bug #299733 - // JspFactory does a simple - // Class.getForName("org.apache.jasper.runtime.JspFactoryImpl") - // however its bundles does not import the jasper package - // so it fails. let's help things out: - fact = (JspFactory) JettyBootstrapActivator.class.getClassLoader() + // JspFactory does a simple + // Class.getForName("org.apache.jasper.runtime.JspFactoryImpl") + // however its bundles does not import the jasper package + // so it fails. let's help things out: + fact = (JspFactory)JettyBootstrapActivator.class.getClassLoader() .loadClass(DEFAULT_JSP_FACTORY_IMPL_CLASS).getDeclaredConstructor().newInstance(); JspFactory.setDefaultFactory(fact); } - } catch (Exception e) { @@ -111,15 +105,15 @@ public class JSTLBundleDiscoverer implements TldBundleDiscoverer * such tag-libraries. Please note that it will work if and only if the * bundle is a jar (!) Currently we just hardcode the bundle that contains * the jstl implemenation. - * + * * A workaround when the tld cannot be parsed with this method is to copy * and paste it inside the WEB-INF of the webapplication where it is used. - * + * * Support only 2 types of packaging for the bundle: - the bundle is a jar * (recommended for runtime.) - the bundle is a folder and contain jars in * the root and/or in the lib folder (nice for PDE development situations) * Unsupported: the bundle is a jar that embeds more jars. - * + * * @return array of URLs * @throws Exception In case of errors during resolving TLDs files */ @@ -142,13 +136,13 @@ public class JSTLBundleDiscoverer implements TldBundleDiscoverer { LOG.info("jstl not on classpath", e); } - + if (jstlClass != null) { //get the bundle containing jstl Bundle tldBundle = FrameworkUtil.getBundle(jstlClass); File tldBundleLocation = locatorHelper.getBundleInstallLocation(tldBundle); - + if (tldBundleLocation != null && tldBundleLocation.isDirectory()) { // try to find the jar files inside this folder @@ -169,23 +163,21 @@ public class JSTLBundleDiscoverer implements TldBundleDiscoverer } } } - } else if (tldBundleLocation != null) { urls.add(tldBundleLocation.toURI().toURL()); - + String pattern = (String)deployer.getContextAttribute("org.eclipse.jetty.server.webapp.containerIncludeBundlePattern"); - pattern = (pattern==null?"":pattern); + pattern = (pattern == null ? "" : pattern); if (!pattern.contains(tldBundle.getSymbolicName())) { - pattern += "|"+tldBundle.getSymbolicName(); + pattern += "|" + tldBundle.getSymbolicName(); deployer.setContextAttribute("org.eclipse.jetty.server.webapp.containerIncludeBundlePattern", pattern); } } } - + return urls.toArray(new URL[urls.size()]); } - } diff --git a/jetty-osgi/jetty-osgi-boot-jsp/src/main/java/org/eclipse/jetty/osgi/boot/jsp/FragmentActivator.java b/jetty-osgi/jetty-osgi-boot-jsp/src/main/java/org/eclipse/jetty/osgi/boot/jsp/FragmentActivator.java index e3bcc1617fb..5649086f424 100644 --- a/jetty-osgi/jetty-osgi-boot-jsp/src/main/java/org/eclipse/jetty/osgi/boot/jsp/FragmentActivator.java +++ b/jetty-osgi/jetty-osgi-boot-jsp/src/main/java/org/eclipse/jetty/osgi/boot/jsp/FragmentActivator.java @@ -18,7 +18,6 @@ package org.eclipse.jetty.osgi.boot.jsp; - import org.eclipse.jetty.osgi.boot.internal.serverfactory.ServerInstanceWrapper; import org.eclipse.jetty.osgi.boot.jasper.ContainerTldBundleDiscoverer; import org.osgi.framework.BundleActivator; @@ -26,16 +25,16 @@ import org.osgi.framework.BundleContext; /** * FragmentActivator - * + * * Sets up support for jsp and jstl. All relevant jsp jars must also be installed * into the osgi environment. - *

    + *

    * Note that as this is part of a bundle fragment, this activator is NOT * called by the OSGi environment. Instead, the org.eclipse.jetty.osgi.boot.utils.internal.PackageAdminTracker * simulates fragment activation and causes this class's start() method to * be called. *

    - *

    + *

    * The package of this class MUST match the Bundle-SymbolicName of this fragment * in order for the PackageAdminTracker to find it. *

    @@ -43,7 +42,7 @@ import org.osgi.framework.BundleContext; public class FragmentActivator implements BundleActivator { /** - * + * */ @Override public void start(BundleContext context) throws Exception @@ -51,11 +50,11 @@ public class FragmentActivator implements BundleActivator //set up some classes that will look for bundles with tlds that must be converted //to urls and treated as if they are on the Jetty container's classpath so that //jasper can deal with them - ServerInstanceWrapper.addContainerTldBundleDiscoverer(new ContainerTldBundleDiscoverer()); + ServerInstanceWrapper.addContainerTldBundleDiscoverer(new ContainerTldBundleDiscoverer()); } /** - * + * */ @Override public void stop(BundleContext context) throws Exception diff --git a/jetty-osgi/jetty-osgi-boot-warurl/pom.xml b/jetty-osgi/jetty-osgi-boot-warurl/pom.xml index 27d17622858..025d737ea11 100644 --- a/jetty-osgi/jetty-osgi-boot-warurl/pom.xml +++ b/jetty-osgi/jetty-osgi-boot-warurl/pom.xml @@ -27,15 +27,15 @@ - org.apache.felix - maven-bundle-plugin - true - - - RFC66 War URL - org.eclipse.jetty.osgi.boot.warurl.WarUrlActivator - - + org.apache.felix + maven-bundle-plugin + true + + + RFC66 War URL + org.eclipse.jetty.osgi.boot.warurl.WarUrlActivator + + org.codehaus.mojo diff --git a/jetty-osgi/jetty-osgi-boot-warurl/src/main/java/org/eclipse/jetty/osgi/boot/warurl/WarUrlActivator.java b/jetty-osgi/jetty-osgi-boot-warurl/src/main/java/org/eclipse/jetty/osgi/boot/warurl/WarUrlActivator.java index 39f2c514d61..9383ca9f60a 100644 --- a/jetty-osgi/jetty-osgi-boot-warurl/src/main/java/org/eclipse/jetty/osgi/boot/warurl/WarUrlActivator.java +++ b/jetty-osgi/jetty-osgi-boot-warurl/src/main/java/org/eclipse/jetty/osgi/boot/warurl/WarUrlActivator.java @@ -33,12 +33,12 @@ import org.osgi.service.url.URLStreamHandlerService; */ public class WarUrlActivator implements BundleActivator { - + private ServiceRegistration _reg; /** * Register the url stream handler factory. - * + * * @param context the {@link BundleContext} to use */ @SuppressWarnings("unchecked") @@ -46,11 +46,11 @@ public class WarUrlActivator implements BundleActivator public void start(BundleContext context) throws Exception { Dictionary props = new Hashtable(); - props.put(URLConstants.URL_HANDLER_PROTOCOL,new String[] {"war"}); + props.put(URLConstants.URL_HANDLER_PROTOCOL, new String[]{"war"}); context.registerService(URLStreamHandlerService.class.getName(), - new WarUrlStreamHandler(), props); + new WarUrlStreamHandler(), props); } - + /** * Remove the url stream handler. (probably not required, * as osgi might shutdown every registered service @@ -71,5 +71,4 @@ public class WarUrlActivator implements BundleActivator e.printStackTrace(); } } - } diff --git a/jetty-osgi/jetty-osgi-boot-warurl/src/main/java/org/eclipse/jetty/osgi/boot/warurl/WarUrlStreamHandler.java b/jetty-osgi/jetty-osgi-boot-warurl/src/main/java/org/eclipse/jetty/osgi/boot/warurl/WarUrlStreamHandler.java index 63ba912b3d2..5bc33d7678b 100644 --- a/jetty-osgi/jetty-osgi-boot-warurl/src/main/java/org/eclipse/jetty/osgi/boot/warurl/WarUrlStreamHandler.java +++ b/jetty-osgi/jetty-osgi-boot-warurl/src/main/java/org/eclipse/jetty/osgi/boot/warurl/WarUrlStreamHandler.java @@ -63,18 +63,18 @@ public class WarUrlStreamHandler extends AbstractURLStreamHandlerService } // if (actual.toString().startsWith("file:/") && ! actual.to) - URLConnection ori = (URLConnection) actual.openConnection(); + URLConnection ori = (URLConnection)actual.openConnection(); ori.setDefaultUseCaches(Resource.getDefaultUseCaches()); JarURLConnection jarOri = null; try { if (ori instanceof JarURLConnection) { - jarOri = (JarURLConnection) ori; + jarOri = (JarURLConnection)ori; } else { - jarOri = (JarURLConnection) new URL("jar:" + actual.toString() + "!/").openConnection(); + jarOri = (JarURLConnection)new URL("jar:" + actual.toString() + "!/").openConnection(); jarOri.setDefaultUseCaches(Resource.getDefaultUseCaches()); } Manifest mf = WarBundleManifestGenerator.createBundleManifest(jarOri.getManifest(), url, jarOri.getJarFile()); @@ -83,22 +83,21 @@ public class WarUrlStreamHandler extends AbstractURLStreamHandlerService jarOri.getJarFile().close(); jarOri = null; } - catch (Throwable t) + catch (Throwable ignored) { } return new WarURLConnection(actual, mf); } finally { - if (jarOri != null) try - { - jarOri.getJarFile().close(); - } - catch (Throwable t) - { - } + if (jarOri != null) + try + { + jarOri.getJarFile().close(); + } + catch (Throwable ignored) + { + } } - } - } diff --git a/jetty-osgi/jetty-osgi-boot-warurl/src/main/java/org/eclipse/jetty/osgi/boot/warurl/internal/WarBundleManifestGenerator.java b/jetty-osgi/jetty-osgi-boot-warurl/src/main/java/org/eclipse/jetty/osgi/boot/warurl/internal/WarBundleManifestGenerator.java index 0c257ba182b..6bf48be72d0 100644 --- a/jetty-osgi/jetty-osgi-boot-warurl/src/main/java/org/eclipse/jetty/osgi/boot/warurl/internal/WarBundleManifestGenerator.java +++ b/jetty-osgi/jetty-osgi-boot-warurl/src/main/java/org/eclipse/jetty/osgi/boot/warurl/internal/WarBundleManifestGenerator.java @@ -35,27 +35,28 @@ import org.osgi.framework.Constants; public class WarBundleManifestGenerator { - /** missing version in the url and in the manifest - * use this one. */ + /** + * missing version in the url and in the manifest + * use this one. + */ private static final String MISSING_VERSION = "0.0.1.unknown"; private static final String MISSING_MANIFEST_VERSION = "2"; - + public static Manifest createBundleManifest(Manifest originalManifest, URL url, JarFile jarFile) { Manifest res = new Manifest(); res.getMainAttributes().putAll( - createBundleManifest(originalManifest.getMainAttributes(), - url.toString(), jarFile)); + createBundleManifest(originalManifest.getMainAttributes(), + url.toString(), jarFile)); return res; } - - + private static Attributes createBundleManifest(Attributes originalManifest, String url, JarFile jarFile) { HashMap res = new HashMap(); for (Entry entries : originalManifest.entrySet()) { - res.put(entries.getKey().toString(),String.valueOf(entries.getValue())); + res.put(entries.getKey().toString(), String.valueOf(entries.getValue())); } MultiMap params = parseQueryString(url); //follow RFC66 documentation: @@ -67,13 +68,13 @@ public class WarBundleManifestGenerator } else { - String versionInManifest = (String) res.get(Constants.BUNDLE_VERSION); + String versionInManifest = (String)res.get(Constants.BUNDLE_VERSION); if (versionInManifest == null) { res.put(Constants.BUNDLE_VERSION, MISSING_VERSION); } } - + //#2 Bundle_ManifestVersion String manversion = params.getString(Constants.BUNDLE_MANIFESTVERSION); if (manversion != null) @@ -83,20 +84,20 @@ public class WarBundleManifestGenerator else { int manv = 2; - try { - String versionInManifest = (String) res.get(Constants.BUNDLE_MANIFESTVERSION); + try + { + String versionInManifest = (String)res.get(Constants.BUNDLE_MANIFESTVERSION); if (versionInManifest != null) { manv = Integer.parseInt(versionInManifest.trim()); } } - catch (NumberFormatException nfe) + catch (NumberFormatException ignored) { - } - res.put(Constants.BUNDLE_MANIFESTVERSION, String.valueOf( manv < 2 ? 2 : manv )); + res.put(Constants.BUNDLE_MANIFESTVERSION, String.valueOf(manv < 2 ? 2 : manv)); } - + //#3 Bundle-SymbolicName String symbname = params.getString(Constants.BUNDLE_SYMBOLICNAME); if (symbname != null) @@ -105,7 +106,7 @@ public class WarBundleManifestGenerator } else { - symbname = (String) res.get(Constants.BUNDLE_SYMBOLICNAME); + symbname = (String)res.get(Constants.BUNDLE_SYMBOLICNAME); if (symbname == null) { //derive the symbolic name from the url. @@ -119,12 +120,12 @@ public class WarBundleManifestGenerator beforeQueryString = url.length(); } } - symbname = url.substring(lastSlash+1, beforeQueryString); + symbname = url.substring(lastSlash + 1, beforeQueryString); //todo: something better probably. res.put(Constants.BUNDLE_SYMBOLICNAME, symbname); } } - + //#4 Bundle-Classpath String extraBundleClasspath = params.getString(Constants.BUNDLE_CLASSPATH); String alreadyBundleClasspath = res.get(Constants.BUNDLE_CLASSPATH); @@ -153,40 +154,40 @@ public class WarBundleManifestGenerator } alreadyBundleClasspath = bundleClasspath.toString(); } - + //if there is already a manifest and it specifies the Bundle-Classpath. //for now let's trust that one. //please note that the draft of the spec implies that we should be parsing the existing //header and merge it with the missing stuff so this does not follow the spec yet. - + res.put(Constants.BUNDLE_CLASSPATH, - alreadyBundleClasspath + (extraBundleClasspath == null ? "" : "," + extraBundleClasspath )); - + alreadyBundleClasspath + (extraBundleClasspath == null ? "" : "," + extraBundleClasspath)); + //#5 Import-Package String extraImportPackage = params.getString(Constants.IMPORT_PACKAGE); String alreadyImportPackage = res.get(Constants.IMPORT_PACKAGE); if (alreadyImportPackage == null) - {//The spec does not specify that the jsp imports are optional - //kind of nice to have them optional so we can run simple wars in - //simple environments. + { + //The spec does not specify that the jsp imports are optional + //kind of nice to have them optional so we can run simple wars in + //simple environments. alreadyImportPackage = "javax.servlet; version=\"2.5\"," + - "javax.servlet.http;version=\"2.5\"," + - "javax.el;version=\"1.0\"" + - "javax.jsp;version=\"2.1\";resolution:=optional," + - "javax.jsp.tagext;version=\"2.1\";resolution:=optional"; - + "javax.servlet.http;version=\"2.5\"," + + "javax.el;version=\"1.0\"" + + "javax.jsp;version=\"2.1\";resolution:=optional," + + "javax.jsp.tagext;version=\"2.1\";resolution:=optional"; } if (extraImportPackage != null) { //if there is already a manifest and it specifies the Bundle-Classpath. //for now let's trust that one. //please note that the draft of the spec implies that we should be parsing the existing //header and merge it with the missing stuff so this does not follow the spec yet. - + res.put(Constants.IMPORT_PACKAGE, - (alreadyImportPackage == null ? "" : alreadyImportPackage + ",") + + (alreadyImportPackage == null ? "" : alreadyImportPackage + ",") + extraImportPackage); } - + //#6 Export-Package String extraExportPackage = params.getString(Constants.EXPORT_PACKAGE); String alreadyExportPackage = res.get(Constants.EXPORT_PACKAGE); @@ -196,10 +197,10 @@ public class WarBundleManifestGenerator //please note that the draft of the spec implies that we should be parsing the existing //header and merge it with the missing stuff so this does not follow the spec yet. res.put(Constants.EXPORT_PACKAGE, - (alreadyExportPackage == null ? "" : alreadyExportPackage + ",") + + (alreadyExportPackage == null ? "" : alreadyExportPackage + ",") + extraImportPackage); } - + //#7 Web-ContextPath String webContextPath = params.getString("Web-ContextPath"); if (webContextPath != null) @@ -214,7 +215,7 @@ public class WarBundleManifestGenerator //we choose to use the symbolic name as the default context path. if (symbname.endsWith(".war")) { - webContextPath = "/" + symbname.substring(0, symbname.length()-".war".length()); + webContextPath = "/" + symbname.substring(0, symbname.length() - ".war".length()); } else { @@ -223,7 +224,7 @@ public class WarBundleManifestGenerator res.put("Web-ContextPath", webContextPath); } } - + //#8 Web-JSPExtractLocation String jspExtractLocation = params.getString("Web-JSPExtractLocation"); if (jspExtractLocation != null) @@ -235,14 +236,13 @@ public class WarBundleManifestGenerator //nothing to do. } Attributes newAttrs = new Attributes(); - for (Entry e : res.entrySet()) + for (Entry e : res.entrySet()) { - newAttrs.putValue(e.getKey(),e.getValue()); + newAttrs.putValue(e.getKey(), e.getValue()); } return newAttrs; } - - + /** * @return The key values pairs that are in the query string of this url. */ @@ -259,11 +259,11 @@ public class WarBundleManifestGenerator { poundIndex = url.length(); } - UrlEncoded.decodeUtf8To(url, questionMarkIndex+1, - poundIndex - questionMarkIndex - 1, res); + UrlEncoded.decodeUtf8To(url, questionMarkIndex + 1, + poundIndex - questionMarkIndex - 1, res); return res; } - + private static List getJarsInWebInfLib(JarFile jarFile) { List res = new ArrayList(); @@ -278,6 +278,4 @@ public class WarBundleManifestGenerator } return res; } - - } diff --git a/jetty-osgi/jetty-osgi-boot-warurl/src/main/java/org/eclipse/jetty/osgi/boot/warurl/internal/WarURLConnection.java b/jetty-osgi/jetty-osgi-boot-warurl/src/main/java/org/eclipse/jetty/osgi/boot/warurl/internal/WarURLConnection.java index e1b4b2196b0..f9502a4251e 100644 --- a/jetty-osgi/jetty-osgi-boot-warurl/src/main/java/org/eclipse/jetty/osgi/boot/warurl/internal/WarURLConnection.java +++ b/jetty-osgi/jetty-osgi-boot-warurl/src/main/java/org/eclipse/jetty/osgi/boot/warurl/internal/WarURLConnection.java @@ -50,13 +50,14 @@ public class WarURLConnection extends URLConnection /** * Use PipedOuputStream and PipedInputStream to do the transformation without making * a new temporary file ust to replace the manifest. + * * @param newmanifest The new manifest * @param rawIn The file input stream or equivalent. not the jar input stream. - * @throws IOException if an I/O error occurs. * @return InputStream of the replaced manifest file + * @throws IOException if an I/O error occurs. */ public static InputStream substitueManifest(final Manifest newmanifest, - final InputStream rawIn) throws IOException + final InputStream rawIn) throws IOException { final PipedOutputStream pOut = new PipedOutputStream(); PipedInputStream pIn = new PipedInputStream(pOut); @@ -81,18 +82,21 @@ public class WarURLConnection extends URLConnection dest.putNextEntry(next); if (next.getSize() > 0) { - IO.copy(jin,dest,next.getSize()); + IO.copy(jin, dest, next.getSize()); } next = jin.getNextJarEntry(); } } - catch (IOException ioe) { + catch (IOException ioe) + { ioe.printStackTrace(); } finally { - if (dest != null) IO.close(dest); - if (jin != null) IO.close(jin); + if (dest != null) + IO.close(dest); + if (jin != null) + IO.close(jin); IO.close(pOut); } } @@ -101,10 +105,10 @@ public class WarURLConnection extends URLConnection th.start(); return pIn; } - + private Manifest _mf; private URLConnection _conn; - + /** * @param url The file url (for example) * @param mf The manifest to use as a replacement to the jar file inside @@ -118,12 +122,12 @@ public class WarURLConnection extends URLConnection _conn.setDefaultUseCaches(Resource.getDefaultUseCaches()); _mf = mf; } + @Override public void connect() throws IOException { _conn.connect(); } - @Override public InputStream getInputStream() throws IOException @@ -134,7 +138,7 @@ public class WarURLConnection extends URLConnection @Override public void addRequestProperty(String key, String value) { - _conn.addRequestProperty(key,value); + _conn.addRequestProperty(key, value); } @Override @@ -228,15 +232,15 @@ public class WarURLConnection extends URLConnection } @Override - public long getHeaderFieldDate(String name, long Default) + public long getHeaderFieldDate(String name, long defaultVal) { - return _conn.getHeaderFieldDate(name,Default); + return _conn.getHeaderFieldDate(name, defaultVal); } @Override - public int getHeaderFieldInt(String name, int Default) + public int getHeaderFieldInt(String name, int defaultVal) { - return _conn.getHeaderFieldInt(name,Default); + return _conn.getHeaderFieldInt(name, defaultVal); } @Override @@ -350,7 +354,7 @@ public class WarURLConnection extends URLConnection @Override public void setRequestProperty(String key, String value) { - _conn.setRequestProperty(key,value); + _conn.setRequestProperty(key, value); } @Override @@ -358,7 +362,4 @@ public class WarURLConnection extends URLConnection { _conn.setUseCaches(usecaches); } - - - } diff --git a/jetty-osgi/jetty-osgi-boot/pom.xml b/jetty-osgi/jetty-osgi-boot/pom.xml index 73ec559a965..443fe24c095 100644 --- a/jetty-osgi/jetty-osgi-boot/pom.xml +++ b/jetty-osgi/jetty-osgi-boot/pom.xml @@ -13,10 +13,10 @@ ${project.groupId}.boot - - org.eclipse.jetty - jetty-annotations - + + org.eclipse.jetty + jetty-annotations + org.eclipse.jetty jetty-webapp @@ -39,80 +39,58 @@ - - - - maven-antrun-plugin - - - process-resources - - - - - - - - - - - - run - - - - - - org.apache.felix - maven-bundle-plugin - true - - - org.eclipse.jetty.osgi.boot;singleton:=true - org.eclipse.jetty.osgi.boot.JettyBootstrapActivator - org.eclipse.jetty.*;version="[$(version;===;${parsedVersion.osgiVersion}),$(version;==+;${parsedVersion.osgiVersion}))" - javax.mail;version="1.4.0";resolution:=optional, - javax.mail.event;version="1.4.0";resolution:=optional, - javax.mail.internet;version="1.4.0";resolution:=optional, - javax.mail.search;version="1.4.0";resolution:=optional, - javax.mail.util;version="1.4.0";resolution:=optional, - javax.servlet;version="[3.1,4.1)", - javax.servlet.http;version="[3.1,4.1)", - javax.transaction;version="1.1.0";resolution:=optional, - javax.transaction.xa;version="1.1.0";resolution:=optional, - org.objectweb.asm;version="5";resolution:=optional, - org.osgi.framework, - org.osgi.service.cm;version="1.2.0", - org.osgi.service.packageadmin, - org.osgi.service.startlevel;version="1.0.0", - org.osgi.service.url;version="1.0.0", - org.osgi.util.tracker;version="1.3.0", - org.slf4j;resolution:=optional, - org.slf4j.spi;resolution:=optional, - org.slf4j.helpers;resolution:=optional, - org.xml.sax, - org.xml.sax.helpers, - org.eclipse.jetty.annotations;resolution:=optional, - * - - - osgi.extender; filter:="(osgi.extender=osgi.serviceloader.registrar)" - - - osgi.serviceloader; osgi.serviceloader=org.eclipse.jetty.webapp.Configuration - - <_nouses>true - - - - - org.codehaus.mojo - findbugs-maven-plugin - - org.eclipse.jetty.osgi.boot.* - - - - + + + + maven-antrun-plugin + + + process-resources + + + + + + + + + + + + run + + + + + + org.apache.felix + maven-bundle-plugin + true + + + org.eclipse.jetty.osgi.boot;singleton:=true + org.eclipse.jetty.osgi.boot.JettyBootstrapActivator + org.eclipse.jetty.*;version="[$(version;===;${parsedVersion.osgiVersion}),$(version;==+;${parsedVersion.osgiVersion}))" + javax.mail;version="1.4.0";resolution:=optional, javax.mail.event;version="1.4.0";resolution:=optional, javax.mail.internet;version="1.4.0";resolution:=optional, javax.mail.search;version="1.4.0";resolution:=optional, javax.mail.util;version="1.4.0";resolution:=optional, javax.servlet;version="[3.1,4.1)", javax.servlet.http;version="[3.1,4.1)", javax.transaction;version="1.1.0";resolution:=optional, javax.transaction.xa;version="1.1.0";resolution:=optional, org.objectweb.asm;version="5";resolution:=optional, org.osgi.framework, org.osgi.service.cm;version="1.2.0", org.osgi.service.packageadmin, org.osgi.service.startlevel;version="1.0.0", org.osgi.service.url;version="1.0.0", org.osgi.util.tracker;version="1.3.0", org.slf4j;resolution:=optional, org.slf4j.spi;resolution:=optional, org.slf4j.helpers;resolution:=optional, org.xml.sax, org.xml.sax.helpers, org.eclipse.jetty.annotations;resolution:=optional, * + + + osgi.extender; filter:="(osgi.extender=osgi.serviceloader.registrar)" + + + osgi.serviceloader; osgi.serviceloader=org.eclipse.jetty.webapp.Configuration + + <_nouses>true + + + + + org.codehaus.mojo + findbugs-maven-plugin + + org.eclipse.jetty.osgi.boot.* + + + +
    diff --git a/jetty-osgi/jetty-osgi-boot/src/main/java/org/eclipse/jetty/osgi/annotations/AnnotationConfiguration.java b/jetty-osgi/jetty-osgi-boot/src/main/java/org/eclipse/jetty/osgi/annotations/AnnotationConfiguration.java index 19f3ed86964..c70a9e7008f 100644 --- a/jetty-osgi/jetty-osgi-boot/src/main/java/org/eclipse/jetty/osgi/annotations/AnnotationConfiguration.java +++ b/jetty-osgi/jetty-osgi-boot/src/main/java/org/eclipse/jetty/osgi/annotations/AnnotationConfiguration.java @@ -39,16 +39,16 @@ import org.osgi.framework.Constants; /** * Extend the AnnotationConfiguration to support OSGi: * Look for annotations inside WEB-INF/lib and also in the fragments and required bundles. - * Discover them using a scanner adapted to OSGi instead of the jarscanner. + * Discover them using a scanner adapted to OSGi instead of the jarscanner. */ public class AnnotationConfiguration extends org.eclipse.jetty.annotations.AnnotationConfiguration { private static final Logger LOG = Log.getLogger(org.eclipse.jetty.annotations.AnnotationConfiguration.class); - + public class BundleParserTask extends ParserTask { - - public BundleParserTask (AnnotationParser parser, Sethandlers, Resource resource) + + public BundleParserTask(AnnotationParser parser, Set handlers, Resource resource) { super(parser, handlers, resource); } @@ -62,19 +62,18 @@ public class AnnotationConfiguration extends org.eclipse.jetty.annotations.Annot Bundle bundle = osgiAnnotationParser.getBundle(_resource); if (_stat != null) _stat.start(); - osgiAnnotationParser.parse(_handlers, bundle); + osgiAnnotationParser.parse(_handlers, bundle); if (_stat != null) _stat.end(); } return null; } } - - + public AnnotationConfiguration() { } - + /** * This parser scans the bundles using the OSGi APIs instead of assuming a jar. */ @@ -83,14 +82,14 @@ public class AnnotationConfiguration extends org.eclipse.jetty.annotations.Annot { return new AnnotationParser(javaTargetVersion); } - + @Override public Resource getJarFor(ServletContainerInitializer service) throws MalformedURLException, IOException { Resource resource = super.getJarFor(service); // TODO This is not correct, but implemented like this to be bug for bug compatible // with previous implementation that could only handle actual jars and not bundles. - if (resource!=null && !resource.toString().endsWith(".jar")) + if (resource != null && !resource.toString().endsWith(".jar")) return null; return resource; } @@ -106,15 +105,15 @@ public class AnnotationConfiguration extends org.eclipse.jetty.annotations.Annot * */ @Override - public void parseWebInfLib (WebAppContext context, org.eclipse.jetty.annotations.AnnotationParser parser) - throws Exception + public void parseWebInfLib(WebAppContext context, org.eclipse.jetty.annotations.AnnotationParser parser) + throws Exception { AnnotationParser oparser = (AnnotationParser)parser; if (_webInfLibStats == null) _webInfLibStats = new CounterStatistic(); - - Bundle webbundle = (Bundle) context.getAttribute(OSGiWebappConstants.JETTY_OSGI_BUNDLE); + + Bundle webbundle = (Bundle)context.getAttribute(OSGiWebappConstants.JETTY_OSGI_BUNDLE); @SuppressWarnings("unchecked") Set fragAndRequiredBundles = (Set)context.getAttribute(OSGiMetaInfConfiguration.FRAGMENT_AND_REQUIRED_BUNDLES); if (fragAndRequiredBundles != null) @@ -125,28 +124,28 @@ public class AnnotationConfiguration extends org.eclipse.jetty.annotations.Annot //skip bundles that have been uninstalled since we discovered them if (bundle.getState() == Bundle.UNINSTALLED) continue; - + Resource bundleRes = oparser.indexBundle(bundle); if (!context.getMetaData().getWebInfJars().contains(bundleRes)) { context.getMetaData().addWebInfJar(bundleRes); } - + if (bundle.getHeaders().get(Constants.FRAGMENT_HOST) != null) { //a fragment indeed: - parseFragmentBundle(context,oparser,webbundle,bundle); + parseFragmentBundle(context, oparser, webbundle, bundle); _webInfLibStats.increment(); } } } //scan ourselves oparser.indexBundle(webbundle); - parseWebBundle(context,oparser,webbundle); + parseWebBundle(context, oparser, webbundle); _webInfLibStats.increment(); - + //scan the WEB-INF/lib - super.parseWebInfLib(context,parser); + super.parseWebInfLib(context, parser); if (fragAndRequiredBundles != null) { //scan the required bundles @@ -155,19 +154,20 @@ public class AnnotationConfiguration extends org.eclipse.jetty.annotations.Annot //skip bundles that have been uninstalled since we discovered them if (requiredBundle.getState() == Bundle.UNINSTALLED) continue; - + if (requiredBundle.getHeaders().get(Constants.FRAGMENT_HOST) == null) { //a bundle indeed: - parseRequiredBundle(context,oparser,webbundle,requiredBundle); + parseRequiredBundle(context, oparser, webbundle, requiredBundle); _webInfLibStats.increment(); } } } } - + /** * Scan a fragment bundle for servlet annotations + * * @param context The webapp context * @param parser The parser * @param webbundle The current webbundle @@ -175,35 +175,33 @@ public class AnnotationConfiguration extends org.eclipse.jetty.annotations.Annot * @throws Exception if unable to parse fragment bundle */ protected void parseFragmentBundle(WebAppContext context, AnnotationParser parser, - Bundle webbundle, Bundle fragmentBundle) throws Exception + Bundle webbundle, Bundle fragmentBundle) throws Exception { - parseBundle(context,parser,webbundle,fragmentBundle); + parseBundle(context, parser, webbundle, fragmentBundle); } - + /** * Scan a bundle required by the webbundle for servlet annotations + * * @param context The webapp context * @param parser The parser * @param webbundle The current webbundle * @throws Exception if unable to parse the web bundle */ protected void parseWebBundle(WebAppContext context, AnnotationParser parser, Bundle webbundle) - throws Exception + throws Exception { - parseBundle(context,parser,webbundle,webbundle); + parseBundle(context, parser, webbundle, webbundle); } - - - - - /** + + /** * @see org.eclipse.jetty.annotations.AnnotationConfiguration#parseWebInfClasses(org.eclipse.jetty.webapp.WebAppContext, org.eclipse.jetty.annotations.AnnotationParser) */ @Override public void parseWebInfClasses(WebAppContext context, org.eclipse.jetty.annotations.AnnotationParser parser) - throws Exception + throws Exception { - Bundle webbundle = (Bundle) context.getAttribute(OSGiWebappConstants.JETTY_OSGI_BUNDLE); + Bundle webbundle = (Bundle)context.getAttribute(OSGiWebappConstants.JETTY_OSGI_BUNDLE); String bundleClasspath = (String)webbundle.getHeaders().get(Constants.BUNDLE_CLASSPATH); //only scan WEB-INF/classes if we didn't already scan it with parseWebBundle if (StringUtil.isBlank(bundleClasspath) || !bundleClasspath.contains("WEB-INF/classes")) @@ -212,6 +210,7 @@ public class AnnotationConfiguration extends org.eclipse.jetty.annotations.Annot /** * Scan a bundle required by the webbundle for servlet annotations + * * @param context The webapp context * @param parser The parser * @param webbundle The current webbundle @@ -219,16 +218,16 @@ public class AnnotationConfiguration extends org.eclipse.jetty.annotations.Annot * @throws Exception if unable to parse the required bundle */ protected void parseRequiredBundle(WebAppContext context, AnnotationParser parser, - Bundle webbundle, Bundle requiredBundle) throws Exception + Bundle webbundle, Bundle requiredBundle) throws Exception { - parseBundle(context,parser,webbundle,requiredBundle); + parseBundle(context, parser, webbundle, requiredBundle); } - + protected void parseBundle(WebAppContext context, AnnotationParser parser, Bundle webbundle, Bundle bundle) throws Exception - { + { - Resource bundleRes = parser.getResource(bundle); + Resource bundleRes = parser.getResource(bundle); Set handlers = new HashSet<>(); handlers.addAll(_discoverableAnnotationHandlers); if (_classInheritanceHandler != null) @@ -243,5 +242,4 @@ public class AnnotationConfiguration extends org.eclipse.jetty.annotations.Annot task.setStatistic(new TimeStatistic()); } } - } diff --git a/jetty-osgi/jetty-osgi-boot/src/main/java/org/eclipse/jetty/osgi/annotations/AnnotationParser.java b/jetty-osgi/jetty-osgi-boot/src/main/java/org/eclipse/jetty/osgi/annotations/AnnotationParser.java index d520cb8316e..c457149301c 100644 --- a/jetty-osgi/jetty-osgi-boot/src/main/java/org/eclipse/jetty/osgi/annotations/AnnotationParser.java +++ b/jetty-osgi/jetty-osgi-boot/src/main/java/org/eclipse/jetty/osgi/annotations/AnnotationParser.java @@ -37,25 +37,25 @@ import org.osgi.framework.Bundle; import org.osgi.framework.Constants; /** - * + * */ public class AnnotationParser extends org.eclipse.jetty.annotations.AnnotationParser { private Set _alreadyParsed = ConcurrentHashMap.newKeySet(); - - private ConcurrentHashMap _uriToBundle = new ConcurrentHashMap<>(); - private ConcurrentHashMap _bundleToResource = new ConcurrentHashMap<>(); + + private ConcurrentHashMap _uriToBundle = new ConcurrentHashMap<>(); + private ConcurrentHashMap _bundleToResource = new ConcurrentHashMap<>(); private ConcurrentHashMap _resourceToBundle = new ConcurrentHashMap<>(); - private ConcurrentHashMap _bundleToUri = new ConcurrentHashMap<>(); - + private ConcurrentHashMap _bundleToUri = new ConcurrentHashMap<>(); + public AnnotationParser(int javaPlatform) { super(javaPlatform, Opcodes.ASM7); } - + /** * Keep track of a jetty URI Resource and its associated OSGi bundle. - * + * * @param bundle the bundle to index * @return the resource for the bundle * @throws Exception if unable to create the resource reference @@ -65,32 +65,34 @@ public class AnnotationParser extends org.eclipse.jetty.annotations.AnnotationPa File bundleFile = BundleFileLocatorHelperFactory.getFactory().getHelper().getBundleInstallLocation(bundle); Resource resource = Resource.newResource(bundleFile.toURI()); URI uri = resource.getURI(); - _uriToBundle.putIfAbsent(uri,bundle); - _bundleToUri.putIfAbsent(bundle,uri); - _bundleToResource.putIfAbsent(bundle,resource); - _resourceToBundle.putIfAbsent(resource,bundle); + _uriToBundle.putIfAbsent(uri, bundle); + _bundleToUri.putIfAbsent(bundle, uri); + _bundleToResource.putIfAbsent(bundle, resource); + _resourceToBundle.putIfAbsent(resource, bundle); return resource; } + protected URI getURI(Bundle bundle) { return _bundleToUri.get(bundle); } + protected Resource getResource(Bundle bundle) { return _bundleToResource.get(bundle); } - protected Bundle getBundle (Resource resource) + + protected Bundle getBundle(Resource resource) { return _resourceToBundle.get(resource); } - - + /** - * + * */ @Override - public void parse (Set handlers, URI[] uris) - throws Exception + public void parse(Set handlers, URI[] uris) + throws Exception { for (URI uri : uris) { @@ -103,7 +105,7 @@ public class AnnotationParser extends org.eclipse.jetty.annotations.AnnotationPa } //a jar in WEB-INF/lib or the WEB-INF/classes //use the behavior of the super class for a standard jar. - super.parse(handlers, new URI[] {uri}); + super.parse(handlers, new URI[]{uri}); } else { @@ -111,16 +113,16 @@ public class AnnotationParser extends org.eclipse.jetty.annotations.AnnotationPa } } } - + protected void parse(Set handlers, Bundle bundle) - throws Exception + throws Exception { URI uri = _bundleToUri.get(bundle); if (!_alreadyParsed.add(uri)) { return; } - + String bundleClasspath = (String)bundle.getHeaders().get(Constants.BUNDLE_CLASSPATH); if (bundleClasspath == null) { @@ -128,20 +130,20 @@ public class AnnotationParser extends org.eclipse.jetty.annotations.AnnotationPa } //order the paths first by the number of tokens in the path second alphabetically. TreeSet paths = new TreeSet<>( - new Comparator() + new Comparator() + { + @Override + public int compare(String o1, String o2) { - @Override - public int compare(String o1, String o2) + int paths1 = new StringTokenizer(o1, "/", false).countTokens(); + int paths2 = new StringTokenizer(o2, "/", false).countTokens(); + if (paths1 == paths2) { - int paths1 = new StringTokenizer(o1,"/",false).countTokens(); - int paths2 = new StringTokenizer(o2,"/",false).countTokens(); - if (paths1 == paths2) - { - return o1.compareTo(o2); - } - return paths2 - paths1; + return o1.compareTo(o2); } - }); + return paths2 - paths1; + } + }); boolean hasDotPath = false; StringTokenizer tokenizer = new StringTokenizer(bundleClasspath, ",;", false); while (tokenizer.hasMoreTokens()) @@ -157,7 +159,7 @@ public class AnnotationParser extends org.eclipse.jetty.annotations.AnnotationPa } else if (!token.endsWith(".jar") && !token.endsWith("/")) { - paths.add(token+"/"); + paths.add(token + "/"); } else { @@ -179,14 +181,14 @@ public class AnnotationParser extends org.eclipse.jetty.annotations.AnnotationPa } } @SuppressWarnings("rawtypes") - Enumeration classes = bundle.findEntries("/","*.class",true); + Enumeration classes = bundle.findEntries("/", "*.class", true); if (classes == null) { return; } while (classes.hasMoreElements()) { - URL classUrl = (URL) classes.nextElement(); + URL classUrl = (URL)classes.nextElement(); String path = classUrl.getPath(); //remove the longest path possible: String name = null; diff --git a/jetty-osgi/jetty-osgi-boot/src/main/java/org/eclipse/jetty/osgi/boot/AbstractContextProvider.java b/jetty-osgi/jetty-osgi-boot/src/main/java/org/eclipse/jetty/osgi/boot/AbstractContextProvider.java index 896f6e85edf..d52f5ff4a47 100644 --- a/jetty-osgi/jetty-osgi-boot/src/main/java/org/eclipse/jetty/osgi/boot/AbstractContextProvider.java +++ b/jetty-osgi/jetty-osgi-boot/src/main/java/org/eclipse/jetty/osgi/boot/AbstractContextProvider.java @@ -37,92 +37,82 @@ import org.eclipse.jetty.util.resource.Resource; import org.eclipse.jetty.xml.XmlConfiguration; import org.osgi.framework.Bundle; - - - /** * AbstractContextProvider * - * Base class for DeploymentManager Providers that can deploy ContextHandlers into + * Base class for DeploymentManager Providers that can deploy ContextHandlers into * Jetty that have been discovered via OSGI either as bundles or services. - * */ public abstract class AbstractContextProvider extends AbstractLifeCycle implements AppProvider { private static final Logger LOG = Log.getLogger(AbstractContextProvider.class); - - private DeploymentManager _deploymentManager; - + + private DeploymentManager _deploymentManager; + private ServerInstanceWrapper _serverWrapper; - - - - - /* ------------------------------------------------------------ */ + /** * OSGiApp - * - * */ public class OSGiApp extends AbstractOSGiApp { private String _contextFile; private ContextHandler _contextHandler; private boolean _configured = false; - + public OSGiApp(DeploymentManager manager, AppProvider provider, String originId, Bundle bundle, String contextFile) { super(manager, provider, bundle, originId); _contextFile = contextFile; } - + public OSGiApp(DeploymentManager manager, AppProvider provider, Bundle bundle, Dictionary properties, String contextFile, String originId) { super(manager, provider, bundle, properties, originId); _contextFile = contextFile; } - - public String getContextFile () + + public String getContextFile() { return _contextFile; } - + public void setHandler(ContextHandler h) { _contextHandler = h; } - + public ContextHandler createContextHandler() - throws Exception + throws Exception { configureContextHandler(); return _contextHandler; } public void configureContextHandler() - throws Exception + throws Exception { if (_configured) return; _configured = true; - + //Override for bundle root may have been set String bundleOverrideLocation = (String)_properties.get(OSGiWebappConstants.JETTY_BUNDLE_INSTALL_LOCATION_OVERRIDE); //Location on filesystem of bundle or the bundle override location File bundleLocation = BundleFileLocatorHelperFactory.getFactory().getHelper().getBundleInstallLocation(_bundle); - File root = (bundleOverrideLocation==null?bundleLocation:new File(bundleOverrideLocation)); + File root = (bundleOverrideLocation == null ? bundleLocation : new File(bundleOverrideLocation)); Resource rootResource = Resource.newResource(BundleFileLocatorHelperFactory.getFactory().getHelper().getLocalURL(root.toURI().toURL())); - + //try and make sure the rootResource is useable - if its a jar then make it a jar file url - if (rootResource.exists()&& !rootResource.isDirectory() && !rootResource.toString().startsWith("jar:")) + if (rootResource.exists() && !rootResource.isDirectory() && !rootResource.toString().startsWith("jar:")) { - Resource jarResource = JarResource.newJarResource(rootResource); - if (jarResource.exists() && jarResource.isDirectory()) - rootResource = jarResource; + Resource jarResource = JarResource.newJarResource(rootResource); + if (jarResource.exists() && jarResource.isDirectory()) + rootResource = jarResource; } - + //Set the base resource of the ContextHandler, if not already set, can also be overridden by the context xml file if (_contextHandler != null && _contextHandler.getBaseResource() == null) { @@ -137,39 +127,39 @@ public abstract class AbstractContextProvider extends AbstractLifeCycle implemen throw new IllegalStateException("No context file or ContextHandler"); if (_contextFile != null) - { + { //apply the contextFile, creating the ContextHandler, the DeploymentManager will register it in the ContextHandlerCollection Resource res = null; - + String jettyHome = (String)getServerInstanceWrapper().getServer().getAttribute(OSGiServerConstants.JETTY_HOME); if (jettyHome == null) - jettyHome = System.getProperty(OSGiServerConstants.JETTY_HOME); - + jettyHome = System.getProperty(OSGiServerConstants.JETTY_HOME); + res = findFile(_contextFile, jettyHome, bundleOverrideLocation, _bundle); //apply the context xml file, either to an existing ContextHandler, or letting the //it create the ContextHandler as necessary if (res != null) - { + { ClassLoader cl = Thread.currentThread().getContextClassLoader(); LOG.debug("Context classloader = " + cl); try { Thread.currentThread().setContextClassLoader(classLoader); - + XmlConfiguration xmlConfiguration = new XmlConfiguration(res); HashMap properties = new HashMap(); //put the server instance in properties.put("Server", getServerInstanceWrapper().getServer()); //put in the location of the bundle root properties.put(OSGiWebappConstants.JETTY_BUNDLE_ROOT, rootResource.toString()); - + // insert the bundle's location as a property. xmlConfiguration.getProperties().putAll(properties); if (_contextHandler == null) - _contextHandler = (ContextHandler) xmlConfiguration.configure(); + _contextHandler = (ContextHandler)xmlConfiguration.configure(); else xmlConfiguration.configure(_contextHandler); } @@ -182,51 +172,43 @@ public abstract class AbstractContextProvider extends AbstractLifeCycle implemen //Set up the class loader we created _contextHandler.setClassLoader(classLoader); - - + //If a bundle/service property specifies context path, let it override the context xml String contextPath = (String)_properties.get(OSGiWebappConstants.RFC66_WEB_CONTEXTPATH); if (contextPath != null) - _contextHandler.setContextPath(contextPath); - + _contextHandler.setContextPath(contextPath); + //osgi Enterprise Spec r4 p.427 _contextHandler.setAttribute(OSGiWebappConstants.OSGI_BUNDLECONTEXT, _bundle.getBundleContext()); - + //make sure we protect also the osgi dirs specified by OSGi Enterprise spec String[] targets = _contextHandler.getProtectedTargets(); - int length = (targets==null?0:targets.length); - + int length = (targets == null ? 0 : targets.length); + String[] updatedTargets = null; if (targets != null) { - updatedTargets = new String[length+OSGiWebappConstants.DEFAULT_PROTECTED_OSGI_TARGETS.length]; + updatedTargets = new String[length + OSGiWebappConstants.DEFAULT_PROTECTED_OSGI_TARGETS.length]; System.arraycopy(targets, 0, updatedTargets, 0, length); - } else updatedTargets = new String[OSGiWebappConstants.DEFAULT_PROTECTED_OSGI_TARGETS.length]; System.arraycopy(OSGiWebappConstants.DEFAULT_PROTECTED_OSGI_TARGETS, 0, updatedTargets, length, OSGiWebappConstants.DEFAULT_PROTECTED_OSGI_TARGETS.length); _contextHandler.setProtectedTargets(updatedTargets); - } - } - - /* ------------------------------------------------------------ */ + public AbstractContextProvider(ServerInstanceWrapper wrapper) { _serverWrapper = wrapper; } - - - /* ------------------------------------------------------------ */ + public ServerInstanceWrapper getServerInstanceWrapper() { return _serverWrapper; } - - /* ------------------------------------------------------------ */ - /** + + /** * @see org.eclipse.jetty.deploy.AppProvider#createContextHandler(org.eclipse.jetty.deploy.App) */ @Override @@ -235,21 +217,19 @@ public abstract class AbstractContextProvider extends AbstractLifeCycle implemen if (app == null) return null; if (!(app instanceof OSGiApp)) - throw new IllegalStateException(app+" is not a BundleApp"); - + throw new IllegalStateException(app + " is not a BundleApp"); + //Create a ContextHandler suitable to deploy in OSGi - ContextHandler h = ((OSGiApp)app).createContextHandler(); + ContextHandler h = ((OSGiApp)app).createContextHandler(); return h; } - - /* ------------------------------------------------------------ */ + @Override public void setDeploymentManager(DeploymentManager deploymentManager) { _deploymentManager = deploymentManager; } - - /* ------------------------------------------------------------ */ + public DeploymentManager getDeploymentManager() { return _deploymentManager; diff --git a/jetty-osgi/jetty-osgi-boot/src/main/java/org/eclipse/jetty/osgi/boot/AbstractOSGiApp.java b/jetty-osgi/jetty-osgi-boot/src/main/java/org/eclipse/jetty/osgi/boot/AbstractOSGiApp.java index 6d1785f1060..1db95bb2df3 100644 --- a/jetty-osgi/jetty-osgi-boot/src/main/java/org/eclipse/jetty/osgi/boot/AbstractOSGiApp.java +++ b/jetty-osgi/jetty-osgi-boot/src/main/java/org/eclipse/jetty/osgi/boot/AbstractOSGiApp.java @@ -34,74 +34,63 @@ import org.osgi.framework.Bundle; import org.osgi.framework.FrameworkUtil; import org.osgi.framework.ServiceRegistration; - - /** * AbstractOSGiApp * * Base class representing info about a webapp/ContextHandler that is deployed into Jetty. - * */ public abstract class AbstractOSGiApp extends App -{ +{ private static final Logger LOG = Log.getLogger(AbstractOSGiApp.class); - + protected Bundle _bundle; - protected Dictionary _properties; + protected Dictionary _properties; protected ServiceRegistration _registration; - /* ------------------------------------------------------------ */ public AbstractOSGiApp(DeploymentManager manager, AppProvider provider, Bundle bundle, String originId) { - this (manager, provider, bundle, bundle.getHeaders(), originId); + this(manager, provider, bundle, bundle.getHeaders(), originId); } - /* ------------------------------------------------------------ */ - public AbstractOSGiApp(DeploymentManager manager, AppProvider provider, Bundle bundle, Dictionary properties, String originId) + + public AbstractOSGiApp(DeploymentManager manager, AppProvider provider, Bundle bundle, Dictionary properties, String originId) { super(manager, provider, originId); _properties = properties; _bundle = bundle; } - - /* ------------------------------------------------------------ */ + public String getBundleSymbolicName() { return _bundle.getSymbolicName(); } - - /* ------------------------------------------------------------ */ + public String getBundleVersionAsString() { - if (_bundle.getVersion() == null) - return null; - return _bundle.getVersion().toString(); + if (_bundle.getVersion() == null) + return null; + return _bundle.getVersion().toString(); } - - /* ------------------------------------------------------------ */ + public Bundle getBundle() { return _bundle; } - - /* ------------------------------------------------------------ */ - public void setRegistration (ServiceRegistration registration) + + public void setRegistration(ServiceRegistration registration) { _registration = registration; } - - /* ------------------------------------------------------------ */ - public ServiceRegistration getRegistration () + + public ServiceRegistration getRegistration() { return _registration; } - - - /* ------------------------------------------------------------ */ + public void registerAsOSGiService() throws Exception { if (_registration == null) { - Dictionary properties = new Hashtable(); + Dictionary properties = new Hashtable(); properties.put(OSGiWebappConstants.WATERMARK, OSGiWebappConstants.WATERMARK); if (getBundleSymbolicName() != null) properties.put(OSGiWebappConstants.OSGI_WEB_SYMBOLICNAME, getBundleSymbolicName()); @@ -113,7 +102,6 @@ public abstract class AbstractOSGiApp extends App } } - /* ------------------------------------------------------------ */ protected void deregisterAsOSGiService() throws Exception { if (_registration == null) @@ -123,39 +111,39 @@ public abstract class AbstractOSGiApp extends App _registration = null; } - protected Resource getFileAsResource (String dir, String file) + protected Resource getFileAsResource(String dir, String file) { Resource r = null; try { - File asFile = new File (dir, file); + File asFile = new File(dir, file); if (asFile.exists()) r = Resource.newResource(asFile); } catch (Exception e) { r = null; - } + } return r; } - - protected Resource getFileAsResource (String file) + + protected Resource getFileAsResource(String file) { Resource r = null; try { - File asFile = new File (file); + File asFile = new File(file); if (asFile.exists()) r = Resource.newResource(asFile); } catch (Exception e) { r = null; - } + } return r; } - - protected Resource findFile (String fileName, String jettyHome, String bundleOverrideLocation, Bundle containingBundle) + + protected Resource findFile(String fileName, String jettyHome, String bundleOverrideLocation, Bundle containingBundle) { Resource res = null; @@ -171,29 +159,28 @@ public abstract class AbstractOSGiApp extends App if (jettyHome.startsWith("\"") || jettyHome.startsWith("'")) jettyHome = jettyHome.substring(1); if (jettyHome.endsWith("\"") || (jettyHome.endsWith("'"))) - jettyHome = jettyHome.substring(0,jettyHome.length()-1); + jettyHome = jettyHome.substring(0, jettyHome.length() - 1); - res = getFileAsResource(jettyHome, fileName); + res = getFileAsResource(jettyHome, fileName); } if (res != null) return res; - //try to find it relative to an override location that has been specified if (bundleOverrideLocation != null) - { - try(Resource location=Resource.newResource(bundleOverrideLocation)) + { + try (Resource location = Resource.newResource(bundleOverrideLocation)) { - res=location.addPath(fileName); + res = location.addPath(fileName); } catch (Exception e) { LOG.warn(e); } - } + } if (res != null) return res; - + //try to find it relative to the bundle in which it is being deployed if (containingBundle != null) { @@ -207,7 +194,7 @@ public abstract class AbstractOSGiApp extends App if (entry != null) res = Resource.newResource(entry); } - + return res; } } diff --git a/jetty-osgi/jetty-osgi-boot/src/main/java/org/eclipse/jetty/osgi/boot/AbstractWebAppProvider.java b/jetty-osgi/jetty-osgi-boot/src/main/java/org/eclipse/jetty/osgi/boot/AbstractWebAppProvider.java index fe54fd50f51..e1b556510c9 100644 --- a/jetty-osgi/jetty-osgi-boot/src/main/java/org/eclipse/jetty/osgi/boot/AbstractWebAppProvider.java +++ b/jetty-osgi/jetty-osgi-boot/src/main/java/org/eclipse/jetty/osgi/boot/AbstractWebAppProvider.java @@ -55,8 +55,6 @@ public abstract class AbstractWebAppProvider extends AbstractLifeCycle implement { private static final Logger LOG = Log.getLogger(AbstractWebAppProvider.class); - - private boolean _parentLoaderPriority; private String _defaultsDescriptor; @@ -64,15 +62,11 @@ public abstract class AbstractWebAppProvider extends AbstractLifeCycle implement private boolean _extractWars = true; //See WebAppContext.extractWars private String _tldBundles; - + private DeploymentManager _deploymentManager; - private ServerInstanceWrapper _serverWrapper; - - - - /* ------------------------------------------------------------ */ + /** * OSGiApp * @@ -88,13 +82,13 @@ public abstract class AbstractWebAppProvider extends AbstractLifeCycle implement { super(manager, provider, bundle, originId); } - + public OSGiApp(DeploymentManager manager, AppProvider provider, Bundle bundle, Dictionary properties, String originId) { super(manager, provider, bundle, properties, originId); } - - public void setWebAppContext (WebAppContext webApp) + + public void setWebAppContext(WebAppContext webApp) { _webApp = webApp; } @@ -119,31 +113,28 @@ public abstract class AbstractWebAppProvider extends AbstractLifeCycle implement { this._webAppPath = path; } - - + public ContextHandler createContextHandler() - throws Exception + throws Exception { if (_webApp != null) { configureWebApp(); return _webApp; } - + createWebApp(); return _webApp; } - - - - protected void createWebApp () - throws Exception + + protected void createWebApp() + throws Exception { _webApp = newWebApp(); configureWebApp(); } - - protected WebAppContext newWebApp () + + protected WebAppContext newWebApp() { WebAppContext webApp = new WebAppContext(); webApp.setAttribute(OSGiWebappConstants.WATERMARK, OSGiWebappConstants.WATERMARK); @@ -153,7 +144,7 @@ public abstract class AbstractWebAppProvider extends AbstractLifeCycle implement String[] updatedTargets = null; if (targets != null) { - updatedTargets = new String[targets.length+OSGiWebappConstants.DEFAULT_PROTECTED_OSGI_TARGETS.length]; + updatedTargets = new String[targets.length + OSGiWebappConstants.DEFAULT_PROTECTED_OSGI_TARGETS.length]; System.arraycopy(targets, 0, updatedTargets, 0, targets.length); } else @@ -161,40 +152,39 @@ public abstract class AbstractWebAppProvider extends AbstractLifeCycle implement System.arraycopy(OSGiWebappConstants.DEFAULT_PROTECTED_OSGI_TARGETS, 0, updatedTargets, targets.length, OSGiWebappConstants.DEFAULT_PROTECTED_OSGI_TARGETS.length); webApp.setProtectedTargets(updatedTargets); - return webApp; + return webApp; } - - public void configureWebApp() - throws Exception - { + public void configureWebApp() + throws Exception + { //TODO turn this around and let any context.xml file get applied first, and have the properties override _webApp.setContextPath(_contextPath); - + //osgi Enterprise Spec r4 p.427 _webApp.setAttribute(OSGiWebappConstants.OSGI_BUNDLECONTEXT, _bundle.getBundleContext()); String overrideBundleInstallLocation = (String)_properties.get(OSGiWebappConstants.JETTY_BUNDLE_INSTALL_LOCATION_OVERRIDE); - File bundleInstallLocation = - (overrideBundleInstallLocation == null - ? BundleFileLocatorHelperFactory.getFactory().getHelper().getBundleInstallLocation(_bundle) - : new File(overrideBundleInstallLocation)); - + File bundleInstallLocation = + (overrideBundleInstallLocation == null + ? BundleFileLocatorHelperFactory.getFactory().getHelper().getBundleInstallLocation(_bundle) + : new File(overrideBundleInstallLocation)); + if (LOG.isDebugEnabled()) { LOG.debug("Bundle location is {}, install location: {}", _bundle.getLocation(), bundleInstallLocation); } - + URL url = null; Resource rootResource = Resource.newResource(BundleFileLocatorHelperFactory.getFactory().getHelper().getLocalURL(bundleInstallLocation.toURI().toURL())); //try and make sure the rootResource is useable - if its a jar then make it a jar file url - if (rootResource.exists()&& !rootResource.isDirectory() && !rootResource.toString().startsWith("jar:")) + if (rootResource.exists() && !rootResource.isDirectory() && !rootResource.toString().startsWith("jar:")) { - Resource jarResource = JarResource.newJarResource(rootResource); - if (jarResource.exists() && jarResource.isDirectory()) - rootResource = jarResource; + Resource jarResource = JarResource.newJarResource(rootResource); + if (jarResource.exists() && jarResource.isDirectory()) + rootResource = jarResource; } - + //if the path wasn't set or it was ., then it is the root of the bundle's installed location if (_webAppPath == null || _webAppPath.length() == 0 || ".".equals(_webAppPath)) { @@ -230,10 +220,9 @@ public abstract class AbstractWebAppProvider extends AbstractLifeCycle implement } if (url == null) - { - throw new IllegalArgumentException("Unable to locate " + _webAppPath - + " in " - + (bundleInstallLocation != null ? bundleInstallLocation.getAbsolutePath() : "unlocated bundle '" + _bundle.getSymbolicName()+ "'")); + { + throw new IllegalArgumentException("Unable to locate " + _webAppPath + " in " + + (bundleInstallLocation != null ? bundleInstallLocation.getAbsolutePath() : "unlocated bundle '" + _bundle.getSymbolicName() + "'")); } //Sets the location of the war file @@ -244,7 +233,6 @@ public abstract class AbstractWebAppProvider extends AbstractLifeCycle implement _webApp.setParentLoaderPriority(isParentLoaderPriority()); _webApp.setExtractWAR(isExtract()); - //Set up configuration from manifest headers //extra classpath String tmp = (String)_properties.get(OSGiWebappConstants.JETTY_EXTRA_CLASSPATH); @@ -255,7 +243,7 @@ public abstract class AbstractWebAppProvider extends AbstractLifeCycle implement tmp = (String)_properties.get(OSGiWebappConstants.JETTY_WEB_XML_PATH); if (tmp != null && tmp.trim().length() != 0) { - File webXml = getFile (tmp, bundleInstallLocation); + File webXml = getFile(tmp, bundleInstallLocation); if (webXml != null && webXml.exists()) _webApp.setDescriptor(webXml.getAbsolutePath()); } @@ -264,13 +252,13 @@ public abstract class AbstractWebAppProvider extends AbstractLifeCycle implement tmp = (String)_properties.get(OSGiWebappConstants.JETTY_DEFAULT_WEB_XML_PATH); if (tmp != null) { - File defaultWebXml = getFile (tmp, bundleInstallLocation); + File defaultWebXml = getFile(tmp, bundleInstallLocation); if (defaultWebXml != null) { if (defaultWebXml.exists()) _webApp.setDefaultsDescriptor(defaultWebXml.getAbsolutePath()); else - LOG.warn(defaultWebXml.getAbsolutePath()+" does not exist"); + LOG.warn(defaultWebXml.getAbsolutePath() + " does not exist"); } } @@ -280,8 +268,6 @@ public abstract class AbstractWebAppProvider extends AbstractLifeCycle implement String requireTldBundles = (String)_properties.get(OSGiWebappConstants.REQUIRE_TLD_BUNDLE); String pathsToTldBundles = getPathsToRequiredBundles(requireTldBundles); - - // make sure we provide access to all the jetty bundles by going // through this bundle. OSGiWebappClassLoader webAppLoader = new OSGiWebappClassLoader(_serverWrapper.getParentClassLoaderForWebapps(), _webApp, _bundle); @@ -290,23 +276,23 @@ public abstract class AbstractWebAppProvider extends AbstractLifeCycle implement webAppLoader.addClassPath(pathsToTldBundles); _webApp.setClassLoader(webAppLoader); - // apply any META-INF/context.xml file that is found to configure // the webapp first try { final Resource finalRootResource = rootResource; - WebAppClassLoader.runWithServerClassAccess(()->{applyMetaInfContextXml(finalRootResource, overrideBundleInstallLocation);return null;}); + WebAppClassLoader.runWithServerClassAccess(() -> + { + applyMetaInfContextXml(finalRootResource, overrideBundleInstallLocation); + return null; + }); } - catch(Exception e) + catch (Exception e) { LOG.warn("Error applying context xml"); throw e; } - - - _webApp.setAttribute(OSGiWebappConstants.REQUIRE_TLD_BUNDLE, requireTldBundles); //Set up some attributes @@ -326,52 +312,53 @@ public abstract class AbstractWebAppProvider extends AbstractLifeCycle implement _webApp.setAttribute(OSGiWebappConstants.JETTY_OSGI_BUNDLE, _bundle); } - protected String getPathsToRequiredBundles (String requireTldBundles) - throws Exception + protected String getPathsToRequiredBundles(String requireTldBundles) + throws Exception { - if (requireTldBundles == null) return null; + if (requireTldBundles == null) + return null; ServiceReference ref = _bundle.getBundleContext().getServiceReference(org.osgi.service.packageadmin.PackageAdmin.class.getName()); PackageAdmin packageAdmin = (ref == null) ? null : (PackageAdmin)_bundle.getBundleContext().getService(ref); if (packageAdmin == null) throw new IllegalStateException("Unable to get PackageAdmin reference to locate required Tld bundles"); - StringBuilder paths = new StringBuilder(); + StringBuilder paths = new StringBuilder(); String[] symbNames = requireTldBundles.split("[, ]"); for (String symbName : symbNames) { Bundle[] bs = packageAdmin.getBundles(symbName, null); - if (bs == null || bs.length == 0) - { - throw new IllegalArgumentException("Unable to locate the bundle '" + symbName - + "' specified by " - + OSGiWebappConstants.REQUIRE_TLD_BUNDLE - + " in manifest of " - + (_bundle == null ? "unknown" : _bundle.getSymbolicName())); + if (bs == null || bs.length == 0) + { + throw new IllegalArgumentException("Unable to locate the bundle '" + symbName + "' specified by " + + OSGiWebappConstants.REQUIRE_TLD_BUNDLE + " in manifest of " + + (_bundle == null ? "unknown" : _bundle.getSymbolicName())); } File f = BundleFileLocatorHelperFactory.getFactory().getHelper().getBundleInstallLocation(bs[0]); - if (paths.length() > 0) paths.append(", "); + if (paths.length() > 0) + paths.append(", "); paths.append(f.toURI().toURL().toString()); LOG.debug("getPathsToRequiredBundles: bundle path=" + bs[0].getLocation() + " uri=" + f.toURI()); } return paths.toString(); } - - + protected void applyMetaInfContextXml(Resource rootResource, String overrideBundleInstallLocation) - throws Exception + throws Exception { - if (_bundle == null) return; - if (_webApp == null) return; + if (_bundle == null) + return; + if (_webApp == null) + return; ClassLoader cl = Thread.currentThread().getContextClassLoader(); LOG.debug("Context classloader = " + cl); try { - + Thread.currentThread().setContextClassLoader(_webApp.getClassLoader()); URI contextXmlUri = null; @@ -379,7 +366,7 @@ public abstract class AbstractWebAppProvider extends AbstractLifeCycle implement //TODO replace this with getting the InputStream so we don't cache in URL //Try looking for a context xml file in META-INF with a specific name URL url = _bundle.getEntry("/META-INF/jetty-webapp-context.xml"); - if(url != null) + if (url != null) { contextXmlUri = url.toURI(); } @@ -398,7 +385,7 @@ public abstract class AbstractWebAppProvider extends AbstractLifeCycle implement String filename = filenames[0]; //should only be 1 filename in this usage String jettyHome = (String)getServerInstanceWrapper().getServer().getAttribute(OSGiServerConstants.JETTY_HOME); if (jettyHome == null) - jettyHome = System.getProperty(OSGiServerConstants.JETTY_HOME); + jettyHome = System.getProperty(OSGiServerConstants.JETTY_HOME); Resource res = findFile(filename, jettyHome, overrideBundleInstallLocation, _bundle); if (res != null) { @@ -415,10 +402,10 @@ public abstract class AbstractWebAppProvider extends AbstractLifeCycle implement LOG.info("Applying " + contextXmlUri + " to " + _webApp); XmlConfiguration xmlConfiguration = new XmlConfiguration(Resource.newResource(contextXmlUri)); - WebAppClassLoader.runWithServerClassAccess(()-> + WebAppClassLoader.runWithServerClassAccess(() -> { - HashMap properties = new HashMap<>(); - xmlConfiguration.getIdMap().put("Server",getDeploymentManager().getServer()); + HashMap properties = new HashMap<>(); + xmlConfiguration.getIdMap().put("Server", getDeploymentManager().getServer()); properties.put(OSGiWebappConstants.JETTY_BUNDLE_ROOT, rootResource.toString()); properties.put(OSGiServerConstants.JETTY_HOME, (String)getDeploymentManager().getServer().getAttribute(OSGiServerConstants.JETTY_HOME)); xmlConfiguration.getProperties().putAll(properties); @@ -431,8 +418,8 @@ public abstract class AbstractWebAppProvider extends AbstractLifeCycle implement Thread.currentThread().setContextClassLoader(cl); } } - - private File getFile (String file, File bundleInstall) + + private File getFile(String file, File bundleInstall) { if (file == null) return null; @@ -443,29 +430,26 @@ public abstract class AbstractWebAppProvider extends AbstractLifeCycle implement { //relative location //try inside the bundle first - File f = new File (bundleInstall, file); - if (f.exists()) return f; + File f = new File(bundleInstall, file); + if (f.exists()) + return f; String jettyHome = (String)getDeploymentManager().getServer().getAttribute(OSGiServerConstants.JETTY_HOME); if (jettyHome != null) return new File(jettyHome, file); } - + return null; } } - - /* ------------------------------------------------------------ */ - public AbstractWebAppProvider (ServerInstanceWrapper wrapper) + + public AbstractWebAppProvider(ServerInstanceWrapper wrapper) { _serverWrapper = wrapper; } - - - - /* ------------------------------------------------------------ */ + /** * Get the parentLoaderPriority. - * + * * @return the parentLoaderPriority */ public boolean isParentLoaderPriority() @@ -473,10 +457,9 @@ public abstract class AbstractWebAppProvider extends AbstractLifeCycle implement return _parentLoaderPriority; } - /* ------------------------------------------------------------ */ /** * Set the parentLoaderPriority. - * + * * @param parentLoaderPriority the parentLoaderPriority to set */ public void setParentLoaderPriority(boolean parentLoaderPriority) @@ -484,10 +467,9 @@ public abstract class AbstractWebAppProvider extends AbstractLifeCycle implement _parentLoaderPriority = parentLoaderPriority; } - /* ------------------------------------------------------------ */ /** * Get the defaultsDescriptor. - * + * * @return the defaultsDescriptor */ public String getDefaultsDescriptor() @@ -495,55 +477,44 @@ public abstract class AbstractWebAppProvider extends AbstractLifeCycle implement return _defaultsDescriptor; } - /* ------------------------------------------------------------ */ /** * Set the defaultsDescriptor. - * + * * @param defaultsDescriptor the defaultsDescriptor to set */ public void setDefaultsDescriptor(String defaultsDescriptor) { _defaultsDescriptor = defaultsDescriptor; } - - - /* ------------------------------------------------------------ */ + public boolean isExtract() { return _extractWars; } - - - /* ------------------------------------------------------------ */ + public void setExtract(boolean extract) { _extractWars = extract; } - - - /* ------------------------------------------------------------ */ + /** * @param tldBundles Comma separated list of bundles that contain tld jars - * that should be setup on the jetty instances created here. + * that should be setup on the jetty instances created here. */ public void setTldBundles(String tldBundles) { _tldBundles = tldBundles; } - - - /* ------------------------------------------------------------ */ + /** * @return The list of bundles that contain tld jars that should be setup on - * the jetty instances created here. + * the jetty instances created here. */ public String getTldBundles() { return _tldBundles; } - - /* ------------------------------------------------------------ */ public void setServerInstanceWrapper(ServerInstanceWrapper wrapper) { _serverWrapper = wrapper; @@ -554,14 +525,12 @@ public abstract class AbstractWebAppProvider extends AbstractLifeCycle implement return _serverWrapper; } - /* ------------------------------------------------------------ */ public DeploymentManager getDeploymentManager() { return _deploymentManager; } - /* ------------------------------------------------------------ */ - /** + /** * @see org.eclipse.jetty.deploy.AppProvider#setDeploymentManager(org.eclipse.jetty.deploy.DeploymentManager) */ @Override @@ -569,27 +538,22 @@ public abstract class AbstractWebAppProvider extends AbstractLifeCycle implement { _deploymentManager = deploymentManager; } - - - /* ------------------------------------------------------------ */ + @Override public ContextHandler createContextHandler(App app) throws Exception { if (app == null) return null; if (!(app instanceof OSGiApp)) - throw new IllegalStateException(app+" is not a BundleApp"); + throw new IllegalStateException(app + " is not a BundleApp"); //Create a WebAppContext suitable to deploy in OSGi ContextHandler ch = ((OSGiApp)app).createContextHandler(); return ch; } - - /* ------------------------------------------------------------ */ public static String getOriginId(Bundle contributor, String path) { return contributor.getSymbolicName() + "-" + contributor.getVersion().toString() + (path.startsWith("/") ? path : "/" + path); } - } diff --git a/jetty-osgi/jetty-osgi-boot/src/main/java/org/eclipse/jetty/osgi/boot/BundleContextProvider.java b/jetty-osgi/jetty-osgi-boot/src/main/java/org/eclipse/jetty/osgi/boot/BundleContextProvider.java index ccf47b77ee3..a5873d23dcf 100644 --- a/jetty-osgi/jetty-osgi-boot/src/main/java/org/eclipse/jetty/osgi/boot/BundleContextProvider.java +++ b/jetty-osgi/jetty-osgi-boot/src/main/java/org/eclipse/jetty/osgi/boot/BundleContextProvider.java @@ -43,29 +43,28 @@ import org.osgi.util.tracker.BundleTracker; * Handles deploying OSGi bundles that define a context xml file for configuring them. */ public class BundleContextProvider extends AbstractContextProvider implements BundleProvider -{ +{ private static final Logger LOG = Log.getLogger(AbstractContextProvider.class); private Map _appMap = new HashMap(); - + private Map> _bundleMap = new HashMap>(); - + private ServiceRegistration _serviceRegForBundles; - + private BundleTracker _tracker; - - + public class ContextBundleTracker extends BundleTracker { protected String _managedServerName; - - public ContextBundleTracker (BundleContext bundleContext, String managedServerName) + + public ContextBundleTracker(BundleContext bundleContext, String managedServerName) { - super (bundleContext, Bundle.ACTIVE | Bundle.STOPPING,null); + super(bundleContext, Bundle.ACTIVE | Bundle.STOPPING, null); _managedServerName = managedServerName; } - /** + /** * @see org.osgi.util.tracker.BundleTracker#addingBundle(org.osgi.framework.Bundle, org.osgi.framework.BundleEvent) */ @Override @@ -74,10 +73,10 @@ public class BundleContextProvider extends AbstractContextProvider implements Bu try { String serverName = (String)bundle.getHeaders().get(OSGiServerConstants.MANAGED_JETTY_SERVER_NAME); - if ((StringUtil.isBlank(serverName) && _managedServerName.equals(OSGiServerConstants.MANAGED_JETTY_SERVER_DEFAULT_NAME)) - || (!StringUtil.isBlank(serverName) && (serverName.equals(_managedServerName)))) + if ((StringUtil.isBlank(serverName) && _managedServerName.equals(OSGiServerConstants.MANAGED_JETTY_SERVER_DEFAULT_NAME)) || + (!StringUtil.isBlank(serverName) && (serverName.equals(_managedServerName)))) { - if (bundleAdded (bundle)) + if (bundleAdded(bundle)) return bundle; } } @@ -88,9 +87,7 @@ public class BundleContextProvider extends AbstractContextProvider implements Bu return null; } - - - /** + /** * @see org.osgi.util.tracker.BundleTracker#removedBundle(org.osgi.framework.Bundle, org.osgi.framework.BundleEvent, java.lang.Object) */ @Override @@ -105,37 +102,32 @@ public class BundleContextProvider extends AbstractContextProvider implements Bu LOG.warn(e); } } - } - - /* ------------------------------------------------------------ */ + public BundleContextProvider(ServerInstanceWrapper wrapper) { super(wrapper); } - - - /* ------------------------------------------------------------ */ + @Override protected void doStart() throws Exception { //Track bundles that are ContextHandlers that should be deployed _tracker = new ContextBundleTracker(FrameworkUtil.getBundle(this.getClass()).getBundleContext(), getServerInstanceWrapper().getManagedServerName()); _tracker.open(); - + //register as an osgi service for deploying contexts defined in a bundle, advertising the name of the jetty Server instance we are related to - Dictionary properties = new Hashtable(); + Dictionary properties = new Hashtable(); properties.put(OSGiServerConstants.MANAGED_JETTY_SERVER_NAME, getServerInstanceWrapper().getManagedServerName()); _serviceRegForBundles = FrameworkUtil.getBundle(this.getClass()).getBundleContext().registerService(BundleProvider.class.getName(), this, properties); super.doStart(); } - /* ------------------------------------------------------------ */ @Override protected void doStop() throws Exception { _tracker.close(); - + //unregister ourselves if (_serviceRegForBundles != null) { @@ -150,12 +142,8 @@ public class BundleContextProvider extends AbstractContextProvider implements Bu } } - - - - /* ------------------------------------------------------------ */ @Override - public boolean bundleAdded (Bundle bundle) throws Exception + public boolean bundleAdded(Bundle bundle) throws Exception { if (bundle == null) return false; @@ -163,16 +151,16 @@ public class BundleContextProvider extends AbstractContextProvider implements Bu //If the bundle defines a Web-ContextPath then its probably a webapp and the BundleWebAppProvider should deploy it if ((String)bundle.getHeaders().get(OSGiWebappConstants.RFC66_WEB_CONTEXTPATH) != null) { - if (LOG.isDebugEnabled()) LOG.debug("BundleContextProvider ignoring bundle {} with {} set", bundle.getSymbolicName(), OSGiWebappConstants.RFC66_WEB_CONTEXTPATH); + if (LOG.isDebugEnabled()) + LOG.debug("BundleContextProvider ignoring bundle {} with {} set", bundle.getSymbolicName(), OSGiWebappConstants.RFC66_WEB_CONTEXTPATH); return false; } - - String contextFiles = (String)bundle.getHeaders().get(OSGiWebappConstants.JETTY_CONTEXT_FILE_PATH); + + String contextFiles = (String)bundle.getHeaders().get(OSGiWebappConstants.JETTY_CONTEXT_FILE_PATH); if (contextFiles == null) return false; - - + boolean added = false; //bundle defines JETTY_CONTEXT_FILE_PATH header, //a comma separated list of context xml files that each define a ContextHandler @@ -180,9 +168,9 @@ public class BundleContextProvider extends AbstractContextProvider implements Bu String[] tmp = contextFiles.split("[,;]"); for (String contextFile : tmp) { - String originId = bundle.getSymbolicName() + "-" + bundle.getVersion().toString() + "-"+contextFile; + String originId = bundle.getSymbolicName() + "-" + bundle.getVersion().toString() + "-" + contextFile; OSGiApp app = new OSGiApp(getDeploymentManager(), this, originId, bundle, contextFile); - _appMap.put(originId,app); + _appMap.put(originId, app); List apps = _bundleMap.get(bundle); if (apps == null) { @@ -196,23 +184,21 @@ public class BundleContextProvider extends AbstractContextProvider implements Bu return added; //true if even 1 context from this bundle was added } - - - /* ------------------------------------------------------------ */ - /** + + /** * Bundle has been removed. If it was a context we deployed, undeploy it. - * + * * @param bundle the bundle * @return true if this was a context we had deployed, false otherwise */ @Override - public boolean bundleRemoved (Bundle bundle) throws Exception + public boolean bundleRemoved(Bundle bundle) throws Exception { List apps = _bundleMap.remove(bundle); boolean removed = false; if (apps != null) { - for (App app:apps) + for (App app : apps) { _appMap.remove(app.getOriginId()); getDeploymentManager().removeApp(app); @@ -221,6 +207,4 @@ public class BundleContextProvider extends AbstractContextProvider implements Bu } return removed; //true if even 1 context was removed associated with this bundle } - - } diff --git a/jetty-osgi/jetty-osgi-boot/src/main/java/org/eclipse/jetty/osgi/boot/BundleProvider.java b/jetty-osgi/jetty-osgi-boot/src/main/java/org/eclipse/jetty/osgi/boot/BundleProvider.java index 9efa432c03b..33b36b85186 100644 --- a/jetty-osgi/jetty-osgi-boot/src/main/java/org/eclipse/jetty/osgi/boot/BundleProvider.java +++ b/jetty-osgi/jetty-osgi-boot/src/main/java/org/eclipse/jetty/osgi/boot/BundleProvider.java @@ -27,7 +27,7 @@ import org.osgi.framework.Bundle; */ public interface BundleProvider { - public boolean bundleAdded (Bundle bundle) throws Exception; - - public boolean bundleRemoved (Bundle bundle) throws Exception; + public boolean bundleAdded(Bundle bundle) throws Exception; + + public boolean bundleRemoved(Bundle bundle) throws Exception; } diff --git a/jetty-osgi/jetty-osgi-boot/src/main/java/org/eclipse/jetty/osgi/boot/BundleWebAppProvider.java b/jetty-osgi/jetty-osgi-boot/src/main/java/org/eclipse/jetty/osgi/boot/BundleWebAppProvider.java index b2b4b0c47ba..353f9396a01 100644 --- a/jetty-osgi/jetty-osgi-boot/src/main/java/org/eclipse/jetty/osgi/boot/BundleWebAppProvider.java +++ b/jetty-osgi/jetty-osgi-boot/src/main/java/org/eclipse/jetty/osgi/boot/BundleWebAppProvider.java @@ -42,30 +42,29 @@ import org.osgi.util.tracker.BundleTracker; * A Jetty Provider that knows how to deploy a WebApp contained inside a Bundle. */ public class BundleWebAppProvider extends AbstractWebAppProvider implements BundleProvider -{ +{ private static final Logger LOG = Log.getLogger(AbstractWebAppProvider.class); - + /** * Map of Bundle to App. Used when a Bundle contains a webapp. */ private Map _bundleMap = new HashMap<>(); - + private ServiceRegistration _serviceRegForBundles; - + private WebAppTracker _webappTracker; - - + public class WebAppTracker extends BundleTracker { protected String _managedServerName; - - public WebAppTracker (BundleContext bundleContext, String managedServerName) + + public WebAppTracker(BundleContext bundleContext, String managedServerName) { - super (bundleContext, Bundle.ACTIVE | Bundle.STOPPING,null); + super(bundleContext, Bundle.ACTIVE | Bundle.STOPPING, null); _managedServerName = managedServerName; } - /** + /** * @see org.osgi.util.tracker.BundleTracker#addingBundle(org.osgi.framework.Bundle, org.osgi.framework.BundleEvent) */ @Override @@ -74,10 +73,10 @@ public class BundleWebAppProvider extends AbstractWebAppProvider implements Bund try { String serverName = (String)bundle.getHeaders().get(OSGiServerConstants.MANAGED_JETTY_SERVER_NAME); - if ((StringUtil.isBlank(serverName) && _managedServerName.equals(OSGiServerConstants.MANAGED_JETTY_SERVER_DEFAULT_NAME)) - || (!StringUtil.isBlank(serverName) && (serverName.equals(_managedServerName)))) + if ((StringUtil.isBlank(serverName) && _managedServerName.equals(OSGiServerConstants.MANAGED_JETTY_SERVER_DEFAULT_NAME)) || + (!StringUtil.isBlank(serverName) && (serverName.equals(_managedServerName)))) { - if (bundleAdded (bundle)) + if (bundleAdded(bundle)) return bundle; } } @@ -88,9 +87,7 @@ public class BundleWebAppProvider extends AbstractWebAppProvider implements Bund return null; } - - - /** + /** * @see org.osgi.util.tracker.BundleTracker#removedBundle(org.osgi.framework.Bundle, org.osgi.framework.BundleEvent, java.lang.Object) */ @Override @@ -105,18 +102,14 @@ public class BundleWebAppProvider extends AbstractWebAppProvider implements Bund LOG.warn(e); } } - - } - /* ------------------------------------------------------------ */ - public BundleWebAppProvider (ServerInstanceWrapper wrapper) + public BundleWebAppProvider(ServerInstanceWrapper wrapper) { super(wrapper); } - - /* ------------------------------------------------------------ */ - /** + + /** * @see org.eclipse.jetty.util.component.AbstractLifeCycle#doStart() */ @Override @@ -125,21 +118,20 @@ public class BundleWebAppProvider extends AbstractWebAppProvider implements Bund _webappTracker = new WebAppTracker(FrameworkUtil.getBundle(this.getClass()).getBundleContext(), getServerInstanceWrapper().getManagedServerName()); _webappTracker.open(); //register as an osgi service for deploying bundles, advertising the name of the jetty Server instance we are related to - Dictionary properties = new Hashtable<>(); + Dictionary properties = new Hashtable<>(); properties.put(OSGiServerConstants.MANAGED_JETTY_SERVER_NAME, getServerInstanceWrapper().getManagedServerName()); _serviceRegForBundles = FrameworkUtil.getBundle(this.getClass()).getBundleContext().registerService(BundleProvider.class.getName(), this, properties); super.doStart(); } - /* ------------------------------------------------------------ */ - /** + /** * @see org.eclipse.jetty.util.component.AbstractLifeCycle#doStop() */ @Override protected void doStop() throws Exception { _webappTracker.close(); - + //unregister ourselves if (_serviceRegForBundles != null) { @@ -152,22 +144,17 @@ public class BundleWebAppProvider extends AbstractWebAppProvider implements Bund LOG.warn(e); } } - + super.doStop(); } - - - - - - /* ------------------------------------------------------------ */ /** - * A bundle has been added that could be a webapp + * A bundle has been added that could be a webapp + * * @param bundle the bundle */ @Override - public boolean bundleAdded (Bundle bundle) throws Exception + public boolean bundleAdded(Bundle bundle) throws Exception { if (bundle == null) return false; @@ -175,10 +162,10 @@ public class BundleWebAppProvider extends AbstractWebAppProvider implements Bund ClassLoader cl = Thread.currentThread().getContextClassLoader(); Thread.currentThread().setContextClassLoader(getServerInstanceWrapper().getParentClassLoaderForWebapps()); String contextPath = null; - try + try { @SuppressWarnings("unchecked") - Dictionary headers = bundle.getHeaders(); + Dictionary headers = bundle.getHeaders(); //does the bundle have a OSGiWebappConstants.JETTY_WAR_FOLDER_PATH String resourcePath = Util.getManifestHeaderValue(OSGiWebappConstants.JETTY_WAR_RESOURCE_PATH, headers); @@ -187,7 +174,7 @@ public class BundleWebAppProvider extends AbstractWebAppProvider implements Bund String base = resourcePath; contextPath = getContextPath(bundle); String originId = getOriginId(bundle, base); - + //TODO : we don't know whether an app is actually deployed, as deploymentManager swallows all //exceptions inside the impl of addApp. Need to send the Event and also register as a service //only if the deployment succeeded @@ -199,19 +186,18 @@ public class BundleWebAppProvider extends AbstractWebAppProvider implements Bund return true; } - //does the bundle have a WEB-INF/web.xml if (bundle.getEntry("/WEB-INF/web.xml") != null) { String base = "."; contextPath = getContextPath(bundle); String originId = getOriginId(bundle, base); - + OSGiApp app = new OSGiApp(getDeploymentManager(), this, bundle, originId); app.setContextPath(contextPath); app.setWebAppPath(base); _bundleMap.put(bundle, app); - getDeploymentManager().addApp(app); + getDeploymentManager().addApp(app); return true; } @@ -221,13 +207,13 @@ public class BundleWebAppProvider extends AbstractWebAppProvider implements Bund //Could be a static webapp with no web.xml String base = "."; contextPath = headers.get(OSGiWebappConstants.RFC66_WEB_CONTEXTPATH); - String originId = getOriginId(bundle,base); - + String originId = getOriginId(bundle, base); + OSGiApp app = new OSGiApp(getDeploymentManager(), this, bundle, originId); app.setContextPath(contextPath); app.setWebAppPath(base); _bundleMap.put(bundle, app); - getDeploymentManager().addApp(app); + getDeploymentManager().addApp(app); return true; } @@ -235,7 +221,7 @@ public class BundleWebAppProvider extends AbstractWebAppProvider implements Bund } catch (Exception e) { - + throw e; } finally @@ -244,35 +230,28 @@ public class BundleWebAppProvider extends AbstractWebAppProvider implements Bund } } - - /* ------------------------------------------------------------ */ - /** + /** * Bundle has been removed. If it was a webapp we deployed, undeploy it. - * + * * @param bundle the bundle * @return true if this was a webapp we had deployed, false otherwise */ @Override - public boolean bundleRemoved (Bundle bundle) throws Exception + public boolean bundleRemoved(Bundle bundle) throws Exception { App app = _bundleMap.remove(bundle); if (app != null) { - getDeploymentManager().removeApp(app); + getDeploymentManager().removeApp(app); return true; } return false; } - - - - - /* ------------------------------------------------------------ */ private static String getContextPath(Bundle bundle) { Dictionary headers = bundle.getHeaders(); - String contextPath = (String) headers.get(OSGiWebappConstants.RFC66_WEB_CONTEXTPATH); + String contextPath = (String)headers.get(OSGiWebappConstants.RFC66_WEB_CONTEXTPATH); if (contextPath == null) { // extract from the last token of the bundle's location: @@ -280,7 +259,7 @@ public class BundleWebAppProvider extends AbstractWebAppProvider implements Bund // the location will often reflect the version. // maybe this is relevant when the file is a war) String location = bundle.getLocation(); - String toks[] = StringUtil.replace(location, '\\', '/').split("/"); + String[] toks = StringUtil.replace(location, '\\', '/').split("/"); contextPath = toks[toks.length - 1]; // remove .jar, .war etc: int lastDot = contextPath.lastIndexOf('.'); @@ -289,10 +268,7 @@ public class BundleWebAppProvider extends AbstractWebAppProvider implements Bund } if (!contextPath.startsWith("/")) contextPath = "/" + contextPath; - + return contextPath; } - - - } diff --git a/jetty-osgi/jetty-osgi-boot/src/main/java/org/eclipse/jetty/osgi/boot/JettyBootstrapActivator.java b/jetty-osgi/jetty-osgi-boot/src/main/java/org/eclipse/jetty/osgi/boot/JettyBootstrapActivator.java index f54d8be9882..63140b189b3 100644 --- a/jetty-osgi/jetty-osgi-boot/src/main/java/org/eclipse/jetty/osgi/boot/JettyBootstrapActivator.java +++ b/jetty-osgi/jetty-osgi-boot/src/main/java/org/eclipse/jetty/osgi/boot/JettyBootstrapActivator.java @@ -42,7 +42,7 @@ import org.osgi.util.tracker.ServiceTracker; public class JettyBootstrapActivator implements BundleActivator { private static final Logger LOG = Log.getLogger(JettyBootstrapActivator.class); - + private static JettyBootstrapActivator INSTANCE = null; public static JettyBootstrapActivator getInstance() @@ -51,30 +51,27 @@ public class JettyBootstrapActivator implements BundleActivator } private ServiceRegistration _registeredServer; - + private PackageAdminServiceTracker _packageAdminServiceTracker; private ServiceTracker _jettyServerServiceTracker; - - - - /* ------------------------------------------------------------ */ + /** * Setup a new jetty Server, registers it as a service. Setup the Service * tracker for the jetty ContextHandlers that are in charge of deploying the * webapps. Setup the BundleListener that supports the extender pattern for * the jetty ContextHandler. - * + * * @param context the bundle context */ @Override public void start(final BundleContext context) throws Exception { ServiceReference[] references = context.getAllServiceReferences("org.eclipse.jetty.http.HttpFieldPreEncoder", null); - - if (references == null || references.length==0) + + if (references == null || references.length == 0) LOG.warn("OSGi support for java.util.ServiceLoader may not be present. You may experience runtime errors."); - + INSTANCE = this; // track other bundles and fragments attached to this bundle that we @@ -84,19 +81,15 @@ public class JettyBootstrapActivator implements BundleActivator // track jetty Server instances that we should support as deployment targets _jettyServerServiceTracker = new ServiceTracker(context, context.createFilter("(objectclass=" + Server.class.getName() + ")"), new JettyServerServiceTracker()); _jettyServerServiceTracker.open(); - + // Create a default jetty instance right now. DefaultJettyAtJettyHomeHelper.startJettyAtJettyHome(context); } - - - /* ------------------------------------------------------------ */ /** * Stop the activator. - * - * @see - * org.osgi.framework.BundleActivator#stop(org.osgi.framework.BundleContext) + * + * @see org.osgi.framework.BundleActivator#stop(org.osgi.framework.BundleContext) */ @Override public void stop(BundleContext context) throws Exception diff --git a/jetty-osgi/jetty-osgi-boot/src/main/java/org/eclipse/jetty/osgi/boot/OSGiDeployer.java b/jetty-osgi/jetty-osgi-boot/src/main/java/org/eclipse/jetty/osgi/boot/OSGiDeployer.java index 9edfd10df4a..ac6161d7302 100644 --- a/jetty-osgi/jetty-osgi-boot/src/main/java/org/eclipse/jetty/osgi/boot/OSGiDeployer.java +++ b/jetty-osgi/jetty-osgi-boot/src/main/java/org/eclipse/jetty/osgi/boot/OSGiDeployer.java @@ -24,27 +24,22 @@ import org.eclipse.jetty.deploy.graph.Node; import org.eclipse.jetty.osgi.boot.internal.serverfactory.ServerInstanceWrapper; import org.eclipse.jetty.osgi.boot.utils.EventSender; - /** * OSGiDeployer * - * Extension of standard Jetty deployer that emits OSGi EventAdmin + * Extension of standard Jetty deployer that emits OSGi EventAdmin * events whenever a webapp is deployed into OSGi via Jetty. - * */ public class OSGiDeployer extends StandardDeployer { - + private ServerInstanceWrapper _server; - /* ------------------------------------------------------------ */ - public OSGiDeployer (ServerInstanceWrapper server) + public OSGiDeployer(ServerInstanceWrapper server) { - _server = server; + _server = server; } - - - /* ------------------------------------------------------------ */ + @Override public void processBinding(Node node, App app) throws Exception { @@ -52,36 +47,34 @@ public class OSGiDeployer extends StandardDeployer //OSGi Enterprise Spec only wants an event sent if its a webapp bundle (ie not a ContextHandler) if (!(app instanceof AbstractOSGiApp)) { - doProcessBinding(node,app); + doProcessBinding(node, app); } else { EventSender.getInstance().send(EventSender.DEPLOYING_EVENT, ((AbstractOSGiApp)app).getBundle(), app.getContextPath()); try { - doProcessBinding(node,app); + doProcessBinding(node, app); ((AbstractOSGiApp)app).registerAsOSGiService(); EventSender.getInstance().send(EventSender.DEPLOYED_EVENT, ((AbstractOSGiApp)app).getBundle(), app.getContextPath()); } catch (Exception e) { - EventSender.getInstance().send(EventSender.FAILED_EVENT, ((AbstractOSGiApp)app).getBundle(), app.getContextPath()); + EventSender.getInstance().send(EventSender.FAILED_EVENT, ((AbstractOSGiApp)app).getBundle(), app.getContextPath()); throw e; } } } - - - /* ------------------------------------------------------------ */ - protected void doProcessBinding (Node node, App app) throws Exception + + protected void doProcessBinding(Node node, App app) throws Exception { ClassLoader old = Thread.currentThread().getContextClassLoader(); Thread.currentThread().setContextClassLoader(_server.getParentClassLoaderForWebapps()); try { - super.processBinding(node,app); + super.processBinding(node, app); } - finally + finally { Thread.currentThread().setContextClassLoader(old); } diff --git a/jetty-osgi/jetty-osgi-boot/src/main/java/org/eclipse/jetty/osgi/boot/OSGiMetaInfConfiguration.java b/jetty-osgi/jetty-osgi-boot/src/main/java/org/eclipse/jetty/osgi/boot/OSGiMetaInfConfiguration.java index 3093424dcb4..8af1f54ce92 100644 --- a/jetty-osgi/jetty-osgi-boot/src/main/java/org/eclipse/jetty/osgi/boot/OSGiMetaInfConfiguration.java +++ b/jetty-osgi/jetty-osgi-boot/src/main/java/org/eclipse/jetty/osgi/boot/OSGiMetaInfConfiguration.java @@ -46,17 +46,15 @@ import org.eclipse.jetty.webapp.WebInfConfiguration; import org.osgi.framework.Bundle; import org.osgi.framework.FrameworkUtil; - - /** * OSGiWebInfConfiguration * - * Handle adding resources found in bundle fragments, and add them into the + * Handle adding resources found in bundle fragments, and add them into the */ public class OSGiMetaInfConfiguration extends MetaInfConfiguration { private static final Logger LOG = Log.getLogger(WebInfConfiguration.class); - + /** * Comma separated list of symbolic names of bundles that contain tlds that should be considered * as on the container classpath @@ -68,26 +66,25 @@ public class OSGiMetaInfConfiguration extends MetaInfConfiguration public static final String CONTAINER_BUNDLE_PATTERN = "org.eclipse.jetty.server.webapp.containerIncludeBundlePattern"; public static final String FRAGMENT_AND_REQUIRED_BUNDLES = "org.eclipse.jetty.osgi.fragmentAndRequiredBundles"; public static final String FRAGMENT_AND_REQUIRED_RESOURCES = "org.eclipse.jetty.osgi.fragmentAndRequiredResources"; - + @Override public Class replaces() { return MetaInfConfiguration.class; } - - /* ------------------------------------------------------------ */ - /** + + /** * Check to see if there have been any bundle symbolic names added of bundles that should be * regarded as being on the container classpath, and scanned for fragments, tlds etc etc. * This can be defined in: *
      - *
    1. SystemProperty SYS_PROP_TLD_BUNDLES
    2. - *
    3. DeployerManager.setContextAttribute CONTAINER_BUNDLE_PATTERN
    4. - *
    - * - * We also allow individual bundles to specify particular bundles that might include TLDs via the Require-Tlds - * MANIFEST.MF header. - * + *
  • SystemProperty SYS_PROP_TLD_BUNDLES
  • + *
  • DeployerManager.setContextAttribute CONTAINER_BUNDLE_PATTERN
  • + * + * + * We also allow individual bundles to specify particular bundles that might include TLDs via the Require-Tlds + * MANIFEST.MF header. + * * @see org.eclipse.jetty.webapp.WebInfConfiguration#preConfigure(org.eclipse.jetty.webapp.WebAppContext) */ @Override @@ -95,7 +92,7 @@ public class OSGiMetaInfConfiguration extends MetaInfConfiguration { super.preConfigure(context); } - + @Override protected void scanJars(final WebAppContext context) throws Exception { @@ -105,20 +102,22 @@ public class OSGiMetaInfConfiguration extends MetaInfConfiguration // 1. SystemProperty SYS_PROP_TLD_BUNDLES // 2. DeployerManager.setContextAttribute CONTAINER_BUNDLE_PATTERN String tmp = (String)context.getAttribute(CONTAINER_BUNDLE_PATTERN); - Pattern pattern = (tmp==null?null:Pattern.compile(tmp)); + Pattern pattern = (tmp == null ? null : Pattern.compile(tmp)); List names = new ArrayList(); tmp = System.getProperty(SYS_PROP_TLD_BUNDLES); if (tmp != null) { StringTokenizer tokenizer = new StringTokenizer(tmp, ", \n\r\t", false); while (tokenizer.hasMoreTokens()) + { names.add(tokenizer.nextToken()); + } } HashSet matchingResources = new HashSet(); - if ( !names.isEmpty() || pattern != null) + if (!names.isEmpty() || pattern != null) { Bundle[] bundles = FrameworkUtil.getBundle(OSGiMetaInfConfiguration.class).getBundleContext().getBundles(); - + for (Bundle bundle : bundles) { LOG.debug("Checking bundle {}:{}", bundle.getBundleId(), bundle.getSymbolicName()); @@ -130,7 +129,7 @@ public class OSGiMetaInfConfiguration extends MetaInfConfiguration //get the file location of the jar and put it into the list of container jars that will be scanned for stuff (including tlds) matchingResources.addAll(getBundleAsResource(bundle)); } - } + } if (names != null) { //if there is an explicit bundle name, then check if it matches @@ -138,39 +137,38 @@ public class OSGiMetaInfConfiguration extends MetaInfConfiguration matchingResources.addAll(getBundleAsResource(bundle)); } } - } - for (Resource r:matchingResources) + } + for (Resource r : matchingResources) { context.getMetaData().addContainerResource(r); } - + super.scanJars(context); } - + @Override public void postConfigure(WebAppContext context) throws Exception { - context.setAttribute(FRAGMENT_AND_REQUIRED_BUNDLES, null); + context.setAttribute(FRAGMENT_AND_REQUIRED_BUNDLES, null); context.setAttribute(FRAGMENT_AND_REQUIRED_RESOURCES, null); super.postConfigure(context); } - - /* ------------------------------------------------------------ */ - /** + + /** * Consider the fragment bundles associated with the bundle of the webapp being deployed. - * + * * @see org.eclipse.jetty.webapp.MetaInfConfiguration#findJars(org.eclipse.jetty.webapp.WebAppContext) */ @Override - protected List findJars (WebAppContext context) - throws Exception + protected List findJars(WebAppContext context) + throws Exception { List mergedResources = new ArrayList(); //get jars from WEB-INF/lib if there are any List webInfJars = super.findJars(context); if (webInfJars != null) mergedResources.addAll(webInfJars); - + //add fragment jars and any Required-Bundles as if in WEB-INF/lib of the associated webapp Bundle[] bundles = PackageAdminServiceTracker.INSTANCE.getFragmentsAndRequiredBundles((Bundle)context.getAttribute(OSGiWebappConstants.JETTY_OSGI_BUNDLE)); if (bundles != null && bundles.length > 0) @@ -181,20 +179,20 @@ public class OSGiMetaInfConfiguration extends MetaInfConfiguration fragsAndReqsBundles = new HashSet(); context.setAttribute(FRAGMENT_AND_REQUIRED_BUNDLES, fragsAndReqsBundles); } - + Set fragsAndReqsResources = (Set)context.getAttribute(FRAGMENT_AND_REQUIRED_RESOURCES); if (fragsAndReqsResources == null) { fragsAndReqsResources = new HashSet(); context.setAttribute(FRAGMENT_AND_REQUIRED_RESOURCES, fragsAndReqsResources); } - + for (Bundle b : bundles) { //skip bundles that are not installed if (b.getState() == Bundle.UNINSTALLED) continue; - + //add to context attribute storing associated fragments and required bundles fragsAndReqsBundles.add(b); File f = BundleFileLocatorHelperFactory.getFactory().getHelper().getBundleInstallLocation(b); @@ -204,16 +202,15 @@ public class OSGiMetaInfConfiguration extends MetaInfConfiguration mergedResources.add(r); } } - + return mergedResources; } - - /* ------------------------------------------------------------ */ - /** + + /** * Allow fragments to supply some resources that are added to the baseResource of the webapp. - * + * * The resources can be either prepended or appended to the baseResource. - * + * * @see org.eclipse.jetty.webapp.WebInfConfiguration#configure(org.eclipse.jetty.webapp.WebAppContext) */ @Override @@ -221,7 +218,7 @@ public class OSGiMetaInfConfiguration extends MetaInfConfiguration { TreeMap prependedResourcesPath = new TreeMap(); TreeMap appendedResourcesPath = new TreeMap(); - + Bundle bundle = (Bundle)context.getAttribute(OSGiWebappConstants.JETTY_OSGI_BUNDLE); if (bundle != null) { @@ -257,32 +254,30 @@ public class OSGiMetaInfConfiguration extends MetaInfConfiguration resources.addAll(resourceDirs); //Then append the values from JETTY_WAR_FRAGMENT_FOLDER_PATH resources.addAll(appendedResourcesPath.values()); - + context.setAttribute(MetaInfConfiguration.RESOURCE_DIRS, resources); } } } - + super.configure(context); // place the prepended resources at the beginning of the contexts's resource base if (!prependedResourcesPath.isEmpty()) { - Resource[] resources = new Resource[1+prependedResourcesPath.size()]; + Resource[] resources = new Resource[1 + prependedResourcesPath.size()]; System.arraycopy(prependedResourcesPath.values().toArray(new Resource[prependedResourcesPath.size()]), 0, resources, 0, prependedResourcesPath.size()); - resources[resources.length-1] = context.getBaseResource(); + resources[resources.length - 1] = context.getBaseResource(); context.setBaseResource(new ResourceCollection(resources)); } } - - /* ------------------------------------------------------------ */ /** - * Resolves the bundle. Usually that would be a single URL per bundle. But we do some more work if there are jars - * embedded in the bundle. - */ - private List getBundleAsResource(Bundle bundle) - throws Exception + * Resolves the bundle. Usually that would be a single URL per bundle. But we do some more work if there are jars + * embedded in the bundle. + */ + private List getBundleAsResource(Bundle bundle) + throws Exception { List resources = new ArrayList(); @@ -312,32 +307,23 @@ public class OSGiMetaInfConfiguration extends MetaInfConfiguration { resources.add(Resource.newResource(file)); } - + return resources; } - /** * Convert a path inside a fragment into a Resource - * @param resourcePath - * @param fragment - * @param resourceMap - * @throws Exception */ - private void convertFragmentPathToResource (String resourcePath, Bundle fragment, Map resourceMap ) - throws Exception + private void convertFragmentPathToResource(String resourcePath, Bundle fragment, Map resourceMap) + throws Exception { if (resourcePath == null) return; URL url = fragment.getEntry(resourcePath); - if (url == null) - { - throw new IllegalArgumentException("Unable to locate " + resourcePath - + " inside " - + " the fragment '" - + fragment.getSymbolicName() - + "'"); + if (url == null) + { + throw new IllegalArgumentException("Unable to locate " + resourcePath + " inside the fragment '" + fragment.getSymbolicName() + "'"); } url = BundleFileLocatorHelperFactory.getFactory().getHelper().getLocalURL(url); String key = resourcePath.startsWith("/") ? resourcePath.substring(1) : resourcePath; @@ -345,7 +331,7 @@ public class OSGiMetaInfConfiguration extends MetaInfConfiguration URI uri; try { - uri = url.toURI(); + uri = url.toURI(); } catch (URISyntaxException e) { diff --git a/jetty-osgi/jetty-osgi-boot/src/main/java/org/eclipse/jetty/osgi/boot/OSGiServerConstants.java b/jetty-osgi/jetty-osgi-boot/src/main/java/org/eclipse/jetty/osgi/boot/OSGiServerConstants.java index b66e097ed04..3795396fd8a 100644 --- a/jetty-osgi/jetty-osgi-boot/src/main/java/org/eclipse/jetty/osgi/boot/OSGiServerConstants.java +++ b/jetty-osgi/jetty-osgi-boot/src/main/java/org/eclipse/jetty/osgi/boot/OSGiServerConstants.java @@ -20,7 +20,7 @@ package org.eclipse.jetty.osgi.boot; /** * OSGiServerConstants - * + * * Name of the properties that configure a jetty Server OSGi service. */ public class OSGiServerConstants @@ -62,7 +62,7 @@ public class OSGiServerConstants * PID of the jetty servers's ManagedFactory */ public static final String MANAGED_JETTY_SERVER_FACTORY_PID = "org.eclipse.jetty.osgi.boot.managedserverfactory"; - + /** * The associated value of that configuration parameter is the name under which this * instance of the jetty server is tracked. @@ -75,12 +75,12 @@ public class OSGiServerConstants * Usually the first one to be created. */ public static final String MANAGED_JETTY_SERVER_DEFAULT_NAME = "defaultJettyServer"; - + /** * List of URLs to the jetty.xml files that configure th server. */ public static final String MANAGED_JETTY_XML_CONFIG_URLS = "jetty.etc.config.urls"; - + /** * List of URLs to the folders where the legacy J2EE shared libraries are stored aka lib/ext, lib/jsp etc. */ diff --git a/jetty-osgi/jetty-osgi-boot/src/main/java/org/eclipse/jetty/osgi/boot/OSGiUndeployer.java b/jetty-osgi/jetty-osgi-boot/src/main/java/org/eclipse/jetty/osgi/boot/OSGiUndeployer.java index 0e113da0270..90fc0daf06a 100644 --- a/jetty-osgi/jetty-osgi-boot/src/main/java/org/eclipse/jetty/osgi/boot/OSGiUndeployer.java +++ b/jetty-osgi/jetty-osgi-boot/src/main/java/org/eclipse/jetty/osgi/boot/OSGiUndeployer.java @@ -24,29 +24,21 @@ import org.eclipse.jetty.deploy.graph.Node; import org.eclipse.jetty.osgi.boot.internal.serverfactory.ServerInstanceWrapper; import org.eclipse.jetty.osgi.boot.utils.EventSender; - - - /** * OSGiUndeployer * * Extension of the Jetty Undeployer which emits OSGi EventAdmin events * whenever a webapp is undeployed from Jetty. - * */ public class OSGiUndeployer extends StandardUndeployer { private ServerInstanceWrapper _server; - - /* ------------------------------------------------------------ */ - public OSGiUndeployer (ServerInstanceWrapper server) + public OSGiUndeployer(ServerInstanceWrapper server) { _server = server; } - - - /* ------------------------------------------------------------ */ + @Override public void processBinding(Node node, App app) throws Exception { @@ -55,9 +47,9 @@ public class OSGiUndeployer extends StandardUndeployer Thread.currentThread().setContextClassLoader(_server.getParentClassLoaderForWebapps()); try { - super.processBinding(node,app); + super.processBinding(node, app); } - finally + finally { Thread.currentThread().setContextClassLoader(old); } diff --git a/jetty-osgi/jetty-osgi-boot/src/main/java/org/eclipse/jetty/osgi/boot/OSGiWebInfConfiguration.java b/jetty-osgi/jetty-osgi-boot/src/main/java/org/eclipse/jetty/osgi/boot/OSGiWebInfConfiguration.java index d3415119820..b4a4dc9758d 100644 --- a/jetty-osgi/jetty-osgi-boot/src/main/java/org/eclipse/jetty/osgi/boot/OSGiWebInfConfiguration.java +++ b/jetty-osgi/jetty-osgi-boot/src/main/java/org/eclipse/jetty/osgi/boot/OSGiWebInfConfiguration.java @@ -21,12 +21,10 @@ package org.eclipse.jetty.osgi.boot; import org.eclipse.jetty.webapp.Configuration; import org.eclipse.jetty.webapp.WebInfConfiguration; - - /** * OSGiWebInfConfiguration * - * Handle adding resources found in bundle fragments, and add them into the + * Handle adding resources found in bundle fragments, and add them into the */ public class OSGiWebInfConfiguration extends WebInfConfiguration { diff --git a/jetty-osgi/jetty-osgi-boot/src/main/java/org/eclipse/jetty/osgi/boot/OSGiWebappConstants.java b/jetty-osgi/jetty-osgi-boot/src/main/java/org/eclipse/jetty/osgi/boot/OSGiWebappConstants.java index 53258bffedf..35581168bbc 100644 --- a/jetty-osgi/jetty-osgi-boot/src/main/java/org/eclipse/jetty/osgi/boot/OSGiWebappConstants.java +++ b/jetty-osgi/jetty-osgi-boot/src/main/java/org/eclipse/jetty/osgi/boot/OSGiWebappConstants.java @@ -20,29 +20,36 @@ package org.eclipse.jetty.osgi.boot; /** * OSGiWebappConstants - * - * + * + * * Constants (MANIFEST headers, service properties etc) associated with deploying * webapps into OSGi via Jetty. - * */ public class OSGiWebappConstants { - /** service property osgi.web.symbolicname. See OSGi r4 */ + /** + * service property osgi.web.symbolicname. See OSGi r4 + */ public static final String OSGI_WEB_SYMBOLICNAME = "osgi.web.symbolicname"; - - /** service property osgi.web.symbolicname. See OSGi r4 */ + + /** + * service property osgi.web.symbolicname. See OSGi r4 + */ public static final String OSGI_WEB_VERSION = "osgi.web.version"; - - /** service property osgi.web.contextpath. See OSGi r4 */ + + /** + * service property osgi.web.contextpath. See OSGi r4 + */ public static final String OSGI_WEB_CONTEXTPATH = "osgi.web.contextpath"; - - /** See OSGi r4 p.427 */ + + /** + * See OSGi r4 p.427 + */ public static final String OSGI_BUNDLECONTEXT = "osgi-bundlecontext"; - - - /** url scheme to deploy war file as bundled webapp */ + /** + * url scheme to deploy war file as bundled webapp + */ public static final String RFC66_WAR_URL_SCHEME = "war"; /** @@ -56,26 +63,38 @@ public class OSGiWebappConstants */ public static final String RFC66_JSP_EXTRACT_LOCATION = "Jsp-ExtractLocation"; - /** Name of the servlet context attribute that points to the bundle context. */ + /** + * Name of the servlet context attribute that points to the bundle context. + */ public static final String RFC66_OSGI_BUNDLE_CONTEXT = "osgi-bundlecontext"; - /** Name of the servlet context attribute that points to the bundle object. - * We can't always rely on the bundle-context as there might be no such thing. */ + /** + * Name of the servlet context attribute that points to the bundle object. + * We can't always rely on the bundle-context as there might be no such thing. + */ public static final String JETTY_OSGI_BUNDLE = "osgi-bundle"; - /** List of relative pathes within the bundle to the jetty context files. */ + /** + * List of relative pathes within the bundle to the jetty context files. + */ public static final String JETTY_CONTEXT_FILE_PATH = "Jetty-ContextFilePath"; - /** path within the bundle to the folder that contains the basic resources. */ + /** + * path within the bundle to the folder that contains the basic resources. + */ public static final String JETTY_WAR_RESOURCE_PATH = "Jetty-WarResourcePath"; - /** path within a fragment hosted by a web-bundle to a folder that contains basic resources. - * the path is appended to the lookup path where jetty locates static resources */ + /** + * path within a fragment hosted by a web-bundle to a folder that contains basic resources. + * the path is appended to the lookup path where jetty locates static resources + */ public static final String JETTY_WAR_FRAGMENT_RESOURCE_PATH = "Jetty-WarFragmentResourcePath"; - /** path within a fragment hosted by a web-bundle to a folder that contains basic resources. + /** + * path within a fragment hosted by a web-bundle to a folder that contains basic resources. * The path is prefixed to the lookup path where jetty locates static resources: - * this will override static resources with the same name in the web-bundle. */ + * this will override static resources with the same name in the web-bundle. + */ public static final String JETTY_WAR_PREPEND_FRAGMENT_RESOURCE_PATH = "Jetty-WarPrependFragmentResourcePath"; /** @@ -89,17 +108,15 @@ public class OSGiWebappConstants public static final String JETTY_EXTRA_CLASSPATH = "Jetty-extraClasspath"; /** - * web.xml file path + * web.xml file path */ public static final String JETTY_WEB_XML_PATH = "Jetty-WebXmlFilePath"; - - /** - * defaultweb.xml file path + /** + * defaultweb.xml file path */ public static final String JETTY_DEFAULT_WEB_XML_PATH = "Jetty-defaultWebXmlFilePath"; - /** * path to the base folder that overrides the computed bundle installation * location if not null useful to install webapps or jetty context files @@ -107,7 +124,6 @@ public class OSGiWebappConstants */ public static final String JETTY_BUNDLE_INSTALL_LOCATION_OVERRIDE = "Jetty-bundleInstall"; - /** * Comma separated list of bundles that contain tld file used by the webapp. */ @@ -117,14 +133,11 @@ public class OSGiWebappConstants * Both the name of the manifest header and the name of the service property. */ public static final String SERVICE_PROP_REQUIRE_TLD_BUNDLE = REQUIRE_TLD_BUNDLE; - + public static final String WATERMARK = "o.e.j.o.b.watermark"; - + /** * Set of extra dirs that must not be served by osgi webapps */ public static final String[] DEFAULT_PROTECTED_OSGI_TARGETS = {"/osgi-inf", "/osgi-opts"}; - - - } diff --git a/jetty-osgi/jetty-osgi-boot/src/main/java/org/eclipse/jetty/osgi/boot/ServiceContextProvider.java b/jetty-osgi/jetty-osgi-boot/src/main/java/org/eclipse/jetty/osgi/boot/ServiceContextProvider.java index aad726462ac..f7a2aa7c1a0 100644 --- a/jetty-osgi/jetty-osgi-boot/src/main/java/org/eclipse/jetty/osgi/boot/ServiceContextProvider.java +++ b/jetty-osgi/jetty-osgi-boot/src/main/java/org/eclipse/jetty/osgi/boot/ServiceContextProvider.java @@ -44,55 +44,50 @@ import org.osgi.util.tracker.ServiceTracker; * ServiceContextProvider * * Jetty DeploymentManager Provider that is able to deploy ContextHandlers discovered via OSGi as services. - * - * */ public class ServiceContextProvider extends AbstractContextProvider implements ServiceProvider -{ +{ private static final Logger LOG = Log.getLogger(AbstractContextProvider.class); - + private Map _serviceMap = new HashMap<>(); - + private ServiceRegistration _serviceRegForServices; - + ServiceTracker _tracker; - - + /** * ContextTracker - * - * */ public class ContextTracker extends ServiceTracker { - - public ContextTracker (BundleContext bundleContext, Filter filter) + + public ContextTracker(BundleContext bundleContext, Filter filter) { super(bundleContext, filter, null); } - /** + /** * @see org.osgi.util.tracker.ServiceTracker#addingService(org.osgi.framework.ServiceReference) */ @Override public Object addingService(ServiceReference reference) { ContextHandler h = (ContextHandler)context.getService(reference); - serviceAdded (reference, h); + serviceAdded(reference, h); return h; } - /** + /** * @see org.osgi.util.tracker.ServiceTracker#modifiedService(org.osgi.framework.ServiceReference, java.lang.Object) */ @Override public void modifiedService(ServiceReference reference, Object service) { - removedService(reference,service); + removedService(reference, service); addingService(reference); } - /** + /** * @see org.osgi.util.tracker.ServiceTracker#removedService(org.osgi.framework.ServiceReference, java.lang.Object) */ @Override @@ -102,13 +97,9 @@ public class ServiceContextProvider extends AbstractContextProvider implements S serviceRemoved(reference, (ContextHandler)service); } } - - - + /** * ServiceApp - * - * */ public class ServiceApp extends OSGiApp { @@ -134,30 +125,25 @@ public class ServiceContextProvider extends AbstractContextProvider implements S //not applicable for apps that are already services } } - - - - /* ------------------------------------------------------------ */ + public ServiceContextProvider(ServerInstanceWrapper wrapper) { super(wrapper); } - - - /* ------------------------------------------------------------ */ + @Override - public boolean serviceAdded (ServiceReference serviceRef, ContextHandler context) + public boolean serviceAdded(ServiceReference serviceRef, ContextHandler context) { if (context == null || serviceRef == null) return false; - + if (context instanceof org.eclipse.jetty.webapp.WebAppContext) return false; //the ServiceWebAppProvider will deploy it - + String watermark = (String)serviceRef.getProperty(OSGiWebappConstants.WATERMARK); if (watermark != null && !"".equals(watermark)) return false; //this service represents a contexthandler that has already been registered as a service by another of our deployers - + ClassLoader cl = Thread.currentThread().getContextClassLoader(); Thread.currentThread().setContextClassLoader(getServerInstanceWrapper().getParentClassLoaderForWebapps()); try @@ -166,15 +152,17 @@ public class ServiceContextProvider extends AbstractContextProvider implements S String contextFile = (String)serviceRef.getProperty(OSGiWebappConstants.JETTY_CONTEXT_FILE_PATH); String[] keys = serviceRef.getPropertyKeys(); - Dictionary properties = new Hashtable<>(); + Dictionary properties = new Hashtable<>(); if (keys != null) { - for (String key:keys) + for (String key : keys) + { properties.put(key, serviceRef.getProperty(key)); + } } - Bundle bundle = serviceRef.getBundle(); - String originId = bundle.getSymbolicName() + "-" + bundle.getVersion().toString() + "-"+(contextFile!=null?contextFile:serviceRef.getProperty(Constants.SERVICE_ID)); - ServiceApp app = new ServiceApp(getDeploymentManager(), this, bundle, properties, contextFile, originId); + Bundle bundle = serviceRef.getBundle(); + String originId = bundle.getSymbolicName() + "-" + bundle.getVersion().toString() + "-" + (contextFile != null ? contextFile : serviceRef.getProperty(Constants.SERVICE_ID)); + ServiceApp app = new ServiceApp(getDeploymentManager(), this, bundle, properties, contextFile, originId); app.setHandler(context); //set the pre=made ContextHandler instance _serviceMap.put(serviceRef, app); getDeploymentManager().addApp(app); @@ -182,23 +170,21 @@ public class ServiceContextProvider extends AbstractContextProvider implements S } finally { - Thread.currentThread().setContextClassLoader(cl); + Thread.currentThread().setContextClassLoader(cl); } } - - - /* ------------------------------------------------------------ */ + @Override - public boolean serviceRemoved (ServiceReference serviceRef, ContextHandler context) + public boolean serviceRemoved(ServiceReference serviceRef, ContextHandler context) { if (context == null || serviceRef == null) return false; - + String watermark = (String)serviceRef.getProperty(OSGiWebappConstants.WATERMARK); if (watermark != null && !"".equals(watermark)) return false; //this service represents a contexthandler that will be deregistered as a service by another of our deployers - + App app = _serviceMap.remove(serviceRef); if (app != null) { @@ -208,10 +194,7 @@ public class ServiceContextProvider extends AbstractContextProvider implements S return false; } - - - - /* ------------------------------------------------------------ */ + @Override protected void doStart() throws Exception { @@ -219,27 +202,25 @@ public class ServiceContextProvider extends AbstractContextProvider implements S BundleContext bundleContext = FrameworkUtil.getBundle(this.getClass()).getBundleContext(); //Start a tracker to find webapps that are osgi services that are targeted to my server name - _tracker = new ContextTracker (bundleContext, - Util.createFilter(bundleContext, ContextHandler.class.getName(), getServerInstanceWrapper().getManagedServerName())); + _tracker = new ContextTracker(bundleContext, + Util.createFilter(bundleContext, ContextHandler.class.getName(), getServerInstanceWrapper().getManagedServerName())); _tracker.open(); - //register as an osgi service for deploying contexts defined in a bundle, advertising the name of the jetty Server instance we are related to - Dictionary properties = new Hashtable<>(); + Dictionary properties = new Hashtable<>(); properties.put(OSGiServerConstants.MANAGED_JETTY_SERVER_NAME, getServerInstanceWrapper().getManagedServerName()); - + //register as an osgi service for deploying contexts, advertising the name of the jetty Server instance we are related to _serviceRegForServices = FrameworkUtil.getBundle(this.getClass()).getBundleContext().registerService(ServiceProvider.class.getName(), this, properties); super.doStart(); } - - /* ------------------------------------------------------------ */ + @Override protected void doStop() throws Exception { if (_tracker != null) _tracker.close(); - + //unregister ourselves if (_serviceRegForServices != null) { diff --git a/jetty-osgi/jetty-osgi-boot/src/main/java/org/eclipse/jetty/osgi/boot/ServiceProvider.java b/jetty-osgi/jetty-osgi-boot/src/main/java/org/eclipse/jetty/osgi/boot/ServiceProvider.java index 036830b789f..916f3b17a5b 100644 --- a/jetty-osgi/jetty-osgi-boot/src/main/java/org/eclipse/jetty/osgi/boot/ServiceProvider.java +++ b/jetty-osgi/jetty-osgi-boot/src/main/java/org/eclipse/jetty/osgi/boot/ServiceProvider.java @@ -28,7 +28,7 @@ import org.osgi.framework.ServiceReference; */ public interface ServiceProvider { - public boolean serviceAdded (ServiceReference ref, ContextHandler handler) throws Exception; - - public boolean serviceRemoved (ServiceReference ref, ContextHandler handler) throws Exception; + public boolean serviceAdded(ServiceReference ref, ContextHandler handler) throws Exception; + + public boolean serviceRemoved(ServiceReference ref, ContextHandler handler) throws Exception; } diff --git a/jetty-osgi/jetty-osgi-boot/src/main/java/org/eclipse/jetty/osgi/boot/ServiceWebAppProvider.java b/jetty-osgi/jetty-osgi-boot/src/main/java/org/eclipse/jetty/osgi/boot/ServiceWebAppProvider.java index ec363514ba4..d5409d479c1 100644 --- a/jetty-osgi/jetty-osgi-boot/src/main/java/org/eclipse/jetty/osgi/boot/ServiceWebAppProvider.java +++ b/jetty-osgi/jetty-osgi-boot/src/main/java/org/eclipse/jetty/osgi/boot/ServiceWebAppProvider.java @@ -46,23 +46,20 @@ import org.osgi.util.tracker.ServiceTracker; * Jetty Provider that knows how to deploy a WebApp that has been registered as an OSGi service. */ public class ServiceWebAppProvider extends AbstractWebAppProvider implements ServiceProvider -{ +{ private static final Logger LOG = Log.getLogger(AbstractWebAppProvider.class); - + /** * Map of ServiceRef to App. Used when it is an osgi service that is a WebAppContext. */ private Map _serviceMap = new HashMap<>(); - + private ServiceRegistration _serviceRegForServices; - + private ServiceTracker webappTracker; - /** * WebAppTracker - * - * */ public class WebAppTracker extends ServiceTracker { @@ -70,33 +67,33 @@ public class ServiceWebAppProvider extends AbstractWebAppProvider implements Ser * @param bundleContext the osgi context * @param filter the osgi filter for the tracker */ - public WebAppTracker (BundleContext bundleContext, Filter filter) + public WebAppTracker(BundleContext bundleContext, Filter filter) { super(bundleContext, filter, null); } - /** + /** * @see org.osgi.util.tracker.ServiceTracker#addingService(org.osgi.framework.ServiceReference) */ @Override public Object addingService(ServiceReference reference) { WebAppContext wac = (WebAppContext)context.getService(reference); - serviceAdded (reference, wac); + serviceAdded(reference, wac); return wac; } - /** + /** * @see org.osgi.util.tracker.ServiceTracker#modifiedService(org.osgi.framework.ServiceReference, java.lang.Object) */ @Override public void modifiedService(ServiceReference reference, Object service) { - removedService(reference,service); + removedService(reference, service); addingService(reference); } - /** + /** * @see org.osgi.util.tracker.ServiceTracker#removedService(org.osgi.framework.ServiceReference, java.lang.Object) */ @Override @@ -106,17 +103,14 @@ public class ServiceWebAppProvider extends AbstractWebAppProvider implements Ser context.ungetService(reference); } } - - + /** * ServiceApp - * - * */ public class ServiceApp extends OSGiApp { - public ServiceApp(DeploymentManager manager, AppProvider provider, Bundle bundle, Dictionary properties, String originId) + public ServiceApp(DeploymentManager manager, AppProvider provider, Bundle bundle, Dictionary properties, String originId) { super(manager, provider, bundle, properties, originId); } @@ -138,46 +132,40 @@ public class ServiceWebAppProvider extends AbstractWebAppProvider implements Ser //not applicable for apps that are already services } } - - - - /* ------------------------------------------------------------ */ - public ServiceWebAppProvider (ServerInstanceWrapper wrapper) + + public ServiceWebAppProvider(ServerInstanceWrapper wrapper) { super(wrapper); } - - - /* ------------------------------------------------------------ */ + /** * A webapp that was deployed as an osgi service has been added, * and we want to deploy it. - * + * * @param context the webapp */ @Override - public boolean serviceAdded (ServiceReference serviceRef, ContextHandler context) - { + public boolean serviceAdded(ServiceReference serviceRef, ContextHandler context) + { if (context == null || !(context instanceof WebAppContext)) return false; - + String watermark = (String)serviceRef.getProperty(OSGiWebappConstants.WATERMARK); if (watermark != null && !"".equals(watermark)) return false; //this service represents a webapp that has already been registered as a service by another of our deployers - - + WebAppContext webApp = (WebAppContext)context; - Dictionary properties = new Hashtable<>(); - + Dictionary properties = new Hashtable<>(); + String contextPath = (String)serviceRef.getProperty(OSGiWebappConstants.RFC66_WEB_CONTEXTPATH); if (contextPath == null) return false; //No context path - + String base = (String)serviceRef.getProperty(OSGiWebappConstants.JETTY_WAR_RESOURCE_PATH); - if (base == null) - return false; //No webapp base - + if (base == null) + return false; //No webapp base + String webdefaultXml = (String)serviceRef.getProperty(OSGiWebappConstants.JETTY_DEFAULT_WEB_XML_PATH); if (webdefaultXml != null) properties.put(OSGiWebappConstants.JETTY_DEFAULT_WEB_XML_PATH, webdefaultXml); @@ -194,7 +182,7 @@ public class ServiceWebAppProvider extends AbstractWebAppProvider implements Ser if (bundleInstallOverride != null) properties.put(OSGiWebappConstants.JETTY_BUNDLE_INSTALL_LOCATION_OVERRIDE, bundleInstallOverride); - String requiredTlds = (String)serviceRef.getProperty(OSGiWebappConstants.REQUIRE_TLD_BUNDLE); + String requiredTlds = (String)serviceRef.getProperty(OSGiWebappConstants.REQUIRE_TLD_BUNDLE); if (requiredTlds == null) requiredTlds = (String)serviceRef.getProperty(OSGiWebappConstants.SERVICE_PROP_REQUIRE_TLD_BUNDLE); if (requiredTlds != null) @@ -215,26 +203,23 @@ public class ServiceWebAppProvider extends AbstractWebAppProvider implements Ser } finally { - Thread.currentThread().setContextClassLoader(cl); + Thread.currentThread().setContextClassLoader(cl); } } - - - - /* ------------------------------------------------------------ */ + /** * @param context the webapp */ @Override - public boolean serviceRemoved (ServiceReference serviceRef, ContextHandler context) + public boolean serviceRemoved(ServiceReference serviceRef, ContextHandler context) { if (context == null || !(context instanceof WebAppContext)) return false; - + String watermark = (String)serviceRef.getProperty(OSGiWebappConstants.WATERMARK); if (watermark != null && !"".equals(watermark)) return false; //this service represents a contexthandler that will be deregistered as a service by another of our deployers - + App app = _serviceMap.remove(serviceRef); if (app != null) { @@ -243,10 +228,8 @@ public class ServiceWebAppProvider extends AbstractWebAppProvider implements Ser } return false; } - - - /* ------------------------------------------------------------ */ - /** + + /** * @see org.eclipse.jetty.util.component.AbstractLifeCycle#doStart() */ @Override @@ -255,28 +238,27 @@ public class ServiceWebAppProvider extends AbstractWebAppProvider implements Ser BundleContext bundleContext = FrameworkUtil.getBundle(this.getClass()).getBundleContext(); //Start a tracker to find webapps that are osgi services that are targeted to my server name - webappTracker = new WebAppTracker (bundleContext, - Util.createFilter(bundleContext, WebAppContext.class.getName(), getServerInstanceWrapper().getManagedServerName())); + webappTracker = new WebAppTracker(bundleContext, + Util.createFilter(bundleContext, WebAppContext.class.getName(), getServerInstanceWrapper().getManagedServerName())); webappTracker.open(); - + //register as an osgi service for deploying bundles, advertising the name of the jetty Server instance we are related to - Dictionary properties = new Hashtable<>(); + Dictionary properties = new Hashtable<>(); properties.put(OSGiServerConstants.MANAGED_JETTY_SERVER_NAME, getServerInstanceWrapper().getManagedServerName()); - + //register as an osgi service for deploying contexts (discovered as osgi services), advertising the name of the jetty Server instance we are related to _serviceRegForServices = FrameworkUtil.getBundle(this.getClass()).getBundleContext().registerService(ServiceProvider.class.getName(), this, properties); super.doStart(); } - /* ------------------------------------------------------------ */ - /** + /** * @see org.eclipse.jetty.util.component.AbstractLifeCycle#doStop() */ @Override protected void doStop() throws Exception { webappTracker.close(); - + //unregister ourselves if (_serviceRegForServices != null) { @@ -291,5 +273,4 @@ public class ServiceWebAppProvider extends AbstractWebAppProvider implements Ser } super.doStop(); } - } diff --git a/jetty-osgi/jetty-osgi-boot/src/main/java/org/eclipse/jetty/osgi/boot/internal/serverfactory/DefaultJettyAtJettyHomeHelper.java b/jetty-osgi/jetty-osgi-boot/src/main/java/org/eclipse/jetty/osgi/boot/internal/serverfactory/DefaultJettyAtJettyHomeHelper.java index 22999850d60..95f27927ffb 100644 --- a/jetty-osgi/jetty-osgi-boot/src/main/java/org/eclipse/jetty/osgi/boot/internal/serverfactory/DefaultJettyAtJettyHomeHelper.java +++ b/jetty-osgi/jetty-osgi-boot/src/main/java/org/eclipse/jetty/osgi/boot/internal/serverfactory/DefaultJettyAtJettyHomeHelper.java @@ -47,9 +47,9 @@ import org.osgi.framework.BundleContext; * Creates a default instance of Jetty, based on the values of the * System properties "jetty.home" or "jetty.home.bundle", one of which * must be specified in order to create the default instance. - *

    + *

    * Called by the {@link JettyBootstrapActivator} during the starting of the - * bundle. + * bundle. */ public class DefaultJettyAtJettyHomeHelper { @@ -64,15 +64,12 @@ public class DefaultJettyAtJettyHomeHelper * Set of config files to apply to a jetty Server instance if none are supplied by SYS_PROP_JETTY_ETC_FILES */ public static final String DEFAULT_JETTY_ETC_FILES = "etc/jetty.xml,etc/jetty-http.xml,etc/jetty-deployer.xml"; - + /** * Default location within bundle of a jetty home dir. */ public static final String DEFAULT_JETTYHOME = "/jettyhome"; - - - - /* ------------------------------------------------------------ */ + /** * Called by the JettyBootStrapActivator. If the system property jetty.home * is defined and points to a folder, creates a corresponding jetty @@ -92,6 +89,7 @@ public class DefaultJettyAtJettyHomeHelper * jetty.ssl.port are passed to the configuration files that might use them * as part of their properties. *

    + * * @param bundleContext the bundle context * @return the configured server * @throws Exception if unable to create / configure / or start the server @@ -102,7 +100,7 @@ public class DefaultJettyAtJettyHomeHelper String jettyHomeBundleSysProp = System.getProperty(OSGiServerConstants.JETTY_HOME_BUNDLE); File jettyHomeDir = null; Bundle jettyHomeBundle = null; - + Dictionary properties = new Hashtable<>(); if (jettyHomeSysProp != null) { @@ -110,17 +108,17 @@ public class DefaultJettyAtJettyHomeHelper // bug 329621 if (jettyHomeSysProp.startsWith("\"") && jettyHomeSysProp.endsWith("\"") || (jettyHomeSysProp.startsWith("'") && jettyHomeSysProp.endsWith("'"))) jettyHomeSysProp = jettyHomeSysProp.substring(1, jettyHomeSysProp.length() - 1); - + if (jettyHomeBundleSysProp != null) LOG.warn("Both jetty.home and jetty.home.bundle property defined: jetty.home.bundle ignored."); - + jettyHomeDir = new File(jettyHomeSysProp); if (!jettyHomeDir.exists() || !jettyHomeDir.isDirectory()) { LOG.warn("Unable to locate the jetty.home folder " + jettyHomeSysProp); return null; } - + //set jetty.home Util.setProperty(properties, OSGiServerConstants.JETTY_HOME, jettyHomeDir.getAbsolutePath()); } @@ -131,7 +129,7 @@ public class DefaultJettyAtJettyHomeHelper { if (b.getState() == Bundle.UNINSTALLED) continue; - + if (b.getSymbolicName().equals(jettyHomeBundleSysProp)) { jettyHomeBundle = b; @@ -144,40 +142,38 @@ public class DefaultJettyAtJettyHomeHelper return null; } } - + if (jettyHomeDir == null && jettyHomeBundle == null) { LOG.warn("No default jetty created."); return null; } - - - + //configure the server here rather than letting the JettyServerServiceTracker do it, because we want to be able to //configure the ThreadPool, which can only be done via the constructor, ie from within the xml configuration processing List configURLs = jettyHomeDir != null ? getJettyConfigurationURLs(jettyHomeDir) : getJettyConfigurationURLs(jettyHomeBundle, properties); - LOG.info("Configuring the default jetty server with {}",configURLs); - String home=(String)properties.get(OSGiServerConstants.JETTY_HOME); - String base=(String)properties.get(OSGiServerConstants.JETTY_BASE); - if (base==null) - base=home; - LOG.info("JETTY.HOME="+home); - LOG.info("JETTY.BASE="+base); + LOG.info("Configuring the default jetty server with {}", configURLs); + String home = (String)properties.get(OSGiServerConstants.JETTY_HOME); + String base = (String)properties.get(OSGiServerConstants.JETTY_BASE); + if (base == null) + base = home; + LOG.info("JETTY.HOME=" + home); + LOG.info("JETTY.BASE=" + base); ClassLoader contextCl = Thread.currentThread().getContextClassLoader(); try { ClassLoader cl; if (jettyHomeBundle != null) { - cl = new OSGiClassLoader(JettyBootstrapActivator.class.getClassLoader(),jettyHomeBundle); + cl = new OSGiClassLoader(JettyBootstrapActivator.class.getClassLoader(), jettyHomeBundle); } else { cl = JettyBootstrapActivator.class.getClassLoader(); } Thread.currentThread().setContextClassLoader(cl); - + // these properties usually are the ones passed to this type of // configuration. properties.put(OSGiServerConstants.MANAGED_JETTY_SERVER_NAME, OSGiServerConstants.MANAGED_JETTY_SERVER_DEFAULT_NAME); @@ -187,7 +183,7 @@ public class DefaultJettyAtJettyHomeHelper Util.setProperty(properties, OSGiServerConstants.JETTY_HOME, home); Util.setProperty(properties, OSGiServerConstants.JETTY_BASE, base); Server server = ServerInstanceWrapper.configure(null, configURLs, properties); - + //Register the default Server instance as an OSGi service. //The JettyServerServiceTracker will notice it and set it up to deploy bundles as wars etc bundleContext.registerService(Server.class.getName(), server, properties); @@ -205,22 +201,14 @@ public class DefaultJettyAtJettyHomeHelper } } - - - - /* ------------------------------------------------------------ */ /** * Minimum setup for the location of the configuration files given a * jettyhome folder. Reads the system property jetty.etc.config.urls and * look for the corresponding jetty configuration files that will be used to * setup the jetty server. - * - * @param jettyhome - * @return - * @throws MalformedURLException */ - private static List getJettyConfigurationURLs(File jettyhome) - throws MalformedURLException + private static List getJettyConfigurationURLs(File jettyhome) + throws MalformedURLException { List configURLs = new ArrayList<>(); String jettyetc = System.getProperty(JETTY_ETC_FILES, DEFAULT_JETTY_ETC_FILES); @@ -229,29 +217,25 @@ public class DefaultJettyAtJettyHomeHelper { String next = tokenizer.nextToken().trim(); //etc files can either be relative to jetty.home or absolute disk locations - if (!next.startsWith("/") && (next.indexOf(':') == -1)) + if (!next.startsWith("/") && (next.indexOf(':') == -1)) configURLs.add(new File(jettyhome, next).toURI().toURL()); - else + else configURLs.add(new URL(next)); } return configURLs; } - /* ------------------------------------------------------------ */ /** * Minimum setup for the location of the configuration files given a * configuration embedded inside a bundle. Reads the system property * jetty.etc.config.urls and look for the corresponding jetty configuration * files that will be used to setup the jetty server. - * - * @param jettyhome - * @return */ private static List getJettyConfigurationURLs(Bundle configurationBundle, Dictionary properties) - throws Exception + throws Exception { List configURLs = new ArrayList<>(); - String files = System.getProperty(JETTY_ETC_FILES, DEFAULT_JETTY_ETC_FILES); + String files = System.getProperty(JETTY_ETC_FILES, DEFAULT_JETTY_ETC_FILES); StringTokenizer tokenizer = new StringTokenizer(files, ";,", false); while (tokenizer.hasMoreTokens()) @@ -271,10 +255,10 @@ public class DefaultJettyAtJettyHomeHelper if ((enUrls == null || !enUrls.hasMoreElements())) { home = DEFAULT_JETTYHOME; - String tmp = DEFAULT_JETTYHOME+(DEFAULT_JETTYHOME.endsWith("/")?"":"/")+etcFile; - enUrls = BundleFileLocatorHelperFactory.getFactory().getHelper().findEntries(configurationBundle, tmp); - LOG.info("Configuring jetty from bundle: {} with {}", configurationBundle.getSymbolicName(),tmp); - } + String tmp = DEFAULT_JETTYHOME + (DEFAULT_JETTYHOME.endsWith("/") ? "" : "/") + etcFile; + enUrls = BundleFileLocatorHelperFactory.getFactory().getHelper().findEntries(configurationBundle, tmp); + LOG.info("Configuring jetty from bundle: {} with {}", configurationBundle.getSymbolicName(), tmp); + } //lazily ensure jetty.home value is set based on location of etc files if (properties.get(OSGiServerConstants.JETTY_HOME) == null) @@ -283,27 +267,26 @@ public class DefaultJettyAtJettyHomeHelper if (res != null) properties.put(OSGiServerConstants.JETTY_HOME, res.toString()); } - + if (enUrls == null || !enUrls.hasMoreElements()) - throw new IllegalStateException ("Unable to locate a jetty configuration file for " + etcFile); + throw new IllegalStateException("Unable to locate a jetty configuration file for " + etcFile); URL url = BundleFileLocatorHelperFactory.getFactory().getHelper().getFileURL(enUrls.nextElement()); configURLs.add(url); - } } return configURLs; } - - /* ------------------------------------------------------------ */ + /** * Get a resource representing a directory inside a bundle. If the dir is null, * return a resource representing the installation location of the bundle. + * * @param bundle the bundle * @param dir the directory * @return the resource found */ - public static Resource findDir (Bundle bundle, String dir) + public static Resource findDir(Bundle bundle, String dir) { if (bundle == null) return null; @@ -315,21 +298,20 @@ public class DefaultJettyAtJettyHomeHelper u = BundleFileLocatorHelperFactory.getFactory().getHelper().getLocalURL(u); Resource res = Resource.newResource(u); String s = res.toString(); - + //check if it is an unarchived bundle if (s.endsWith(".jar") && s.startsWith("file:")) res = JarResource.newJarResource(res); - + //if looking for a directory if (dir != null) res = res.addPath(dir); - + return res; - } catch (Exception e) { - LOG.warn("Bad bundle location" , e); + LOG.warn("Bad bundle location", e); return null; } } diff --git a/jetty-osgi/jetty-osgi-boot/src/main/java/org/eclipse/jetty/osgi/boot/internal/serverfactory/JettyServerServiceTracker.java b/jetty-osgi/jetty-osgi-boot/src/main/java/org/eclipse/jetty/osgi/boot/internal/serverfactory/JettyServerServiceTracker.java index d60eb57fe59..03daafe65b9 100644 --- a/jetty-osgi/jetty-osgi-boot/src/main/java/org/eclipse/jetty/osgi/boot/internal/serverfactory/JettyServerServiceTracker.java +++ b/jetty-osgi/jetty-osgi-boot/src/main/java/org/eclipse/jetty/osgi/boot/internal/serverfactory/JettyServerServiceTracker.java @@ -20,7 +20,6 @@ package org.eclipse.jetty.osgi.boot.internal.serverfactory; import java.util.Dictionary; import java.util.Hashtable; -import java.util.Properties; import org.eclipse.jetty.osgi.boot.OSGiServerConstants; import org.eclipse.jetty.server.Server; @@ -32,29 +31,31 @@ import org.osgi.util.tracker.ServiceTrackerCustomizer; /** * JettyServerServiceTracker - * - * Tracks instances of Jetty Servers, and configures them so that they can deploy + * + * Tracks instances of Jetty Servers, and configures them so that they can deploy * webapps or ContextHandlers discovered from the OSGi environment. - * */ public class JettyServerServiceTracker implements ServiceTrackerCustomizer { private static Logger LOG = Log.getLogger(JettyServerServiceTracker.class.getName()); - - /** + /** * @see org.osgi.util.tracker.ServiceTrackerCustomizer#addingService(org.osgi.framework.ServiceReference) */ @Override public Object addingService(ServiceReference sr) { Bundle contributor = sr.getBundle(); - Server server = (Server) contributor.getBundleContext().getService(sr); - String name = (String) sr.getProperty(OSGiServerConstants.MANAGED_JETTY_SERVER_NAME); - if (name == null) { throw new IllegalArgumentException("The property " + OSGiServerConstants.MANAGED_JETTY_SERVER_NAME + " is mandatory"); } - if (LOG.isDebugEnabled()) LOG.debug("Adding Server {}", name); + Server server = (Server)contributor.getBundleContext().getService(sr); + String name = (String)sr.getProperty(OSGiServerConstants.MANAGED_JETTY_SERVER_NAME); + if (name == null) + { + throw new IllegalArgumentException("The property " + OSGiServerConstants.MANAGED_JETTY_SERVER_NAME + " is mandatory"); + } + if (LOG.isDebugEnabled()) + LOG.debug("Adding Server {}", name); ServerInstanceWrapper wrapper = new ServerInstanceWrapper(name); - Dictionary props = new Hashtable<>(); + Dictionary props = new Hashtable<>(); for (String key : sr.getPropertyKeys()) { props.put(key, sr.getProperty(key)); @@ -72,7 +73,7 @@ public class JettyServerServiceTracker implements ServiceTrackerCustomizer } } - /** + /** * @see org.osgi.util.tracker.ServiceTrackerCustomizer#modifiedService(org.osgi.framework.ServiceReference, java.lang.Object) */ @Override @@ -82,7 +83,7 @@ public class JettyServerServiceTracker implements ServiceTrackerCustomizer addingService(reference); } - /** + /** * @see org.osgi.util.tracker.ServiceTrackerCustomizer#removedService(org.osgi.framework.ServiceReference, java.lang.Object) */ @Override @@ -94,13 +95,12 @@ public class JettyServerServiceTracker implements ServiceTrackerCustomizer { ServerInstanceWrapper wrapper = (ServerInstanceWrapper)service; wrapper.stop(); - LOG.info("Stopped Server {}",wrapper.getManagedServerName()); + LOG.info("Stopped Server {}", wrapper.getManagedServerName()); } catch (Exception e) { LOG.warn(e); } } - } } diff --git a/jetty-osgi/jetty-osgi-boot/src/main/java/org/eclipse/jetty/osgi/boot/internal/serverfactory/ServerInstanceWrapper.java b/jetty-osgi/jetty-osgi-boot/src/main/java/org/eclipse/jetty/osgi/boot/internal/serverfactory/ServerInstanceWrapper.java index 1862a8f51a4..bd20b079fba 100644 --- a/jetty-osgi/jetty-osgi-boot/src/main/java/org/eclipse/jetty/osgi/boot/internal/serverfactory/ServerInstanceWrapper.java +++ b/jetty-osgi/jetty-osgi-boot/src/main/java/org/eclipse/jetty/osgi/boot/internal/serverfactory/ServerInstanceWrapper.java @@ -58,8 +58,8 @@ import org.eclipse.jetty.xml.XmlConfiguration; /** * ServerInstanceWrapper - * - * Configures and starts a jetty Server instance. + * + * Configures and starts a jetty Server instance. */ public class ServerInstanceWrapper { @@ -70,13 +70,10 @@ public class ServerInstanceWrapper * support the case where the bundle is zipped. */ public static final String PROPERTY_THIS_JETTY_XML_FOLDER_URL = "this.jetty.xml.parent.folder.url"; - - + private static Collection __containerTldBundleDiscoverers = new ArrayList<>(); private static Logger LOG = Log.getLogger(ServerInstanceWrapper.class.getName()); - - private final String _managedServerName; @@ -95,36 +92,31 @@ public class ServerInstanceWrapper private ClassLoader _commonParentClassLoaderForWebapps; private DeploymentManager _deploymentManager; - - - - /* ------------------------------------------------------------ */ - public static void addContainerTldBundleDiscoverer (TldBundleDiscoverer tldBundleDiscoverer) + + public static void addContainerTldBundleDiscoverer(TldBundleDiscoverer tldBundleDiscoverer) { __containerTldBundleDiscoverers.add(tldBundleDiscoverer); } - - /* ------------------------------------------------------------ */ + public static Collection getContainerTldBundleDiscoverers() { return __containerTldBundleDiscoverers; } - - - - /* ------------------------------------------------------------ */ public static Server configure(Server server, List jettyConfigurations, Dictionary props) throws Exception { - - if (jettyConfigurations == null || jettyConfigurations.isEmpty()) { return server; } - - Map id_map = new HashMap<>(); + + if (jettyConfigurations == null || jettyConfigurations.isEmpty()) + { + return server; + } + + Map idMap = new HashMap<>(); if (server != null) { //Put in a mapping for the id "Server" and the name of the server as the instance being configured - id_map.put("Server", server); - id_map.put((String)props.get(OSGiServerConstants.MANAGED_JETTY_SERVER_NAME), server); + idMap.put("Server", server); + idMap.put((String)props.get(OSGiServerConstants.MANAGED_JETTY_SERVER_NAME), server); } Map properties = new HashMap<>(); @@ -136,7 +128,8 @@ public class ServerInstanceWrapper String key = en.nextElement(); Object value = props.get(key); properties.put(key, value.toString()); - if (server != null) server.setAttribute(key, value); + if (server != null) + server.setAttribute(key, value); } } @@ -147,7 +140,7 @@ public class ServerInstanceWrapper // Execute a Jetty configuration file XmlConfiguration config = new XmlConfiguration(Resource.newResource(jettyConfiguration)); - config.getIdMap().putAll(id_map); + config.getIdMap().putAll(idMap); config.getProperties().putAll(properties); // #334062 compute the URL of the folder that contains the @@ -165,7 +158,7 @@ public class ServerInstanceWrapper if (server == null) server = (Server)o; - id_map = config.getIdMap(); + idMap = config.getIdMap(); } catch (Exception e) { @@ -176,37 +169,28 @@ public class ServerInstanceWrapper return server; } - - - - - /* ------------------------------------------------------------ */ + public ServerInstanceWrapper(String managedServerName) { _managedServerName = managedServerName; } - /* ------------------------------------------------------------ */ public String getManagedServerName() { return _managedServerName; } - - - /* ------------------------------------------------------------ */ + /** * The classloader that should be the parent classloader for each webapp * deployed on this server. - * + * * @return the classloader */ public ClassLoader getParentClassLoaderForWebapps() { return _commonParentClassLoaderForWebapps; } - - - /* ------------------------------------------------------------ */ + /** * @return The deployment manager registered on this server. */ @@ -214,9 +198,7 @@ public class ServerInstanceWrapper { return _deploymentManager; } - - - /* ------------------------------------------------------------ */ + /** * @return The app provider registered on this server. */ @@ -225,7 +207,6 @@ public class ServerInstanceWrapper return _server; } - /* ------------------------------------------------------------ */ /** * @return The collection of context handlers */ @@ -233,9 +214,8 @@ public class ServerInstanceWrapper { return _ctxtCollection; } - - /* ------------------------------------------------------------ */ - public void start(Server server, Dictionary props) throws Exception + + public void start(Server server, Dictionary props) throws Exception { _server = server; ClassLoader contextCl = Thread.currentThread().getContextClassLoader(); @@ -247,17 +227,18 @@ public class ServerInstanceWrapper // makes sure there is access to all the jetty's bundles ClassLoader libExtClassLoader = LibExtClassLoaderHelper.createLibExtClassLoader(null, sharedURLs, JettyBootstrapActivator.class.getClassLoader()); - if (LOG.isDebugEnabled()) LOG.debug("LibExtClassLoader = "+libExtClassLoader); - + if (LOG.isDebugEnabled()) + LOG.debug("LibExtClassLoader = " + libExtClassLoader); + Thread.currentThread().setContextClassLoader(libExtClassLoader); - String jettyConfigurationUrls = (String) props.get(OSGiServerConstants.MANAGED_JETTY_XML_CONFIG_URLS); + String jettyConfigurationUrls = (String)props.get(OSGiServerConstants.MANAGED_JETTY_XML_CONFIG_URLS); List jettyConfigurations = jettyConfigurationUrls != null ? Util.fileNamesAsURLs(jettyConfigurationUrls, Util.DEFAULT_DELIMS) : null; - + _server = configure(server, jettyConfigurations, props); init(); - + //if support for jsp is enabled, we need to convert locations of bundles that contain tlds into urls. //these are tlds that we want jasper to treat as if they are on the container's classpath. Web bundles //can use the Require-TldBundle MANIFEST header to name other tld-containing bundles that should be regarded @@ -266,22 +247,24 @@ public class ServerInstanceWrapper { Set urls = new HashSet<>(); //discover bundles with tlds that need to be on the container's classpath as URLs - for (TldBundleDiscoverer d:__containerTldBundleDiscoverers) + for (TldBundleDiscoverer d : __containerTldBundleDiscoverers) { URL[] list = d.getUrlsForBundlesWithTlds(_deploymentManager, BundleFileLocatorHelperFactory.getFactory().getHelper()); if (list != null) { - for (URL u:list) + for (URL u : list) + { urls.add(u); + } } } - _commonParentClassLoaderForWebapps = new FakeURLClassLoader(libExtClassLoader, urls.toArray(new URL[urls.size()])); + _commonParentClassLoaderForWebapps = new FakeURLClassLoader(libExtClassLoader, urls.toArray(new URL[urls.size()])); } else _commonParentClassLoaderForWebapps = libExtClassLoader; - - if (LOG.isDebugEnabled()) LOG.debug("common classloader = "+_commonParentClassLoaderForWebapps); + if (LOG.isDebugEnabled()) + LOG.debug("common classloader = " + _commonParentClassLoaderForWebapps); server.start(); } @@ -306,7 +289,6 @@ public class ServerInstanceWrapper } } - /* ------------------------------------------------------------ */ public void stop() { try @@ -321,36 +303,31 @@ public class ServerInstanceWrapper LOG.warn(e); } } - - - - - /* ------------------------------------------------------------ */ + /** - * Must be called after the server is configured. - * + * Must be called after the server is configured. + * * It is assumed the server has already been configured with the ContextHandlerCollection structure. - * */ private void init() { // Get the context handler - _ctxtCollection = (ContextHandlerCollection) _server.getChildHandlerByClass(ContextHandlerCollection.class); + _ctxtCollection = (ContextHandlerCollection)_server.getChildHandlerByClass(ContextHandlerCollection.class); - if (_ctxtCollection == null) + if (_ctxtCollection == null) throw new IllegalStateException("ERROR: No ContextHandlerCollection configured in Server"); - + List providerClassNames = new ArrayList<>(); - + // get a deployerManager and some providers Collection deployers = _server.getBeans(DeploymentManager.class); if (deployers != null && !deployers.isEmpty()) { _deploymentManager = deployers.iterator().next(); - + for (AppProvider provider : _deploymentManager.getAppProviders()) { - providerClassNames.add(provider.getClass().getName()); + providerClassNames.add(provider.getClass().getName()); } } else @@ -368,7 +345,7 @@ public class ServerInstanceWrapper deploymentLifeCycleBindings.add(new StandardStopper()); deploymentLifeCycleBindings.add(new OSGiUndeployer(this)); _deploymentManager.setLifeCycleBindings(deploymentLifeCycleBindings); - + if (!providerClassNames.contains(BundleWebAppProvider.class.getName())) { // create it on the fly with reasonable default values. @@ -424,7 +401,6 @@ public class ServerInstanceWrapper } } - /** * Get the Jetty Shared Lib Folder URLs in a form that is suitable for * {@link LibExtClassLoaderHelper} to use. @@ -432,9 +408,9 @@ public class ServerInstanceWrapper * @param props the properties to look for the configuration in * @return the list of URLs found, or null if none found */ - private List getManagedJettySharedLibFolderUrls(Dictionary props) + private List getManagedJettySharedLibFolderUrls(Dictionary props) { - String sharedURLs = (String) props.get(OSGiServerConstants.MANAGED_JETTY_SHARED_LIB_FOLDER_URLS); + String sharedURLs = (String)props.get(OSGiServerConstants.MANAGED_JETTY_SHARED_LIB_FOLDER_URLS); if (StringUtil.isBlank(sharedURLs)) { return null; diff --git a/jetty-osgi/jetty-osgi-boot/src/main/java/org/eclipse/jetty/osgi/boot/internal/webapp/LibExtClassLoaderHelper.java b/jetty-osgi/jetty-osgi-boot/src/main/java/org/eclipse/jetty/osgi/boot/internal/webapp/LibExtClassLoaderHelper.java index 15db1c464c0..46c026ff5f1 100644 --- a/jetty-osgi/jetty-osgi-boot/src/main/java/org/eclipse/jetty/osgi/boot/internal/webapp/LibExtClassLoaderHelper.java +++ b/jetty-osgi/jetty-osgi-boot/src/main/java/org/eclipse/jetty/osgi/boot/internal/webapp/LibExtClassLoaderHelper.java @@ -55,10 +55,10 @@ import java.util.Set; */ public class LibExtClassLoaderHelper { - /* ------------------------------------------------------------ */ + /** * IFilesInJettyHomeResourcesProcessor - * + * * Interface for callback impls */ public interface IFilesInJettyHomeResourcesProcessor @@ -66,23 +66,22 @@ public class LibExtClassLoaderHelper void processFilesInResourcesFolder(File jettyHome, Map filesInResourcesFolder); } - - public static final Set registeredFilesInJettyHomeResourcesProcessors = new HashSet<>(); - - /* ------------------------------------------------------------ */ /** - * @param jettyHome the jetty home + * @param jettyHome the jetty home * @param parentClassLoader the parent classloader * @return a url classloader with the jars of resources, lib/ext and the - * jars passed in the other argument. The parent classloader usually - * is the JettyBootStrapper (an osgi classloader. + * jars passed in the other argument. The parent classloader usually + * is the JettyBootStrapper (an osgi classloader. * @throws MalformedURLException if the jetty home reference is invalid */ public static ClassLoader createLibEtcClassLoader(File jettyHome, ClassLoader parentClassLoader) throws MalformedURLException { - if (jettyHome == null) { return parentClassLoader; } + if (jettyHome == null) + { + return parentClassLoader; + } ArrayList urls = new ArrayList<>(); File jettyResources = new File(jettyHome, "resources"); if (jettyResources.exists()) @@ -116,7 +115,8 @@ public class LibExtClassLoaderHelper // cheap to tolerate folders so let's do it. URL url = f.toURI().toURL(); if (f.isFile()) - {// is this necessary anyways? + { + // is this necessary anyways? url = new URL("jar:" + url.toString() + "!/"); } urls.add(url); @@ -127,22 +127,23 @@ public class LibExtClassLoaderHelper return new URLClassLoader(urls.toArray(new URL[urls.size()]), parentClassLoader); } - - /* ------------------------------------------------------------ */ /** * @param jarsContainerOrJars the jars via file references * @param otherJarsOrFolder more jars via url references * @param parentClassLoader the parent classloader * @return a url classloader with the jars of resources, lib/ext and the - * jars passed in the other argument. The parent classloader usually - * is the JettyBootStrapper (an osgi classloader). If there was no - * extra jars to insert, then just return the parentClassLoader. + * jars passed in the other argument. The parent classloader usually + * is the JettyBootStrapper (an osgi classloader). If there was no + * extra jars to insert, then just return the parentClassLoader. * @throws MalformedURLException if there is a bad jar file reference */ - public static ClassLoader createLibExtClassLoader(List jarsContainerOrJars, List otherJarsOrFolder, ClassLoader parentClassLoader) - throws MalformedURLException + public static ClassLoader createLibExtClassLoader(List jarsContainerOrJars, List otherJarsOrFolder, ClassLoader parentClassLoader) + throws MalformedURLException { - if (jarsContainerOrJars == null && otherJarsOrFolder == null) { return parentClassLoader; } + if (jarsContainerOrJars == null && otherJarsOrFolder == null) + { + return parentClassLoader; + } List urls = new ArrayList<>(); if (otherJarsOrFolder != null) { @@ -174,7 +175,6 @@ public class LibExtClassLoaderHelper return new URLClassLoader(urls.toArray(new URL[urls.size()]), parentClassLoader); } - /* ------------------------------------------------------------ */ /** * When we find files typically used for central logging configuration we do * what it takes in this method to do what the user expects. Without @@ -187,6 +187,7 @@ public class LibExtClassLoaderHelper *

    * We recommend that slf4j jars are all placed in the osgi framework. And a * single implementation if possible packaged as an osgi bundle is there. + * * @param jettyHome the jetty home reference * @param childrenFiles the map of child files */ @@ -197,5 +198,4 @@ public class LibExtClassLoaderHelper processor.processFilesInResourcesFolder(jettyHome, childrenFiles); } } - } diff --git a/jetty-osgi/jetty-osgi-boot/src/main/java/org/eclipse/jetty/osgi/boot/internal/webapp/OSGiWebappClassLoader.java b/jetty-osgi/jetty-osgi-boot/src/main/java/org/eclipse/jetty/osgi/boot/internal/webapp/OSGiWebappClassLoader.java index 9afb705ad34..9cfdc747513 100644 --- a/jetty-osgi/jetty-osgi-boot/src/main/java/org/eclipse/jetty/osgi/boot/internal/webapp/OSGiWebappClassLoader.java +++ b/jetty-osgi/jetty-osgi-boot/src/main/java/org/eclipse/jetty/osgi/boot/internal/webapp/OSGiWebappClassLoader.java @@ -44,8 +44,8 @@ import org.osgi.framework.BundleReference; /** * OSGiWebappClassLoader - * - * + * + * * Extends the webapp classloader to also use the classloader of the Bundle defining the webapp. */ public class OSGiWebappClassLoader extends WebAppClassLoader implements BundleReference @@ -78,7 +78,6 @@ public class OSGiWebappClassLoader extends WebAppClassLoader implements BundleRe private Bundle _contributor; - /* ------------------------------------------------------------ */ /** * @param parent The parent classloader. * @param context The WebAppContext @@ -86,14 +85,12 @@ public class OSGiWebappClassLoader extends WebAppClassLoader implements BundleRe * @throws IOException if unable to cerate the OSGiWebappClassLoader */ public OSGiWebappClassLoader(ClassLoader parent, WebAppContext context, Bundle contributor) - throws IOException + throws IOException { super(parent, context); _contributor = contributor; _osgiBundleClassLoader = BundleClassLoaderHelperFactory.getFactory().getHelper().getBundleClassLoader(contributor); } - - @Override protected Class findClass(String name) throws ClassNotFoundException @@ -116,12 +113,11 @@ public class OSGiWebappClassLoader extends WebAppClassLoader implements BundleRe } } - /* ------------------------------------------------------------ */ /** * Returns the Bundle that defined this web-application. - * + * * @return The Bundle object associated with this - * BundleReference. + * BundleReference. */ @Override public Bundle getBundle() @@ -129,7 +125,6 @@ public class OSGiWebappClassLoader extends WebAppClassLoader implements BundleRe return _contributor; } - /* ------------------------------------------------------------ */ @Override public Enumeration getResources(String name) throws IOException { @@ -138,35 +133,29 @@ public class OSGiWebappClassLoader extends WebAppClassLoader implements BundleRe List resources = toList(osgiUrls, urls); return Collections.enumeration(resources); } - - /* ------------------------------------------------------------ */ + @Override public URL getResource(String name) { URL url = _osgiBundleClassLoader.getResource(name); return url != null ? url : super.getResource(name); } - - - - + @Override public URL findResource(String name) { URL url = _osgiBundleClassLoader.getResource(name); return url != null ? url : super.findResource(name); } - - - /** + /** * Try to load the class from the bundle classloader. * We do NOT load it as a resource as the WebAppClassLoader does because the * url that is returned is an osgi-special url that does not play * properly with WebAppClassLoader's method of extracting the class * from the resource. This implementation directly asks the osgi * bundle classloader to load the given class name. - * + * * @see org.eclipse.jetty.webapp.WebAppClassLoader#loadAsResource(java.lang.String, boolean) */ @Override @@ -189,18 +178,20 @@ public class OSGiWebappClassLoader extends WebAppClassLoader implements BundleRe } } - /* ------------------------------------------------------------ */ private List toList(Enumeration e, Enumeration e2) { List list = new ArrayList<>(); while (e != null && e.hasMoreElements()) + { list.add(e.nextElement()); + } while (e2 != null && e2.hasMoreElements()) + { list.add(e2.nextElement()); + } return list; - } - - /* ------------------------------------------------------------ */ + } + /** * Parse the classpath ourselves to be able to filter things. This is a * derivative work of the super class @@ -226,13 +217,9 @@ public class OSGiWebappClassLoader extends WebAppClassLoader implements BundleRe __logger.info("Did not add " + path + " to the classloader of the webapp " + getContext()); } } - } - - /* ------------------------------------------------------------ */ /** - * @param lib * @return true if the lib should be included in the webapp classloader. */ private boolean isAcceptableLibrary(File file, Set pathToClassFiles) @@ -243,7 +230,10 @@ public class OSGiWebappClassLoader extends WebAppClassLoader implements BundleRe { for (String criteria : pathToClassFiles) { - if (new File(file, criteria).exists()) { return false; } + if (new File(file, criteria).exists()) + { + return false; + } } } else @@ -254,18 +244,22 @@ public class OSGiWebappClassLoader extends WebAppClassLoader implements BundleRe jar = new JarFile(file); for (String criteria : pathToClassFiles) { - if (jar.getEntry(criteria) != null) { return false; } + if (jar.getEntry(criteria) != null) + { + return false; + } } } finally { - if (jar != null) try - { - jar.close(); - } - catch (IOException ioe) - { - } + if (jar != null) + try + { + jar.close(); + } + catch (IOException ignored) + { + } } } } @@ -279,14 +273,13 @@ public class OSGiWebappClassLoader extends WebAppClassLoader implements BundleRe private static Field _contextField; - - /* ------------------------------------------------------------ */ /** * In the case of the generation of a webapp via a jetty context file we * need a proper classloader to setup the app before we have the * WebappContext So we place a fake one there to start with. We replace it * with the actual webapp context with this method. We also apply the * extraclasspath there at the same time. + * * @param webappContext the web app context */ public void setWebappContext(WebAppContext webappContext) diff --git a/jetty-osgi/jetty-osgi-boot/src/main/java/org/eclipse/jetty/osgi/boot/utils/BundleClassLoaderHelper.java b/jetty-osgi/jetty-osgi-boot/src/main/java/org/eclipse/jetty/osgi/boot/utils/BundleClassLoaderHelper.java index 3cbc3264697..d69fca5c306 100644 --- a/jetty-osgi/jetty-osgi-boot/src/main/java/org/eclipse/jetty/osgi/boot/utils/BundleClassLoaderHelper.java +++ b/jetty-osgi/jetty-osgi-boot/src/main/java/org/eclipse/jetty/osgi/boot/utils/BundleClassLoaderHelper.java @@ -23,7 +23,7 @@ import org.osgi.framework.Bundle; /** * BundleClassLoaderHelper - *

    + *

    * Is there a clean OSGi way to go from the Bundle object to the classloader of * the Bundle ? You can certainly take a class inside the bundle and get the * bundle's classloader that way. Getting the classloader directly from the @@ -39,17 +39,20 @@ import org.osgi.framework.Bundle; public interface BundleClassLoaderHelper { - /** The name of the custom implementation for this interface in a fragment. */ + /** + * The name of the custom implementation for this interface in a fragment. + */ public static final String CLASS_NAME = "org.eclipse.jetty.osgi.boot.utils.BundleClassLoaderHelperImpl"; - /** The default instance supports felix and equinox */ + /** + * The default instance supports felix and equinox + */ public static BundleClassLoaderHelper DEFAULT = new DefaultBundleClassLoaderHelper(); /** * @param bundle the bundle * @return The classloader of a given bundle. Assuming the bundle is - * started. + * started. */ public ClassLoader getBundleClassLoader(Bundle bundle); - } diff --git a/jetty-osgi/jetty-osgi-boot/src/main/java/org/eclipse/jetty/osgi/boot/utils/BundleClassLoaderHelperFactory.java b/jetty-osgi/jetty-osgi-boot/src/main/java/org/eclipse/jetty/osgi/boot/utils/BundleClassLoaderHelperFactory.java index 20c473f95e6..d52375109e1 100644 --- a/jetty-osgi/jetty-osgi-boot/src/main/java/org/eclipse/jetty/osgi/boot/utils/BundleClassLoaderHelperFactory.java +++ b/jetty-osgi/jetty-osgi-boot/src/main/java/org/eclipse/jetty/osgi/boot/utils/BundleClassLoaderHelperFactory.java @@ -29,22 +29,18 @@ import org.eclipse.jetty.util.log.Logger; public class BundleClassLoaderHelperFactory { private static final Logger LOG = Log.getLogger(BundleClassLoaderHelperFactory.class); - + private static BundleClassLoaderHelperFactory _instance = new BundleClassLoaderHelperFactory(); - - - /* ------------------------------------------------------------ */ + public static BundleClassLoaderHelperFactory getFactory() { return _instance; } - - /* ------------------------------------------------------------ */ + private BundleClassLoaderHelperFactory() { } - - /* ------------------------------------------------------------ */ + public BundleClassLoaderHelper getHelper() { //use the default @@ -52,15 +48,14 @@ public class BundleClassLoaderHelperFactory try { //if a fragment has not provided their own impl - helper = (BundleClassLoaderHelper) Class.forName(BundleClassLoaderHelper.CLASS_NAME) + helper = (BundleClassLoaderHelper)Class.forName(BundleClassLoaderHelper.CLASS_NAME) .getDeclaredConstructor().newInstance(); } catch (Throwable t) { LOG.ignore(t); } - + return helper; } - } diff --git a/jetty-osgi/jetty-osgi-boot/src/main/java/org/eclipse/jetty/osgi/boot/utils/BundleFileLocatorHelper.java b/jetty-osgi/jetty-osgi-boot/src/main/java/org/eclipse/jetty/osgi/boot/utils/BundleFileLocatorHelper.java index c808a2fafb2..81ea9475503 100644 --- a/jetty-osgi/jetty-osgi-boot/src/main/java/org/eclipse/jetty/osgi/boot/utils/BundleFileLocatorHelper.java +++ b/jetty-osgi/jetty-osgi-boot/src/main/java/org/eclipse/jetty/osgi/boot/utils/BundleFileLocatorHelper.java @@ -27,17 +27,21 @@ import org.osgi.framework.Bundle; /** * BundleFileLocatorHelper - *

    + *

    * From a bundle to its location on the filesystem. Assumes the bundle is not a * jar. */ public interface BundleFileLocatorHelper { - /** The name of the custom implementation for this interface in a fragment. */ + /** + * The name of the custom implementation for this interface in a fragment. + */ public static final String CLASS_NAME = "org.eclipse.jetty.osgi.boot.utils.FileLocatorHelperImpl"; - /** The default instance supports felix and equinox */ + /** + * The default instance supports felix and equinox + */ public static BundleFileLocatorHelper DEFAULT = new DefaultFileLocatorHelper(); /** @@ -46,7 +50,7 @@ public interface BundleFileLocatorHelper * other situations. *

    * Currently only works with bundles that are not jar. - * + * * @param bundle The bundle * @return Its installation location as a file. * @throws Exception if unable to get the install location @@ -55,7 +59,7 @@ public interface BundleFileLocatorHelper /** * Locate a file inside a bundle. - * + * * @param bundle the bundle * @param path the path * @return file the file object @@ -71,10 +75,10 @@ public interface BundleFileLocatorHelper * files inside jars alone. In fact we only support the second situation for * development purpose where the bundle was imported in pde and the classes * kept in a jar. - * + * * @param bundle the bundle * @return The jar(s) file that is either the bundle itself, either the jars - * embedded inside it. + * embedded inside it. * @throws Exception if unable to locate the jars */ public File[] locateJarsInsideBundle(Bundle bundle) throws Exception; @@ -82,26 +86,26 @@ public interface BundleFileLocatorHelper /** * Helper method equivalent to Bundle#getEntry(String entryPath) except that * it searches for entries in the fragments by using the findEntries method. - * + * * @param bundle the bundle * @param entryPath the entry path * @return null or all the entries found for that path. */ public Enumeration findEntries(Bundle bundle, String entryPath); - + /** * Only useful for equinox: on felix we get the file:// or jar:// url * already. Other OSGi implementations have not been tested *

    * Get a URL to the bundle entry that uses a common protocol (i.e. file: * jar: or http: etc.). - * - * @param url the url + * + * @param url the url * @return a URL to the bundle entry that uses a common protocol * @throws Exception if unable to get the local url */ public URL getLocalURL(URL url) throws Exception; - + /** * Only useful for equinox: on felix we get the file:// url already. Other * OSGi implementations have not been tested @@ -109,12 +113,11 @@ public interface BundleFileLocatorHelper * Get a URL to the content of the bundle entry that uses the file: * protocol. The content of the bundle entry may be downloaded or extracted * to the local file system in order to create a file: URL. - * - * @param url the url + * + * @param url the url * @return a URL to the content of the bundle entry that uses the file: - * protocol + * protocol * @throws Exception if unable to get the file url */ public URL getFileURL(URL url) throws Exception; - } diff --git a/jetty-osgi/jetty-osgi-boot/src/main/java/org/eclipse/jetty/osgi/boot/utils/BundleFileLocatorHelperFactory.java b/jetty-osgi/jetty-osgi-boot/src/main/java/org/eclipse/jetty/osgi/boot/utils/BundleFileLocatorHelperFactory.java index 0a1c091e1de..a9335f1eebc 100644 --- a/jetty-osgi/jetty-osgi-boot/src/main/java/org/eclipse/jetty/osgi/boot/utils/BundleFileLocatorHelperFactory.java +++ b/jetty-osgi/jetty-osgi-boot/src/main/java/org/eclipse/jetty/osgi/boot/utils/BundleFileLocatorHelperFactory.java @@ -27,25 +27,27 @@ import org.eclipse.jetty.util.log.Logger; * Obtain a helper for locating files based on the bundle. */ public class BundleFileLocatorHelperFactory -{ +{ private static final Logger LOG = Log.getLogger(BundleFileLocatorHelperFactory.class); - + private static BundleFileLocatorHelperFactory _instance = new BundleFileLocatorHelperFactory(); - - private BundleFileLocatorHelperFactory() {} - + + private BundleFileLocatorHelperFactory() + { + } + public static BundleFileLocatorHelperFactory getFactory() { return _instance; } - + public BundleFileLocatorHelper getHelper() { BundleFileLocatorHelper helper = BundleFileLocatorHelper.DEFAULT; try { //see if a fragment has supplied an alternative - helper = (BundleFileLocatorHelper) Class.forName(BundleFileLocatorHelper.CLASS_NAME) + helper = (BundleFileLocatorHelper)Class.forName(BundleFileLocatorHelper.CLASS_NAME) .getDeclaredConstructor().newInstance(); } catch (Throwable t) @@ -54,5 +56,4 @@ public class BundleFileLocatorHelperFactory } return helper; } - } diff --git a/jetty-osgi/jetty-osgi-boot/src/main/java/org/eclipse/jetty/osgi/boot/utils/EventSender.java b/jetty-osgi/jetty-osgi-boot/src/main/java/org/eclipse/jetty/osgi/boot/utils/EventSender.java index 27b19cda888..ed6798e3a94 100644 --- a/jetty-osgi/jetty-osgi-boot/src/main/java/org/eclipse/jetty/osgi/boot/utils/EventSender.java +++ b/jetty-osgi/jetty-osgi-boot/src/main/java/org/eclipse/jetty/osgi/boot/utils/EventSender.java @@ -31,43 +31,44 @@ import org.osgi.util.tracker.ServiceTracker; * Utility class for emitting OSGi EventAdmin events */ public class EventSender -{ +{ //OSGi Event Admin events for webapps public static final String DEPLOYING_EVENT = "org/osgi/service/web/DEPLOYING"; public static final String DEPLOYED_EVENT = "org/osgi/service/web/DEPLOYED"; public static final String UNDEPLOYING_EVENT = "org/osgi/service/web/UNDEPLOYING"; - public static final String UNDEPLOYED_EVENT = "org/osgi/service/web/UNDEPLOYED"; - public static final String FAILED_EVENT = "org/osgi/service/web/FAILED"; - + public static final String UNDEPLOYED_EVENT = "org/osgi/service/web/UNDEPLOYED"; + public static final String FAILED_EVENT = "org/osgi/service/web/FAILED"; + private static final EventSender __instance = new EventSender(); private Bundle _myBundle; private ServiceTracker _serviceTracker; - - private EventSender () + + private EventSender() { _myBundle = FrameworkUtil.getBundle(EventSender.class); - _serviceTracker = new ServiceTracker(_myBundle.getBundleContext(),EventAdmin.class.getName(),null); + _serviceTracker = new ServiceTracker(_myBundle.getBundleContext(), EventAdmin.class.getName(), null); _serviceTracker.open(); } - + public static EventSender getInstance() { return __instance; } - public void send (String topic, Bundle wab, String contextPath) + public void send(String topic, Bundle wab, String contextPath) { - if (topic==null || wab==null || contextPath==null) + if (topic == null || wab == null || contextPath == null) return; - + send(topic, wab, contextPath, null); } - - public void send (String topic, Bundle wab, String contextPath, Exception ex) - { + + public void send(String topic, Bundle wab, String contextPath, Exception ex) + { EventAdmin service = (EventAdmin)_serviceTracker.getService(); - if (service != null) { - Dictionary props = new Hashtable<>(); + if (service != null) + { + Dictionary props = new Hashtable<>(); props.put("bundle.symbolicName", wab.getSymbolicName()); props.put("bundle.id", wab.getBundleId()); props.put("bundle", wab); @@ -78,10 +79,10 @@ public class EventSender props.put("extender.bundle.symbolicName", _myBundle.getSymbolicName()); props.put("extender.bundle.id", _myBundle.getBundleId()); props.put("extender.bundle.version", _myBundle.getVersion()); - - if (FAILED_EVENT.equalsIgnoreCase(topic) && ex != null) + + if (FAILED_EVENT.equalsIgnoreCase(topic) && ex != null) props.put("exception", ex); - + service.sendEvent(new Event(topic, props)); } } diff --git a/jetty-osgi/jetty-osgi-boot/src/main/java/org/eclipse/jetty/osgi/boot/utils/FakeURLClassLoader.java b/jetty-osgi/jetty-osgi-boot/src/main/java/org/eclipse/jetty/osgi/boot/utils/FakeURLClassLoader.java index ccc3e6a4b7f..f755f85bbbb 100644 --- a/jetty-osgi/jetty-osgi-boot/src/main/java/org/eclipse/jetty/osgi/boot/utils/FakeURLClassLoader.java +++ b/jetty-osgi/jetty-osgi-boot/src/main/java/org/eclipse/jetty/osgi/boot/utils/FakeURLClassLoader.java @@ -35,18 +35,16 @@ import java.net.URLClassLoader; public class FakeURLClassLoader extends URLClassLoader { private URL[] _jars; - - /* ------------------------------------------------------------ */ + public FakeURLClassLoader(ClassLoader osgiClassLoader, URL[] jars) { - super(new URL[] {},osgiClassLoader); + super(new URL[]{}, osgiClassLoader); _jars = jars; } - /* ------------------------------------------------------------ */ /** * @return the jars that contains tlds so that TldLocationsCache or - * TldScanner can find them. + * TldScanner can find them. */ @Override public URL[] getURLs() @@ -54,9 +52,7 @@ public class FakeURLClassLoader extends URLClassLoader return _jars; } - - /* ------------------------------------------------------------ */ - /** + /** * @see java.lang.Object#toString() */ @Override @@ -66,8 +62,10 @@ public class FakeURLClassLoader extends URLClassLoader if (_jars != null) { - for (URL u:_jars) - builder.append(" "+u.toString()); + for (URL u : _jars) + { + builder.append(" " + u.toString()); + } return builder.toString(); } else diff --git a/jetty-osgi/jetty-osgi-boot/src/main/java/org/eclipse/jetty/osgi/boot/utils/OSGiClassLoader.java b/jetty-osgi/jetty-osgi-boot/src/main/java/org/eclipse/jetty/osgi/boot/utils/OSGiClassLoader.java index 51ce968a220..6c7a44d804f 100644 --- a/jetty-osgi/jetty-osgi-boot/src/main/java/org/eclipse/jetty/osgi/boot/utils/OSGiClassLoader.java +++ b/jetty-osgi/jetty-osgi-boot/src/main/java/org/eclipse/jetty/osgi/boot/utils/OSGiClassLoader.java @@ -39,13 +39,11 @@ import org.osgi.framework.Bundle; public class OSGiClassLoader extends URLClassLoader { private static final Logger LOG = Log.getLogger(OSGiClassLoader.class); - - + private Bundle _bundle; private ClassLoader _osgiBundleClassLoader; private ClassLoader _parent; - - /* ------------------------------------------------------------ */ + public OSGiClassLoader(ClassLoader parent, Bundle bundle) { super(new URL[]{}, parent); @@ -53,24 +51,20 @@ public class OSGiClassLoader extends URLClassLoader _bundle = bundle; _osgiBundleClassLoader = BundleClassLoaderHelperFactory.getFactory().getHelper().getBundleClassLoader(_bundle); } - - - - /* ------------------------------------------------------------ */ + /** * Get a resource from the classloader - * + * * Copied from WebAppClassLoader */ @Override public URL getResource(String name) { - URL url= null; - boolean tried_parent= false; + URL url = null; + boolean triedParent = false; - if (url == null) - { + { url = _osgiBundleClassLoader.getResource(name); if (url == null && name.startsWith("/")) @@ -82,47 +76,45 @@ public class OSGiClassLoader extends URLClassLoader } } - if (url == null && !tried_parent) + if (url == null && !triedParent) { - if (_parent!=null) - url= _parent.getResource(name); + if (_parent != null) + url = _parent.getResource(name); } if (url != null) if (LOG.isDebugEnabled()) - LOG.debug("getResource("+name+")=" + url); + LOG.debug("getResource(" + name + ")=" + url); return url; } - - /* ------------------------------------------------------------ */ + @Override public Class loadClass(String name) throws ClassNotFoundException { return loadClass(name, false); } - /* ------------------------------------------------------------ */ @Override protected synchronized Class loadClass(String name, boolean resolve) throws ClassNotFoundException { Class c = findLoadedClass(name); - ClassNotFoundException ex= null; - boolean tried_parent= false; - + ClassNotFoundException ex = null; + boolean triedParent = false; + if (c == null) { try { - c= this.findClass(name); + c = this.findClass(name); } catch (ClassNotFoundException e) { - ex= e; + ex = e; } } - if (c == null && _parent!=null && !tried_parent) + if (c == null && _parent != null && !triedParent) c = _parent.loadClass(name); if (c == null) @@ -132,12 +124,11 @@ public class OSGiClassLoader extends URLClassLoader resolveClass(c); if (LOG.isDebugEnabled()) - LOG.debug("loaded " + c+ " from "+c.getClassLoader()); - + LOG.debug("loaded " + c + " from " + c.getClassLoader()); + return c; } - - /* ------------------------------------------------------------ */ + @Override public Enumeration getResources(String name) throws IOException { @@ -145,32 +136,27 @@ public class OSGiClassLoader extends URLClassLoader Enumeration urls = super.getResources(name); return Collections.enumeration(toList(osgiUrls, urls)); } - - - /* ------------------------------------------------------------ */ + @Override protected Class findClass(String name) throws ClassNotFoundException { - return _osgiBundleClassLoader.loadClass(name); + return _osgiBundleClassLoader.loadClass(name); } - - - - - /* ------------------------------------------------------------ */ /** - * @param e - * @param e2 - * @return + * */ private List toList(Enumeration e, Enumeration e2) { List list = new ArrayList<>(); while (e != null && e.hasMoreElements()) + { list.add(e.nextElement()); + } while (e2 != null && e2.hasMoreElements()) + { list.add(e2.nextElement()); + } return list; } } diff --git a/jetty-osgi/jetty-osgi-boot/src/main/java/org/eclipse/jetty/osgi/boot/utils/ServerConnectorListener.java b/jetty-osgi/jetty-osgi-boot/src/main/java/org/eclipse/jetty/osgi/boot/utils/ServerConnectorListener.java index 60ddccbc0c7..3e2a3538082 100644 --- a/jetty-osgi/jetty-osgi-boot/src/main/java/org/eclipse/jetty/osgi/boot/utils/ServerConnectorListener.java +++ b/jetty-osgi/jetty-osgi-boot/src/main/java/org/eclipse/jetty/osgi/boot/utils/ServerConnectorListener.java @@ -16,7 +16,6 @@ // ======================================================================== // - package org.eclipse.jetty.osgi.boot.utils; import java.io.FileWriter; @@ -30,7 +29,7 @@ import org.eclipse.jetty.util.component.LifeCycle; /** * ServerConnectorListener * - * This is for test support, where we need jetty to run on a random port, and we need + * This is for test support, where we need jetty to run on a random port, and we need * a client to be able to find out which port was picked. */ public class ServerConnectorListener extends AbstractLifeCycleListener @@ -39,9 +38,7 @@ public class ServerConnectorListener extends AbstractLifeCycleListener private Path _filePath; private String _sysPropertyName; - - - /** + /** * @see org.eclipse.jetty.util.component.AbstractLifeCycle.AbstractLifeCycleListener#lifeCycleStarted(org.eclipse.jetty.util.component.LifeCycle) */ @Override @@ -57,13 +54,13 @@ public class ServerConnectorListener extends AbstractLifeCycleListener } catch (Exception e) { - throw new RuntimeException (e); + throw new RuntimeException(e); } } - + if (getSysPropertyName() != null) { - System.setProperty(_sysPropertyName,String.valueOf(((ServerConnector)event).getLocalPort())); + System.setProperty(_sysPropertyName, String.valueOf(((ServerConnector)event).getLocalPort())); } super.lifeCycleStarted(event); } @@ -99,6 +96,4 @@ public class ServerConnectorListener extends AbstractLifeCycleListener { _sysPropertyName = sysPropertyName; } - - } diff --git a/jetty-osgi/jetty-osgi-boot/src/main/java/org/eclipse/jetty/osgi/boot/utils/TldBundleDiscoverer.java b/jetty-osgi/jetty-osgi-boot/src/main/java/org/eclipse/jetty/osgi/boot/utils/TldBundleDiscoverer.java index 700988354ce..efd3d6321a0 100644 --- a/jetty-osgi/jetty-osgi-boot/src/main/java/org/eclipse/jetty/osgi/boot/utils/TldBundleDiscoverer.java +++ b/jetty-osgi/jetty-osgi-boot/src/main/java/org/eclipse/jetty/osgi/boot/utils/TldBundleDiscoverer.java @@ -22,22 +22,20 @@ import java.net.URL; import org.eclipse.jetty.deploy.DeploymentManager; - /** * TldBundleDiscoverer - * + * * Convert bundles that contain tlds into URL locations for consumption by jasper. */ public interface TldBundleDiscoverer { /** * Find bundles that contain tlds and convert into URL references to their location. - * + * * @param manager The {@link DeploymentManager} instance to use * @param fileLocator the {@link BundleFileLocatorHelper} instance to use * @return array of URLs representing locations of tld containing bundles * @throws Exception In case of errors during resolving TLDs files */ URL[] getUrlsForBundlesWithTlds(DeploymentManager manager, BundleFileLocatorHelper fileLocator) throws Exception; - } diff --git a/jetty-osgi/jetty-osgi-boot/src/main/java/org/eclipse/jetty/osgi/boot/utils/Util.java b/jetty-osgi/jetty-osgi-boot/src/main/java/org/eclipse/jetty/osgi/boot/utils/Util.java index 20fa382a9c6..1938e439389 100644 --- a/jetty-osgi/jetty-osgi-boot/src/main/java/org/eclipse/jetty/osgi/boot/utils/Util.java +++ b/jetty-osgi/jetty-osgi-boot/src/main/java/org/eclipse/jetty/osgi/boot/utils/Util.java @@ -16,7 +16,6 @@ // ======================================================================== // - package org.eclipse.jetty.osgi.boot.utils; import java.net.URL; @@ -38,41 +37,36 @@ public class Util { public static final String DEFAULT_DELIMS = ",;"; - /** * Create an osgi filter for the given classname and server name. - * + * * @param bundleContext the {@link BundleContext} instance to use * @param classname the class to match on the filter * @param managedServerName the name of the jetty server instance * @return a new filter - * * @throws InvalidSyntaxException If the filter contains an invalid string that cannot be parsed. */ - public static Filter createFilter (BundleContext bundleContext, String classname, String managedServerName) throws InvalidSyntaxException + public static Filter createFilter(BundleContext bundleContext, String classname, String managedServerName) throws InvalidSyntaxException { if (StringUtil.isBlank(managedServerName) || managedServerName.equals(OSGiServerConstants.MANAGED_JETTY_SERVER_DEFAULT_NAME)) { - return bundleContext.createFilter("(&(objectclass=" + classname - + ")(|(managedServerName="+managedServerName - +")(!(managedServerName=*))))"); + return bundleContext.createFilter("(&(objectclass=" + classname + ")(|(managedServerName=" + managedServerName + ")(!(managedServerName=*))))"); } else { - return bundleContext.createFilter("(&(objectclass=" + classname+ ")(managedServerName="+managedServerName+"))"); + return bundleContext.createFilter("(&(objectclass=" + classname + ")(managedServerName=" + managedServerName + "))"); } - } - + /** * Get the value of a manifest header. - * + * * @param name the name of the header * @param altName an alternative name for the header (useful for deprecated names) * @param manifest the dictionary * @return the value from the manifest */ - public static String getManifestHeaderValue (String name, String altName, Dictionary manifest) + public static String getManifestHeaderValue(String name, String altName, Dictionary manifest) { if (manifest == null) return null; @@ -90,24 +84,22 @@ public class Util * @param manifest the dictionary * @return the value from the manifest */ - public static String getManifestHeaderValue (String name, Dictionary manifest) + public static String getManifestHeaderValue(String name, Dictionary manifest) { return getManifestHeaderValue(name, null, manifest); } - - /* ------------------------------------------------------------ */ /** * Treating the string as a separated list of filenames, * convert and return the list of urls. - * + * * @param val the separated list of filenames * @param delims the separators (default is ,;) * @return the list of URLs found in the input list * @throws Exception if unable to convert entry to a URL */ - public static List fileNamesAsURLs(String val, String delims) - throws Exception + public static List fileNamesAsURLs(String val, String delims) + throws Exception { String separators = DEFAULT_DELIMS; if (delims == null) @@ -121,34 +113,36 @@ public class Util } return urls; } - - - /* ------------------------------------------------------------ */ - public static void setProperty(Dictionary properties, String key, Object value) + + public static void setProperty(Dictionary properties, String key, Object value) { if (value != null) { properties.put(key, value); } } - - - /* ------------------------------------------------------------ */ + /** * recursively substitute the ${sysprop} by their actual system property. * ${sysprop,defaultvalue} will use 'defaultvalue' as the value if no * sysprop is defined. Not the most efficient code but we are shooting for * simplicity and speed of development here. - * + * * @param value the input string * @return the string with replaced properties */ public static String resolvePropertyValue(String value) { int ind = value.indexOf("${"); - if (ind == -1) { return value; } + if (ind == -1) + { + return value; + } int ind2 = value.indexOf('}', ind); - if (ind2 == -1) { return value; } + if (ind2 == -1) + { + return value; + } String sysprop = value.substring(ind + 2, ind2); String defaultValue = null; int comma = sysprop.indexOf(','); diff --git a/jetty-osgi/jetty-osgi-boot/src/main/java/org/eclipse/jetty/osgi/boot/utils/internal/DefaultBundleClassLoaderHelper.java b/jetty-osgi/jetty-osgi-boot/src/main/java/org/eclipse/jetty/osgi/boot/utils/internal/DefaultBundleClassLoaderHelper.java index 9dd493c576c..bbc7af2242e 100644 --- a/jetty-osgi/jetty-osgi-boot/src/main/java/org/eclipse/jetty/osgi/boot/utils/internal/DefaultBundleClassLoaderHelper.java +++ b/jetty-osgi/jetty-osgi-boot/src/main/java/org/eclipse/jetty/osgi/boot/utils/internal/DefaultBundleClassLoaderHelper.java @@ -36,7 +36,13 @@ import org.osgi.framework.Bundle; public class DefaultBundleClassLoaderHelper implements BundleClassLoaderHelper { private static final Logger LOG = Log.getLogger(BundleClassLoaderHelper.class); - private static enum OSGiContainerType {EquinoxOld, EquinoxLuna, FelixOld, Felix403, Concierge}; + + private static enum OSGiContainerType + { + EquinoxOld, EquinoxLuna, FelixOld, Felix403, Concierge + } + + ; private static OSGiContainerType osgiContainer; private static Class Equinox_BundleHost_Class; private static Class Equinox_EquinoxBundle_Class; @@ -47,26 +53,25 @@ public class DefaultBundleClassLoaderHelper implements BundleClassLoaderHelper private static Method Equinox_BundleLoader_createClassLoader_method; //new equinox private static Method Equinox_EquinoxBundle_getModuleClassLoader_Method; - + //new felix private static Method Felix_BundleImpl_Adapt_Method; //old felix private static Field Felix_BundleImpl_m_Modules_Field; private static Field Felix_ModuleImpl_m_ClassLoader_Field; private static Method Felix_BundleWiring_getClassLoader_Method; - + // Concierge private static Class Concierge_BundleImpl_Class; private static Class Concierge_BundleWiring_Class; private static Method Concierge_BundleImpl_Adapt_Method; private static Method Concierge_BundleWiring_getClassLoader_Method; - - - private static void checkContainerType (Bundle bundle) + + private static void checkContainerType(Bundle bundle) { if (osgiContainer != null) return; - + try { Equinox_BundleHost_Class = bundle.getClass().getClassLoader().loadClass("org.eclipse.osgi.framework.internal.core.BundleHost"); @@ -88,14 +93,14 @@ public class DefaultBundleClassLoaderHelper implements BundleClassLoaderHelper { LOG.ignore(e); } - + try - { + { //old felix or new felix? - Felix_BundleImpl_Class = bundle.getClass().getClassLoader().loadClass("org.apache.felix.framework.BundleImpl"); + Felix_BundleImpl_Class = bundle.getClass().getClassLoader().loadClass("org.apache.felix.framework.BundleImpl"); try { - Felix_BundleImpl_Adapt_Method = Felix_BundleImpl_Class.getDeclaredMethod("adapt", new Class[] {Class.class}); + Felix_BundleImpl_Adapt_Method = Felix_BundleImpl_Class.getDeclaredMethod("adapt", new Class[]{Class.class}); osgiContainer = OSGiContainerType.Felix403; return; } @@ -109,7 +114,7 @@ public class DefaultBundleClassLoaderHelper implements BundleClassLoaderHelper { LOG.ignore(e); } - + try { Concierge_BundleImpl_Class = bundle.getClass().getClassLoader().loadClass("org.eclipse.concierge.BundleImpl"); @@ -125,24 +130,20 @@ public class DefaultBundleClassLoaderHelper implements BundleClassLoaderHelper return; } - - - - /** * Assuming the bundle is started. - * + * * @param bundle the bundle * @return classloader object */ @Override public ClassLoader getBundleClassLoader(Bundle bundle) { - String bundleActivator = (String) bundle.getHeaders().get("Bundle-Activator"); - + String bundleActivator = (String)bundle.getHeaders().get("Bundle-Activator"); + if (bundleActivator == null) { - bundleActivator = (String) bundle.getHeaders().get("Jetty-ClassInBundle"); + bundleActivator = (String)bundle.getHeaders().get("Jetty-ClassInBundle"); } if (bundleActivator != null) { @@ -155,24 +156,23 @@ public class DefaultBundleClassLoaderHelper implements BundleClassLoaderHelper LOG.warn(e); } } - + // resort to introspection return getBundleClassLoaderForContainer(bundle); } - + /** - * @param bundle - * @return + * */ - private ClassLoader getBundleClassLoaderForContainer (Bundle bundle) + private ClassLoader getBundleClassLoaderForContainer(Bundle bundle) { - checkContainerType (bundle); + checkContainerType(bundle); if (osgiContainer == null) { LOG.warn("No classloader for unknown OSGi container type"); return null; } - + switch (osgiContainer) { case EquinoxOld: @@ -184,28 +184,24 @@ public class DefaultBundleClassLoaderHelper implements BundleClassLoaderHelper case FelixOld: case Felix403: { - return internalGetFelixBundleClassLoader(bundle); + return internalGetFelixBundleClassLoader(bundle); } case Concierge: { - return internalGetConciergeBundleClassLoader(bundle); + return internalGetConciergeBundleClassLoader(bundle); } default: { - LOG.warn("No classloader found for bundle "+bundle.getSymbolicName()); + LOG.warn("No classloader found for bundle " + bundle.getSymbolicName()); return null; - } } } - - /** - * @param bundle - * @return + * */ private static ClassLoader internalGetEquinoxBundleClassLoader(Bundle bundle) { @@ -215,18 +211,18 @@ public class DefaultBundleClassLoaderHelper implements BundleClassLoaderHelper { if (Equinox_BundleHost_getBundleLoader_method == null) { - Equinox_BundleHost_getBundleLoader_method = - Equinox_BundleHost_Class.getDeclaredMethod("getBundleLoader", new Class[] {}); + Equinox_BundleHost_getBundleLoader_method = + Equinox_BundleHost_Class.getDeclaredMethod("getBundleLoader", new Class[]{}); Equinox_BundleHost_getBundleLoader_method.setAccessible(true); } - Object bundleLoader = Equinox_BundleHost_getBundleLoader_method.invoke(bundle, new Object[] {}); + Object bundleLoader = Equinox_BundleHost_getBundleLoader_method.invoke(bundle, new Object[]{}); if (Equinox_BundleLoader_createClassLoader_method == null && bundleLoader != null) { - Equinox_BundleLoader_createClassLoader_method = - bundleLoader.getClass().getClassLoader().loadClass("org.eclipse.osgi.internal.loader.BundleLoader").getDeclaredMethod("createClassLoader", new Class[] {}); + Equinox_BundleLoader_createClassLoader_method = + bundleLoader.getClass().getClassLoader().loadClass("org.eclipse.osgi.internal.loader.BundleLoader").getDeclaredMethod("createClassLoader", new Class[]{}); Equinox_BundleLoader_createClassLoader_method.setAccessible(true); } - return (ClassLoader) Equinox_BundleLoader_createClassLoader_method.invoke(bundleLoader, new Object[] {}); + return (ClassLoader)Equinox_BundleLoader_createClassLoader_method.invoke(bundleLoader, new Object[]{}); } catch (ClassNotFoundException t) { @@ -239,16 +235,20 @@ public class DefaultBundleClassLoaderHelper implements BundleClassLoaderHelper return null; } } - + if (osgiContainer == OSGiContainerType.EquinoxLuna) { try { if (Equinox_EquinoxBundle_getModuleClassLoader_Method == null) - Equinox_EquinoxBundle_getModuleClassLoader_Method = Equinox_EquinoxBundle_Class.getDeclaredMethod("getModuleClassLoader", new Class[] {Boolean.TYPE}); + Equinox_EquinoxBundle_getModuleClassLoader_Method = Equinox_EquinoxBundle_Class.getDeclaredMethod("getModuleClassLoader", new Class[]{ + Boolean.TYPE + }); Equinox_EquinoxBundle_getModuleClassLoader_Method.setAccessible(true); - return (ClassLoader)Equinox_EquinoxBundle_getModuleClassLoader_Method.invoke(bundle, new Object[] {Boolean.FALSE}); + return (ClassLoader)Equinox_EquinoxBundle_getModuleClassLoader_Method.invoke(bundle, new Object[]{ + Boolean.FALSE + }); } catch (Exception e) { @@ -256,22 +256,18 @@ public class DefaultBundleClassLoaderHelper implements BundleClassLoaderHelper return null; } } - - LOG.warn("No classloader for equinox platform for bundle "+bundle.getSymbolicName()); + + LOG.warn("No classloader for equinox platform for bundle " + bundle.getSymbolicName()); return null; } - - - /** - * @param bundle - * @return + * */ @SuppressWarnings("unchecked") private static ClassLoader internalGetFelixBundleClassLoader(Bundle bundle) { - + if (osgiContainer == OSGiContainerType.Felix403) { try @@ -279,7 +275,6 @@ public class DefaultBundleClassLoaderHelper implements BundleClassLoaderHelper if (Felix_BundleWiring_Class == null) Felix_BundleWiring_Class = bundle.getClass().getClassLoader().loadClass("org.osgi.framework.wiring.BundleWiring"); - Felix_BundleImpl_Adapt_Method.setAccessible(true); if (Felix_BundleWiring_getClassLoader_Method == null) @@ -288,8 +283,7 @@ public class DefaultBundleClassLoaderHelper implements BundleClassLoaderHelper Felix_BundleWiring_getClassLoader_Method.setAccessible(true); } - - Object wiring = Felix_BundleImpl_Adapt_Method.invoke(bundle, new Object[] {Felix_BundleWiring_Class}); + Object wiring = Felix_BundleImpl_Adapt_Method.invoke(bundle, new Object[]{Felix_BundleWiring_Class}); return (ClassLoader)Felix_BundleWiring_getClassLoader_Method.invoke(wiring); } catch (Exception e) @@ -299,9 +293,8 @@ public class DefaultBundleClassLoaderHelper implements BundleClassLoaderHelper } } - if (osgiContainer == OSGiContainerType.FelixOld) - { + { try { if (Felix_BundleImpl_m_Modules_Field == null) @@ -315,14 +308,14 @@ public class DefaultBundleClassLoaderHelper implements BundleClassLoaderHelper try { - Object[] moduleArray = (Object[]) Felix_BundleImpl_m_Modules_Field.get(bundle); + Object[] moduleArray = (Object[])Felix_BundleImpl_m_Modules_Field.get(bundle); currentModuleImpl = moduleArray[moduleArray.length - 1]; } - catch (Throwable t2) + catch (Throwable ex) { try { - List moduleArray = (List) Felix_BundleImpl_m_Modules_Field.get(bundle); + List moduleArray = (List)Felix_BundleImpl_m_Modules_Field.get(bundle); currentModuleImpl = moduleArray.get(moduleArray.size() - 1); } catch (Exception e) @@ -352,7 +345,7 @@ public class DefaultBundleClassLoaderHelper implements BundleClassLoaderHelper ClassLoader cl = null; try { - cl = (ClassLoader) Felix_ModuleImpl_m_ClassLoader_Field.get(currentModuleImpl); + cl = (ClassLoader)Felix_ModuleImpl_m_ClassLoader_Field.get(currentModuleImpl); if (cl != null) return cl; } @@ -369,7 +362,7 @@ public class DefaultBundleClassLoaderHelper implements BundleClassLoaderHelper try { bundle.loadClass("java.lang.Object"); - cl = (ClassLoader) Felix_ModuleImpl_m_ClassLoader_Field.get(currentModuleImpl); + cl = (ClassLoader)Felix_ModuleImpl_m_ClassLoader_Field.get(currentModuleImpl); return cl; } catch (Exception e) @@ -377,21 +370,20 @@ public class DefaultBundleClassLoaderHelper implements BundleClassLoaderHelper LOG.warn(e); return null; } - } + } catch (Exception e) { LOG.warn(e); return null; } } - - LOG.warn("No classloader for felix platform for bundle "+bundle.getSymbolicName()); + + LOG.warn("No classloader for felix platform for bundle " + bundle.getSymbolicName()); return null; } - + /** - * @param bundle - * @return + * */ private static ClassLoader internalGetConciergeBundleClassLoader(Bundle bundle) { @@ -399,33 +391,34 @@ public class DefaultBundleClassLoaderHelper implements BundleClassLoaderHelper { try { - /** + /** * In Concierge: - * + * * Option A: *
                      * Concierge concierge = new Concierge(...);
                      * BundleWiring bundleWiring = concierge.getWiring(); // method is public
                      * 
    * Problem: getWiring not yet implementd - * + * * Option B: *
                      * Concierge concierge = new Concierge(...);
                      * BundleWiring bundleWiring = concierge.adapt(org.osgi.framework.wiring.BundleWiring);
                      * 
    * Same approach as done in Felix. - * + * */ - if (Concierge_BundleWiring_Class == null) { + if (Concierge_BundleWiring_Class == null) + { Concierge_BundleWiring_Class = bundle.getClass().getClassLoader().loadClass("org.osgi.framework.wiring.BundleWiring"); - Concierge_BundleImpl_Adapt_Method = Concierge_BundleImpl_Class.getMethod("adapt", new Class[] {Class.class}); + Concierge_BundleImpl_Adapt_Method = Concierge_BundleImpl_Class.getMethod("adapt", new Class[]{Class.class}); Concierge_BundleImpl_Adapt_Method.setAccessible(true); Concierge_BundleWiring_getClassLoader_Method = Concierge_BundleWiring_Class.getMethod("getClassLoader"); Concierge_BundleWiring_getClassLoader_Method.setAccessible(true); } - Object wiring = Concierge_BundleImpl_Adapt_Method.invoke(bundle, new Object[] {Concierge_BundleWiring_Class}); + Object wiring = Concierge_BundleImpl_Adapt_Method.invoke(bundle, new Object[]{Concierge_BundleWiring_Class}); ClassLoader cl = (ClassLoader)Concierge_BundleWiring_getClassLoader_Method.invoke(wiring); return cl; } @@ -436,7 +429,7 @@ public class DefaultBundleClassLoaderHelper implements BundleClassLoaderHelper } } - LOG.warn("No classloader for Concierge platform for bundle "+bundle.getSymbolicName()); + LOG.warn("No classloader for Concierge platform for bundle " + bundle.getSymbolicName()); return null; } } diff --git a/jetty-osgi/jetty-osgi-boot/src/main/java/org/eclipse/jetty/osgi/boot/utils/internal/DefaultFileLocatorHelper.java b/jetty-osgi/jetty-osgi-boot/src/main/java/org/eclipse/jetty/osgi/boot/utils/internal/DefaultFileLocatorHelper.java index 926b76d67a3..4692074d055 100644 --- a/jetty-osgi/jetty-osgi-boot/src/main/java/org/eclipse/jetty/osgi/boot/utils/internal/DefaultFileLocatorHelper.java +++ b/jetty-osgi/jetty-osgi-boot/src/main/java/org/eclipse/jetty/osgi/boot/utils/internal/DefaultFileLocatorHelper.java @@ -37,7 +37,7 @@ import org.osgi.framework.Bundle; /** * DefaultFileLocatorHelper - *

    + *

    * From a bundle to its location on the filesystem. Assumes the bundle is not a * jar. */ @@ -59,30 +59,38 @@ public class DefaultFileLocatorHelper implements BundleFileLocatorHelper // DirZipBundleEntry private static Field ZIP_FILE_FILED_FOR_ZIP_BUNDLE_FILE = null;// ZipFile - - private static final String[] FILE_BUNDLE_ENTRY_CLASSES = {"org.eclipse.osgi.baseadaptor.bundlefile.FileBundleEntry","org.eclipse.osgi.storage.bundlefile.FileBundleEntry"}; - private static final String[] ZIP_BUNDLE_ENTRY_CLASSES = {"org.eclipse.osgi.baseadaptor.bundlefile.ZipBundleEntry","org.eclipse.osgi.storage.bundlefile.ZipBundleEntry"}; - private static final String[] DIR_ZIP_BUNDLE_ENTRY_CLASSES = {"org.eclipse.osgi.baseadaptor.bundlefile.DirZipBundleEntry","org.eclipse.osgi.storage.bundlefile.DirZipBundleEntry"}; - private static final String[] BUNDLE_URL_CONNECTION_CLASSES = {"org.eclipse.osgi.framework.internal.core.BundleURLConnection", "org.eclipse.osgi.storage.url.BundleURLConnection"}; + private static final String[] FILE_BUNDLE_ENTRY_CLASSES = { + "org.eclipse.osgi.baseadaptor.bundlefile.FileBundleEntry", "org.eclipse.osgi.storage.bundlefile.FileBundleEntry" + }; + private static final String[] ZIP_BUNDLE_ENTRY_CLASSES = { + "org.eclipse.osgi.baseadaptor.bundlefile.ZipBundleEntry", "org.eclipse.osgi.storage.bundlefile.ZipBundleEntry" + }; + private static final String[] DIR_ZIP_BUNDLE_ENTRY_CLASSES = { + "org.eclipse.osgi.baseadaptor.bundlefile.DirZipBundleEntry", "org.eclipse.osgi.storage.bundlefile.DirZipBundleEntry" + }; + private static final String[] BUNDLE_URL_CONNECTION_CLASSES = { + "org.eclipse.osgi.framework.internal.core.BundleURLConnection", "org.eclipse.osgi.storage.url.BundleURLConnection" + }; - public static boolean match (String name, String... names) + public static boolean match(String name, String... names) { if (name == null || names == null) return false; boolean matched = false; - for (int i=0; i< names.length && !matched; i++) + for (int i = 0; i < names.length && !matched; i++) + { if (name.equals(names[i])) matched = true; + } return matched; } - - + /** * Works with equinox, felix, nuxeo and probably more. Not exactly in the * spirit of OSGi but quite necessary to support self-contained webapps and * other situations. - * + * * @param bundle The bundle * @return Its installation location as a file. * @throws Exception if unable to get the bundle install location @@ -122,7 +130,7 @@ public class DefaultFileLocatorHelper implements BundleFileLocatorHelper BUNDLE_ENTRY_FIELD.setAccessible(true); } Object bundleEntry = BUNDLE_ENTRY_FIELD.get(con); - + if (match(bundleEntry.getClass().getName(), FILE_BUNDLE_ENTRY_CLASSES)) { if (FILE_FIELD == null) @@ -130,7 +138,7 @@ public class DefaultFileLocatorHelper implements BundleFileLocatorHelper FILE_FIELD = bundleEntry.getClass().getDeclaredField("file"); FILE_FIELD.setAccessible(true); } - File f = (File) FILE_FIELD.get(bundleEntry); + File f = (File)FILE_FIELD.get(bundleEntry); return f.getParentFile().getParentFile().getCanonicalFile(); } else if (match(bundleEntry.getClass().getName(), ZIP_BUNDLE_ENTRY_CLASSES)) @@ -141,7 +149,8 @@ public class DefaultFileLocatorHelper implements BundleFileLocatorHelper con.setDefaultUseCaches(Resource.getDefaultUseCaches()); if (BUNDLE_ENTRY_FIELD == null) - {// this one will be a DirZipBundleEntry + { + // this one will be a DirZipBundleEntry BUNDLE_ENTRY_FIELD = con.getClass().getDeclaredField("bundleEntry"); BUNDLE_ENTRY_FIELD.setAccessible(true); } @@ -157,10 +166,10 @@ public class DefaultFileLocatorHelper implements BundleFileLocatorHelper ZIP_FILE_FILED_FOR_ZIP_BUNDLE_FILE = zipBundleFile.getClass().getDeclaredField("zipFile"); ZIP_FILE_FILED_FOR_ZIP_BUNDLE_FILE.setAccessible(true); } - ZipFile zipFile = (ZipFile) ZIP_FILE_FILED_FOR_ZIP_BUNDLE_FILE.get(zipBundleFile); + ZipFile zipFile = (ZipFile)ZIP_FILE_FILED_FOR_ZIP_BUNDLE_FILE.get(zipBundleFile); return new File(zipFile.getName()); } - else if (match (bundleEntry.getClass().getName(), DIR_ZIP_BUNDLE_ENTRY_CLASSES)) + else if (match(bundleEntry.getClass().getName(), DIR_ZIP_BUNDLE_ENTRY_CLASSES)) { // that will not happen as we did ask for the manifest not a // directory. @@ -181,18 +190,20 @@ public class DefaultFileLocatorHelper implements BundleFileLocatorHelper // it is relative to relative to the BundleArchive's // m_archiveRootDir File res = new File(location.substring("file:".length())); - if (!res.exists()) { return null; - // Object bundleArchive = getFelixBundleArchive(bundle); - // File archiveRoot = - // getFelixBundleArchiveRootDir(bundleArchive); - // String currentLocation = - // getFelixBundleArchiveCurrentLocation(bundleArchive); - // System.err.println("Got the archive root " + - // archiveRoot.getAbsolutePath() - // + " current location " + currentLocation + - // " is directory ?"); - // res = new File(archiveRoot, currentLocation != null - // ? currentLocation : location.substring("file:".length())); + if (!res.exists()) + { + return null; + // Object bundleArchive = getFelixBundleArchive(bundle); + // File archiveRoot = + // getFelixBundleArchiveRootDir(bundleArchive); + // String currentLocation = + // getFelixBundleArchiveCurrentLocation(bundleArchive); + // System.err.println("Got the archive root " + + // archiveRoot.getAbsolutePath() + // + " current location " + currentLocation + + // " is directory ?"); + // res = new File(archiveRoot, currentLocation != null + // ? currentLocation : location.substring("file:".length())); } return res; } @@ -208,7 +219,7 @@ public class DefaultFileLocatorHelper implements BundleFileLocatorHelper /** * Locate a file inside a bundle. - * + * * @param bundle the bundle * @param path the path * @return file object @@ -223,12 +234,11 @@ public class DefaultFileLocatorHelper implements BundleFileLocatorHelper } File bundleInstall = getBundleInstallLocation(bundle); File webapp = path != null && path.length() != 0 ? new File(bundleInstall, path) : bundleInstall; - if (!webapp.exists()) { throw new IllegalArgumentException("Unable to locate " + path - + " inside " - + bundle.getSymbolicName() - + " (" - + (bundleInstall != null ? bundleInstall.getAbsolutePath() : " no_bundle_location ") - + ")"); } + if (!webapp.exists()) + { + throw new IllegalArgumentException("Unable to locate " + path + " inside " + bundle.getSymbolicName() + + " (" + (bundleInstall != null ? bundleInstall.getAbsolutePath() : " no_bundle_location ") + ")"); + } return webapp; } @@ -236,7 +246,7 @@ public class DefaultFileLocatorHelper implements BundleFileLocatorHelper * Helper method equivalent to Bundle#getEntry(String entryPath) except that * it searches for entries in the fragments by using the Bundle#findEntries * method. - * + * * @param bundle the bundle * @param entryPath the entry path * @return null or all the entries found for that path. @@ -265,10 +275,10 @@ public class DefaultFileLocatorHelper implements BundleFileLocatorHelper * development purpose where the bundle was imported in pde and the classes * kept in a jar. *

    - * + * * @param bundle the bundle * @return The jar(s) file that is either the bundle itself, either the jars - * embedded inside it. + * embedded inside it. */ @Override public File[] locateJarsInsideBundle(Bundle bundle) throws Exception @@ -299,7 +309,7 @@ public class DefaultFileLocatorHelper implements BundleFileLocatorHelper } else { - return new File[] { jasperLocation }; + return new File[]{jasperLocation}; } } @@ -318,12 +328,12 @@ public class DefaultFileLocatorHelper implements BundleFileLocatorHelper * Get a URL to the bundle entry that uses a common protocol (i.e. file: * jar: or http: etc.). *

    - * + * * @return a URL to the bundle entry that uses a common protocol */ @Override public URL getLocalURL(URL url) - throws Exception + throws Exception { if ("bundleresource".equals(url.getProtocol()) || "bundleentry".equals(url.getProtocol())) { @@ -335,7 +345,10 @@ public class DefaultFileLocatorHelper implements BundleFileLocatorHelper BUNDLE_URL_CONNECTION_getLocalURL = conn.getClass().getMethod("getLocalURL"); BUNDLE_URL_CONNECTION_getLocalURL.setAccessible(true); } - if (BUNDLE_URL_CONNECTION_getLocalURL != null) { return (URL) BUNDLE_URL_CONNECTION_getLocalURL.invoke(conn); } + if (BUNDLE_URL_CONNECTION_getLocalURL != null) + { + return (URL)BUNDLE_URL_CONNECTION_getLocalURL.invoke(conn); + } } return url; } @@ -347,32 +360,31 @@ public class DefaultFileLocatorHelper implements BundleFileLocatorHelper * Get a URL to the content of the bundle entry that uses the file: * protocol. The content of the bundle entry may be downloaded or extracted * to the local file system in order to create a file: URL. - * + * * @return a URL to the content of the bundle entry that uses the file: - * protocol - *

    - * @throws Exception if unable to get the file url + * protocol + *

    + * @throws Exception if unable to get the file url */ @Override public URL getFileURL(URL url) throws Exception - + { if ("bundleresource".equals(url.getProtocol()) || "bundleentry".equals(url.getProtocol())) { URLConnection conn = url.openConnection(); conn.setDefaultUseCaches(Resource.getDefaultUseCaches()); - if (BUNDLE_URL_CONNECTION_getFileURL == null - && - match (conn.getClass().getName(), BUNDLE_URL_CONNECTION_CLASSES)) + if (BUNDLE_URL_CONNECTION_getFileURL == null && match(conn.getClass().getName(), BUNDLE_URL_CONNECTION_CLASSES)) { BUNDLE_URL_CONNECTION_getFileURL = conn.getClass().getMethod("getFileURL"); BUNDLE_URL_CONNECTION_getFileURL.setAccessible(true); } - if (BUNDLE_URL_CONNECTION_getFileURL != null) { return (URL) BUNDLE_URL_CONNECTION_getFileURL.invoke(conn); } - + if (BUNDLE_URL_CONNECTION_getFileURL != null) + { + return (URL)BUNDLE_URL_CONNECTION_getFileURL.invoke(conn); + } } return url; } - } diff --git a/jetty-osgi/jetty-osgi-boot/src/main/java/org/eclipse/jetty/osgi/boot/utils/internal/PackageAdminServiceTracker.java b/jetty-osgi/jetty-osgi-boot/src/main/java/org/eclipse/jetty/osgi/boot/utils/internal/PackageAdminServiceTracker.java index b2662a93762..fb1415985f9 100644 --- a/jetty-osgi/jetty-osgi-boot/src/main/java/org/eclipse/jetty/osgi/boot/utils/internal/PackageAdminServiceTracker.java +++ b/jetty-osgi/jetty-osgi-boot/src/main/java/org/eclipse/jetty/osgi/boot/utils/internal/PackageAdminServiceTracker.java @@ -39,7 +39,7 @@ import org.osgi.service.startlevel.StartLevel; *

    * When the PackageAdmin service is activated we can look for the fragments * attached to this bundle and do a fake "activate" on them. - *

    + *

    * See particularly the jetty-osgi-boot-jsp fragment bundle that uses this * facility. */ @@ -83,12 +83,13 @@ public class PackageAdminServiceTracker implements ServiceListener { ServiceReference sr = _context.getServiceReference(PackageAdmin.class.getName()); _fragmentsWereActivated = sr != null; - if (sr != null) invokeFragmentActivators(sr); + if (sr != null) + invokeFragmentActivators(sr); sr = _context.getServiceReference(StartLevel.class.getName()); if (sr != null) { - _startLevel = (StartLevel) _context.getService(sr); + _startLevel = (StartLevel)_context.getService(sr); try { _maxStartLevel = Integer.parseInt(System.getProperty("osgi.startLevel", "6")); @@ -107,7 +108,7 @@ public class PackageAdminServiceTracker implements ServiceListener * bundle activator for a fragment must be in the package that is defined by * the symbolic name of the fragment and the name of the class must be * 'FragmentActivator'. - * + * * @param event The ServiceEvent object. */ @Override @@ -123,7 +124,7 @@ public class PackageAdminServiceTracker implements ServiceListener * Helper to access the PackageAdmin and return the fragments hosted by a * bundle. when we drop the support for the older versions of OSGi, we will * stop using the PackageAdmin service. - * + * * @param bundle the bundle * @return the bundle fragment list */ @@ -131,10 +132,11 @@ public class PackageAdminServiceTracker implements ServiceListener { ServiceReference sr = _context.getServiceReference(PackageAdmin.class.getName()); if (sr == null) - {// we should never be here really. + { + // we should never be here really. return null; } - PackageAdmin admin = (PackageAdmin) _context.getService(sr); + PackageAdmin admin = (PackageAdmin)_context.getService(sr); return admin.getFragments(bundle); } @@ -142,7 +144,7 @@ public class PackageAdminServiceTracker implements ServiceListener * Returns the fragments and the required-bundles of a bundle. Recursively * collect the required-bundles and fragment when the directive * visibility:=reexport is added to a required-bundle. - * + * * @param bundle the bundle * @return the bundle fragment and required list */ @@ -150,10 +152,11 @@ public class PackageAdminServiceTracker implements ServiceListener { ServiceReference sr = _context.getServiceReference(PackageAdmin.class.getName()); if (sr == null) - {// we should never be here really. + { + // we should never be here really. return null; } - PackageAdmin admin = (PackageAdmin) _context.getService(sr); + PackageAdmin admin = (PackageAdmin)_context.getService(sr); LinkedHashMap deps = new LinkedHashMap<>(); collectFragmentsAndRequiredBundles(bundle, admin, deps, false); return deps.values().toArray(new Bundle[deps.size()]); @@ -163,14 +166,14 @@ public class PackageAdminServiceTracker implements ServiceListener * Returns the fragments and the required-bundles. Collects them * transitively when the directive 'visibility:=reexport' is added to a * required-bundle. - * + * * @param bundle the bundle * @param admin the admin package * @param deps The map of fragment and required bundles associated to the value of the - * jetty-web attribute. + * jetty-web attribute. * @param onlyReexport true to collect resources and web-fragments - * transitively if and only if the directive visibility is - * reexport. + * transitively if and only if the directive visibility is + * reexport. */ protected void collectFragmentsAndRequiredBundles(Bundle bundle, PackageAdmin admin, Map deps, boolean onlyReexport) { @@ -195,19 +198,22 @@ public class PackageAdminServiceTracker implements ServiceListener /** * A simplistic but good enough parser for the Require-Bundle header. Parses * the version range attribute and the visibility directive. - * + * * @param bundle the bundle - * @param admin the admin package + * @param admin the admin package * @param deps The map of required bundles associated to the value of the - * jetty-web attribute. + * jetty-web attribute. * @param onlyReexport true to collect resources and web-fragments - * transitively if and only if the directive visibility is - * reexport. + * transitively if and only if the directive visibility is + * reexport. */ protected void collectRequiredBundles(Bundle bundle, PackageAdmin admin, Map deps, boolean onlyReexport) { - String requiredBundleHeader = (String) bundle.getHeaders().get("Require-Bundle"); - if (requiredBundleHeader == null) { return; } + String requiredBundleHeader = (String)bundle.getHeaders().get("Require-Bundle"); + if (requiredBundleHeader == null) + { + return; + } StringTokenizer tokenizer = new ManifestTokenizer(requiredBundleHeader); while (tokenizer.hasMoreTokens()) { @@ -241,7 +247,10 @@ public class PackageAdminServiceTracker implements ServiceListener reexport = true; } } - if (!reexport && onlyReexport) { return; } + if (!reexport && onlyReexport) + { + return; + } Bundle[] reqBundles = admin.getBundles(symbolicName, versionRange); if (reqBundles != null && reqBundles.length != 0) { @@ -268,9 +277,12 @@ public class PackageAdminServiceTracker implements ServiceListener private void invokeFragmentActivators(ServiceReference sr) { - PackageAdmin admin = (PackageAdmin) _context.getService(sr); + PackageAdmin admin = (PackageAdmin)_context.getService(sr); Bundle[] fragments = admin.getFragments(_context.getBundle()); - if (fragments == null) { return; } + if (fragments == null) + { + return; + } for (Bundle frag : fragments) { // find a convention to look for a class inside the fragment. @@ -280,7 +292,7 @@ public class PackageAdminServiceTracker implements ServiceListener Class c = Class.forName(fragmentActivator); if (c != null) { - BundleActivator bActivator = (BundleActivator) c.getDeclaredConstructor().newInstance(); + BundleActivator bActivator = (BundleActivator)c.getDeclaredConstructor().newInstance(); bActivator.start(_context); _activatedFragments.add(bActivator); } @@ -342,7 +354,10 @@ public class PackageAdminServiceTracker implements ServiceListener do { int quote = getQuote(token, i + 1); - if (quote < 0) { return false; } + if (quote < 0) + { + return false; + } i = token.indexOf(quote, i + 1); i = token.indexOf(quote, i + 1); @@ -366,12 +381,16 @@ public class PackageAdminServiceTracker implements ServiceListener return '\''; } } - if (j < 0) { return '"'; } - if (i < j) { return '"'; } + if (j < 0) + { + return '"'; + } + if (i < j) + { + return '"'; + } return '\''; } - } - } diff --git a/jetty-osgi/jetty-osgi-httpservice/pom.xml b/jetty-osgi/jetty-osgi-httpservice/pom.xml index 3f8808902f7..7bc6e744093 100644 --- a/jetty-osgi/jetty-osgi-httpservice/pom.xml +++ b/jetty-osgi/jetty-osgi-httpservice/pom.xml @@ -46,7 +46,7 @@ - + @@ -57,24 +57,19 @@ - org.apache.felix - maven-bundle-plugin - true - - - org.eclipse.jetty.osgi.httpservice - OSGi HttpService - contexts/httpservice.xml - org.eclipse.jetty.server.handler;version="[9.1,11.0)", -org.eclipse.jetty.util.component;version="[9.1,11.0)", -org.eclipse.jetty.server.session;version="[9.1,11.0)", -org.eclipse.jetty.servlet;version="[9.1,11.0)", -org.eclipse.equinox.http.servlet, -* - - <_nouses>true - - + org.apache.felix + maven-bundle-plugin + true + + + org.eclipse.jetty.osgi.httpservice + OSGi HttpService + contexts/httpservice.xml + org.eclipse.jetty.server.handler;version="[9.1,11.0)", org.eclipse.jetty.util.component;version="[9.1,11.0)", org.eclipse.jetty.server.session;version="[9.1,11.0)", org.eclipse.jetty.servlet;version="[9.1,11.0)", org.eclipse.equinox.http.servlet, * + + <_nouses>true + + org.codehaus.mojo diff --git a/jetty-osgi/jetty-osgi-httpservice/src/main/java/org/eclipse/jetty/osgi/httpservice/HttpServiceErrorHandlerHelper.java b/jetty-osgi/jetty-osgi-httpservice/src/main/java/org/eclipse/jetty/osgi/httpservice/HttpServiceErrorHandlerHelper.java index 249d9709cea..e14208c6212 100644 --- a/jetty-osgi/jetty-osgi-httpservice/src/main/java/org/eclipse/jetty/osgi/httpservice/HttpServiceErrorHandlerHelper.java +++ b/jetty-osgi/jetty-osgi-httpservice/src/main/java/org/eclipse/jetty/osgi/httpservice/HttpServiceErrorHandlerHelper.java @@ -30,16 +30,15 @@ import javax.servlet.http.HttpServlet; */ public class HttpServiceErrorHandlerHelper { - private static HttpServlet _customErrorHandler; + private static HttpServlet _customErrorHandler; - public static HttpServlet getCustomErrorHandler() - { - return _customErrorHandler; - } - - public static void setHttpServiceErrorHandler(HttpServlet servlet) - { - _customErrorHandler = servlet; - } - + public static HttpServlet getCustomErrorHandler() + { + return _customErrorHandler; + } + + public static void setHttpServiceErrorHandler(HttpServlet servlet) + { + _customErrorHandler = servlet; + } } diff --git a/jetty-osgi/jetty-osgi-httpservice/src/main/java/org/eclipse/jetty/osgi/httpservice/HttpServiceErrorPageErrorHandler.java b/jetty-osgi/jetty-osgi-httpservice/src/main/java/org/eclipse/jetty/osgi/httpservice/HttpServiceErrorPageErrorHandler.java index 45a7ed54ec6..85e22fb065c 100644 --- a/jetty-osgi/jetty-osgi-httpservice/src/main/java/org/eclipse/jetty/osgi/httpservice/HttpServiceErrorPageErrorHandler.java +++ b/jetty-osgi/jetty-osgi-httpservice/src/main/java/org/eclipse/jetty/osgi/httpservice/HttpServiceErrorPageErrorHandler.java @@ -19,7 +19,6 @@ package org.eclipse.jetty.osgi.httpservice; import java.io.IOException; - import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; @@ -35,46 +34,44 @@ import org.eclipse.jetty.servlet.ErrorPageErrorHandler; public class HttpServiceErrorPageErrorHandler extends ErrorPageErrorHandler { - private static HttpServiceErrorPageErrorHandler INSTANCE; - - public static HttpServiceErrorPageErrorHandler getInstance() - { - return INSTANCE; - } - - public HttpServiceErrorPageErrorHandler() - { - INSTANCE = this; - } + private static HttpServiceErrorPageErrorHandler INSTANCE; - @Override - public void handle(String target, Request baseRequest, - HttpServletRequest request, HttpServletResponse response) - throws IOException { - if (HttpServiceErrorHandlerHelper.getCustomErrorHandler() != null) - { - try - { - HttpServiceErrorHandlerHelper.getCustomErrorHandler().service(request, response); - } - catch (ServletException e) - { - //well - } - } - if (!response.isCommitted()) - { - super.handle(target, baseRequest, request, response); - } - } + public static HttpServiceErrorPageErrorHandler getInstance() + { + return INSTANCE; + } - @Override - protected void doStop() throws Exception + public HttpServiceErrorPageErrorHandler() + { + INSTANCE = this; + } + + @Override + public void handle(String target, Request baseRequest, + HttpServletRequest request, HttpServletResponse response) + throws IOException + { + if (HttpServiceErrorHandlerHelper.getCustomErrorHandler() != null) { - INSTANCE = null; - super.doStop(); + try + { + HttpServiceErrorHandlerHelper.getCustomErrorHandler().service(request, response); + } + catch (ServletException e) + { + //well + } } - - - + if (!response.isCommitted()) + { + super.handle(target, baseRequest, request, response); + } + } + + @Override + protected void doStop() throws Exception + { + INSTANCE = null; + super.doStop(); + } } diff --git a/jetty-osgi/pom.xml b/jetty-osgi/pom.xml index fc9a004e55e..ecc03573a34 100644 --- a/jetty-osgi/pom.xml +++ b/jetty-osgi/pom.xml @@ -1,6 +1,4 @@ - + org.eclipse.jetty jetty-project @@ -39,15 +37,15 @@ META-INF/.. true - **/.* - **/*.jar - .settings/**/* - pom.xml - - jettyhome/**/* - src/**/* - target/**/* - build.properties + **/.* + **/*.jar + .settings/**/* + pom.xml + + jettyhome/**/* + src/**/* + target/**/* + build.properties META-INF/**/* @@ -56,7 +54,7 @@ src/main/java - **/*.java + **/*.java diff --git a/jetty-osgi/test-jetty-osgi-context/pom.xml b/jetty-osgi/test-jetty-osgi-context/pom.xml index 2202e3c93a2..9deafe864a6 100644 --- a/jetty-osgi/test-jetty-osgi-context/pom.xml +++ b/jetty-osgi/test-jetty-osgi-context/pom.xml @@ -45,7 +45,7 @@ org.apache.maven.plugins maven-deploy-plugin - + true @@ -64,20 +64,7 @@ compilation time. --> <_nouses>true - javax.servlet;version="[3.1,4.1)", - javax.servlet.resources;version="[3.1,4.1)", - org.osgi.framework, - org.osgi.service.cm;version="1.2.0", - org.osgi.service.packageadmin, - org.osgi.service.startlevel;version="1.0.0", - org.osgi.service.url;version="1.0.0", - org.osgi.util.tracker;version="1.3.0", - org.slf4j;resolution:=optional, - org.slf4j.spi;resolution:=optional, - org.slf4j.helpers;resolution:=optional, - org.xml.sax, - org.xml.sax.helpers, - * + javax.servlet;version="[3.1,4.1)", javax.servlet.resources;version="[3.1,4.1)", org.osgi.framework, org.osgi.service.cm;version="1.2.0", org.osgi.service.packageadmin, org.osgi.service.startlevel;version="1.0.0", org.osgi.service.url;version="1.0.0", org.osgi.util.tracker;version="1.3.0", org.slf4j;resolution:=optional, org.slf4j.spi;resolution:=optional, org.slf4j.helpers;resolution:=optional, org.xml.sax, org.xml.sax.helpers, * org.eclipse.jetty.*;version="[9.1,10.0)" diff --git a/jetty-osgi/test-jetty-osgi-context/src/main/java/com/acme/osgi/Activator.java b/jetty-osgi/test-jetty-osgi-context/src/main/java/com/acme/osgi/Activator.java index 3a32624754d..63a1ee99048 100644 --- a/jetty-osgi/test-jetty-osgi-context/src/main/java/com/acme/osgi/Activator.java +++ b/jetty-osgi/test-jetty-osgi-context/src/main/java/com/acme/osgi/Activator.java @@ -30,27 +30,26 @@ import org.osgi.framework.ServiceRegistration; /** * Bootstrap a ContextHandler - * - * */ public class Activator implements BundleActivator { private ServiceRegistration _sr; + /** - * - * @param context + * */ @Override public void start(final BundleContext context) throws Exception { ContextHandler ch = new ContextHandler(); - ch.addEventListener(new ServletContextListener () { + ch.addEventListener(new ServletContextListener() + { @Override public void contextInitialized(ServletContextEvent sce) { - //System.err.println("Context is initialized"); + //System.err.println("Context is initialized"); } @Override @@ -58,19 +57,17 @@ public class Activator implements BundleActivator { //System.err.println("CONTEXT IS DESTROYED!"); } - }); Dictionary props = new Hashtable(); - props.put("Web-ContextPath","/acme"); + props.put("Web-ContextPath", "/acme"); props.put("Jetty-ContextFilePath", "acme.xml"); - _sr = context.registerService(ContextHandler.class.getName(),ch,props); + _sr = context.registerService(ContextHandler.class.getName(), ch, props); } /** * Stop the activator. - * - * @see - * org.osgi.framework.BundleActivator#stop(org.osgi.framework.BundleContext) + * + * @see org.osgi.framework.BundleActivator#stop(org.osgi.framework.BundleContext) */ @Override public void stop(BundleContext context) throws Exception diff --git a/jetty-osgi/test-jetty-osgi-fragment/pom.xml b/jetty-osgi/test-jetty-osgi-fragment/pom.xml index e2605644d2c..e43a76e22a4 100644 --- a/jetty-osgi/test-jetty-osgi-fragment/pom.xml +++ b/jetty-osgi/test-jetty-osgi-fragment/pom.xml @@ -13,37 +13,37 @@ ${project.groupId}.webapp.fragment - - - - src/main/resources - - + + + + src/main/resources + + + + + + org.apache.maven.plugins + maven-deploy-plugin + + + true + + + + org.apache.felix + maven-bundle-plugin + true + + + ${bundle-symbolic-name} + Jetty OSGi Test WebApp Fragment + J2SE-1.5 + org.eclipse.jetty.tests.test-spec-webapp + / + + + + + - - - org.apache.maven.plugins - maven-deploy-plugin - - - true - - - - org.apache.felix - maven-bundle-plugin - true - - - ${bundle-symbolic-name} - Jetty OSGi Test WebApp Fragment - J2SE-1.5 - org.eclipse.jetty.tests.test-spec-webapp - / - - - - - - diff --git a/jetty-osgi/test-jetty-osgi-server/pom.xml b/jetty-osgi/test-jetty-osgi-server/pom.xml index b47c195df90..a213793c34f 100644 --- a/jetty-osgi/test-jetty-osgi-server/pom.xml +++ b/jetty-osgi/test-jetty-osgi-server/pom.xml @@ -36,7 +36,7 @@ org.apache.maven.plugins maven-deploy-plugin - + true @@ -55,20 +55,7 @@ compilation time. --> <_nouses>true - javax.servlet;version="[3.1,4.1)", - javax.servlet.resources;version="[3.1,4.1)", - org.osgi.framework, - org.osgi.service.cm;version="1.2.0", - org.osgi.service.packageadmin, - org.osgi.service.startlevel;version="1.0.o", - org.osgi.service.url;version="1.0.0", - org.osgi.util.tracker;version="1.3.0", - org.slf4j;resolution:=optional, - org.slf4j.spi;resolution:=optional, - org.slf4j.helpers;resolution:=optional, - org.xml.sax, - org.xml.sax.helpers, - * + javax.servlet;version="[3.1,4.1)", javax.servlet.resources;version="[3.1,4.1)", org.osgi.framework, org.osgi.service.cm;version="1.2.0", org.osgi.service.packageadmin, org.osgi.service.startlevel;version="1.0.o", org.osgi.service.url;version="1.0.0", org.osgi.util.tracker;version="1.3.0", org.slf4j;resolution:=optional, org.slf4j.spi;resolution:=optional, org.slf4j.helpers;resolution:=optional, org.xml.sax, org.xml.sax.helpers, * org.eclipse.jetty.*;version="[9.1,10.0)" diff --git a/jetty-osgi/test-jetty-osgi-server/src/main/java/com/acme/osgi/Activator.java b/jetty-osgi/test-jetty-osgi-server/src/main/java/com/acme/osgi/Activator.java index d63f0cea377..0c688fe393c 100644 --- a/jetty-osgi/test-jetty-osgi-server/src/main/java/com/acme/osgi/Activator.java +++ b/jetty-osgi/test-jetty-osgi-server/src/main/java/com/acme/osgi/Activator.java @@ -32,27 +32,24 @@ import org.osgi.framework.ServiceRegistration; /** * Bootstrap a Server - * - * */ public class Activator implements BundleActivator { private ServiceRegistration _sr; - + /** - * - * @param context + * */ @Override public void start(BundleContext context) throws Exception - { + { //For test purposes, use a random port Server server = new Server(0); server.getConnectors()[0].addLifeCycleListener(new AbstractLifeCycleListener() { - /** + /** * @see org.eclipse.jetty.util.component.AbstractLifeCycle.AbstractLifeCycleListener#lifeCycleStarted(org.eclipse.jetty.util.component.LifeCycle) */ @Override @@ -61,20 +58,18 @@ public class Activator implements BundleActivator System.setProperty("bundle.server.port", String.valueOf(((ServerConnector)event).getLocalPort())); super.lifeCycleStarted(event); } - - - }); ContextHandlerCollection contexts = new ContextHandlerCollection(); server.setHandler(contexts); // server.setDumpAfterStart(true); String[] list = new String[]{ - "org.eclipse.jetty.osgi.boot.OSGiWebInfConfiguration", - "org.eclipse.jetty.webapp.WebXmlConfiguration", - "org.eclipse.jetty.webapp.MetaInfConfiguration", - "org.eclipse.jetty.webapp.FragmentConfiguration", - "org.eclipse.jetty.webapp.JettyWebXmlConfiguration"}; + "org.eclipse.jetty.osgi.boot.OSGiWebInfConfiguration", + "org.eclipse.jetty.webapp.WebXmlConfiguration", + "org.eclipse.jetty.webapp.MetaInfConfiguration", + "org.eclipse.jetty.webapp.FragmentConfiguration", + "org.eclipse.jetty.webapp.JettyWebXmlConfiguration" + }; server.setAttribute("org.eclipse.jetty.webapp.configuration", list); Dictionary serverProps = new Hashtable(); @@ -87,9 +82,8 @@ public class Activator implements BundleActivator /** * Stop the activator. - * - * @see - * org.osgi.framework.BundleActivator#stop(org.osgi.framework.BundleContext) + * + * @see org.osgi.framework.BundleActivator#stop(org.osgi.framework.BundleContext) */ @Override public void stop(BundleContext context) throws Exception diff --git a/jetty-osgi/test-jetty-osgi-webapp/src/main/java/com/acme/osgi/Activator.java b/jetty-osgi/test-jetty-osgi-webapp/src/main/java/com/acme/osgi/Activator.java index 1e6043ee9c3..0acdaad41a8 100644 --- a/jetty-osgi/test-jetty-osgi-webapp/src/main/java/com/acme/osgi/Activator.java +++ b/jetty-osgi/test-jetty-osgi-webapp/src/main/java/com/acme/osgi/Activator.java @@ -35,8 +35,6 @@ import org.osgi.framework.ServiceRegistration; /** * Bootstrap a webapp - * - * */ public class Activator implements BundleActivator { @@ -47,7 +45,7 @@ public class Activator implements BundleActivator public static class TestServlet extends HttpServlet { - /** + /** * @see javax.servlet.http.HttpServlet#doGet(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse) */ @Override @@ -57,17 +55,13 @@ public class Activator implements BundleActivator String mimetype = req.getServletContext().getMimeType("file.gz"); resp.setContentType("text/html"); PrintWriter writer = resp.getWriter(); - writer.write("

    MIMETYPE="+mimetype+"

    "); + writer.write("

    MIMETYPE=" + mimetype + "

    "); writer.flush(); } - } - - /** - * - * @param context + * */ @Override public void start(BundleContext context) throws Exception @@ -76,11 +70,11 @@ public class Activator implements BundleActivator WebAppContext webapp = new WebAppContext(); webapp.addServlet(new ServletHolder(new TestServlet()), "/mime"); Dictionary props = new Hashtable(); - props.put("Jetty-WarResourcePath","webappA"); - props.put("Web-ContextPath","/acme"); + props.put("Jetty-WarResourcePath", "webappA"); + props.put("Web-ContextPath", "/acme"); props.put("managedServerName", "defaultJettyServer"); - _srA = context.registerService(WebAppContext.class.getName(),webapp,props); - + _srA = context.registerService(WebAppContext.class.getName(), webapp, props); + //Create a second webappB as a Service and target it at a custom Server //deployed by another bundle WebAppContext webappB = new WebAppContext(); @@ -93,14 +87,13 @@ public class Activator implements BundleActivator /** * Stop the activator. - * - * @see - * org.osgi.framework.BundleActivator#stop(org.osgi.framework.BundleContext) + * + * @see org.osgi.framework.BundleActivator#stop(org.osgi.framework.BundleContext) */ @Override public void stop(BundleContext context) throws Exception { - _srA.unregister(); + _srA.unregister(); _srB.unregister(); } } diff --git a/jetty-osgi/test-jetty-osgi/pom.xml b/jetty-osgi/test-jetty-osgi/pom.xml index 684aafbf77a..c80aa630dcb 100644 --- a/jetty-osgi/test-jetty-osgi/pom.xml +++ b/jetty-osgi/test-jetty-osgi/pom.xml @@ -34,10 +34,10 @@ - org.ops4j.pax.exam - pax-exam-container-forked - ${pax.exam.version} - test + org.ops4j.pax.exam + pax-exam-container-forked + ${pax.exam.version} + test org.ops4j.pax.swissbox @@ -85,10 +85,10 @@ bndlib 2.4.0 - - org.osgi - org.osgi.core - + + org.osgi + org.osgi.core + @@ -98,10 +98,10 @@ test - org.eclipse.platform - org.eclipse.osgi.services - 3.7.100 - test + org.eclipse.platform + org.eclipse.osgi.services + 3.7.100 + test @@ -161,27 +161,27 @@ test - org.apache.aries.spifly + org.apache.aries.spifly org.apache.aries.spifly.dynamic.bundle 1.2 - test - - - org.apache.felix - org.apache.felix.framework - - + test + + + org.apache.felix + org.apache.felix.framework + + - com.sun.activation + com.sun.activation javax.activation 1.2.0 - test + test - org.glassfish.web - javax.servlet.jsp.jstl - 1.2.2 + org.glassfish.web + javax.servlet.jsp.jstl + 1.2.2 javax.servlet.jsp.jstl @@ -202,19 +202,19 @@ - org.eclipse.jetty.orbit - javax.servlet.jsp.jstl - 1.2.0.v201105211821 - - - org.eclipse.jetty.orbit - javax.servlet - - - org.eclipse.jetty.orbit - javax.servlet.jsp - - + org.eclipse.jetty.orbit + javax.servlet.jsp.jstl + 1.2.0.v201105211821 + + + org.eclipse.jetty.orbit + javax.servlet + + + org.eclipse.jetty.orbit + javax.servlet.jsp + + diff --git a/jetty-osgi/test-jetty-osgi/src/test/java/org/eclipse/jetty/osgi/test/SimpleEchoSocket.java b/jetty-osgi/test-jetty-osgi/src/test/java/org/eclipse/jetty/osgi/test/SimpleEchoSocket.java index 1327cf66667..97318efe639 100644 --- a/jetty-osgi/test-jetty-osgi/src/test/java/org/eclipse/jetty/osgi/test/SimpleEchoSocket.java +++ b/jetty-osgi/test-jetty-osgi/src/test/java/org/eclipse/jetty/osgi/test/SimpleEchoSocket.java @@ -45,7 +45,7 @@ public class SimpleEchoSocket public boolean awaitClose(int duration, TimeUnit unit) throws InterruptedException { - return this.closeLatch.await(duration,unit); + return this.closeLatch.await(duration, unit); } @OnWebSocketClose @@ -62,7 +62,7 @@ public class SimpleEchoSocket try { session.getRemote().sendString("Foo"); - session.close(StatusCode.NORMAL,"I'm done"); + session.close(StatusCode.NORMAL, "I'm done"); } catch (Throwable t) { diff --git a/jetty-osgi/test-jetty-osgi/src/test/java/org/eclipse/jetty/osgi/test/SimpleJavaxWebSocket.java b/jetty-osgi/test-jetty-osgi/src/test/java/org/eclipse/jetty/osgi/test/SimpleJavaxWebSocket.java index 165bed6630c..4dd450d77b7 100644 --- a/jetty-osgi/test-jetty-osgi/src/test/java/org/eclipse/jetty/osgi/test/SimpleJavaxWebSocket.java +++ b/jetty-osgi/test-jetty-osgi/src/test/java/org/eclipse/jetty/osgi/test/SimpleJavaxWebSocket.java @@ -18,10 +18,7 @@ package org.eclipse.jetty.osgi.test; -import static org.junit.Assert.fail; - import java.util.concurrent.CountDownLatch; - import javax.websocket.ClientEndpoint; import javax.websocket.CloseReason; import javax.websocket.OnClose; @@ -30,19 +27,21 @@ import javax.websocket.OnMessage; import javax.websocket.OnOpen; import javax.websocket.Session; +import static org.junit.Assert.fail; + @ClientEndpoint( - subprotocols = { "chat"}) + subprotocols = {"chat"}) public class SimpleJavaxWebSocket { private Session session; public CountDownLatch messageLatch = new CountDownLatch(1); public CountDownLatch closeLatch = new CountDownLatch(1); - + @OnError - public void onError (Throwable t) + public void onError(Throwable t) { //t.printStackTrace(); - fail (t.getMessage()); + fail(t.getMessage()); } @OnClose diff --git a/jetty-osgi/test-jetty-osgi/src/test/java/org/eclipse/jetty/osgi/test/SomeCustomBean.java b/jetty-osgi/test-jetty-osgi/src/test/java/org/eclipse/jetty/osgi/test/SomeCustomBean.java index 7732749ec85..3723141a7a8 100644 --- a/jetty-osgi/test-jetty-osgi/src/test/java/org/eclipse/jetty/osgi/test/SomeCustomBean.java +++ b/jetty-osgi/test-jetty-osgi/src/test/java/org/eclipse/jetty/osgi/test/SomeCustomBean.java @@ -20,10 +20,10 @@ package org.eclipse.jetty.osgi.test; /** * Just a simple bean - * - * @author laeubi * + * @author laeubi */ -public class SomeCustomBean { +public class SomeCustomBean +{ } diff --git a/jetty-osgi/test-jetty-osgi/src/test/java/org/eclipse/jetty/osgi/test/TestJettyOSGiBootContextAsService.java b/jetty-osgi/test-jetty-osgi/src/test/java/org/eclipse/jetty/osgi/test/TestJettyOSGiBootContextAsService.java index 7533105461d..a0ca1da0667 100644 --- a/jetty-osgi/test-jetty-osgi/src/test/java/org/eclipse/jetty/osgi/test/TestJettyOSGiBootContextAsService.java +++ b/jetty-osgi/test-jetty-osgi/src/test/java/org/eclipse/jetty/osgi/test/TestJettyOSGiBootContextAsService.java @@ -19,7 +19,6 @@ package org.eclipse.jetty.osgi.test; import java.util.ArrayList; - import javax.inject.Inject; import org.eclipse.jetty.client.HttpClient; diff --git a/jetty-osgi/test-jetty-osgi/src/test/java/org/eclipse/jetty/osgi/test/TestJettyOSGiBootHTTP2Conscrypt.java b/jetty-osgi/test-jetty-osgi/src/test/java/org/eclipse/jetty/osgi/test/TestJettyOSGiBootHTTP2Conscrypt.java index 9099331f971..26f78507a7d 100644 --- a/jetty-osgi/test-jetty-osgi/src/test/java/org/eclipse/jetty/osgi/test/TestJettyOSGiBootHTTP2Conscrypt.java +++ b/jetty-osgi/test-jetty-osgi/src/test/java/org/eclipse/jetty/osgi/test/TestJettyOSGiBootHTTP2Conscrypt.java @@ -70,9 +70,9 @@ public class TestJettyOSGiBootHTTP2Conscrypt options.addAll(TestOSGiUtil.configureJettyHomeAndPort(true, "jetty-http2.xml")); options.add(CoreOptions.bootDelegationPackages("org.xml.sax", "org.xml.*", "org.w3c.*", "javax.xml.*", "javax.activation.*")); options.add(CoreOptions.systemPackages("com.sun.org.apache.xalan.internal.res", "com.sun.org.apache.xml.internal.utils", - "com.sun.org.apache.xml.internal.utils", "com.sun.org.apache.xpath.internal", - "com.sun.org.apache.xpath.internal.jaxp", "com.sun.org.apache.xpath.internal.objects", - "sun.security", "sun.security.x509", "sun.security.ssl")); + "com.sun.org.apache.xml.internal.utils", "com.sun.org.apache.xpath.internal", + "com.sun.org.apache.xpath.internal.jaxp", "com.sun.org.apache.xpath.internal.objects", + "sun.security", "sun.security.x509", "sun.security.ssl")); options.addAll(http2JettyDependencies()); options.addAll(TestOSGiUtil.coreJettyDependencies()); @@ -97,15 +97,14 @@ public class TestJettyOSGiBootHTTP2Conscrypt res.add(CoreOptions.systemProperty("jetty.sslContext.provider").value("Conscrypt")); res.add(wrappedBundle(mavenBundle().groupId("org.conscrypt").artifactId("conscrypt-openjdk-uber").versionAsInProject()) - .imports("javax.net.ssl,*") - .exports("org.conscrypt;version=" + System.getProperty("conscrypt-version")) - .instructions("Bundle-NativeCode=META-INF/native/libconscrypt_openjdk_jni-linux-x86_64.so") - .start()); + .imports("javax.net.ssl,*") + .exports("org.conscrypt;version=" + System.getProperty("conscrypt-version")) + .instructions("Bundle-NativeCode=META-INF/native/libconscrypt_openjdk_jni-linux-x86_64.so") + .start()); res.add(mavenBundle().groupId("org.eclipse.jetty.osgi").artifactId("jetty-osgi-alpn").versionAsInProject().noStart()); res.add(mavenBundle().groupId("org.eclipse.jetty").artifactId("jetty-alpn-conscrypt-server").versionAsInProject().start()); res.add(mavenBundle().groupId("org.eclipse.jetty").artifactId("jetty-alpn-server").versionAsInProject().start()); - res.add(mavenBundle().groupId("org.eclipse.jetty.http2").artifactId("http2-common").versionAsInProject().start()); res.add(mavenBundle().groupId("org.eclipse.jetty.http2").artifactId("http2-hpack").versionAsInProject().start()); res.add(mavenBundle().groupId("org.eclipse.jetty.http2").artifactId("http2-server").versionAsInProject().start()); diff --git a/jetty-osgi/test-jetty-osgi/src/test/java/org/eclipse/jetty/osgi/test/TestJettyOSGiBootHTTP2JDK9.java b/jetty-osgi/test-jetty-osgi/src/test/java/org/eclipse/jetty/osgi/test/TestJettyOSGiBootHTTP2JDK9.java index 856b2a5b900..f124c887b53 100644 --- a/jetty-osgi/test-jetty-osgi/src/test/java/org/eclipse/jetty/osgi/test/TestJettyOSGiBootHTTP2JDK9.java +++ b/jetty-osgi/test-jetty-osgi/src/test/java/org/eclipse/jetty/osgi/test/TestJettyOSGiBootHTTP2JDK9.java @@ -24,7 +24,6 @@ import java.nio.file.Paths; import java.util.ArrayList; import java.util.List; import java.util.concurrent.Executor; - import javax.inject.Inject; import org.eclipse.jetty.client.HttpClient; @@ -69,8 +68,8 @@ public class TestJettyOSGiBootHTTP2JDK9 options.addAll(TestOSGiUtil.configureJettyHomeAndPort(true, "jetty-http2-jdk9.xml")); options.add(CoreOptions.bootDelegationPackages("org.xml.sax", "org.xml.*", "org.w3c.*", "javax.xml.*", "javax.activation.*")); options.add(CoreOptions.systemPackages("com.sun.org.apache.xalan.internal.res", "com.sun.org.apache.xml.internal.utils", - "com.sun.org.apache.xml.internal.utils", "com.sun.org.apache.xpath.internal", - "com.sun.org.apache.xpath.internal.jaxp", "com.sun.org.apache.xpath.internal.objects")); + "com.sun.org.apache.xml.internal.utils", "com.sun.org.apache.xpath.internal", + "com.sun.org.apache.xpath.internal.jaxp", "com.sun.org.apache.xpath.internal.objects")); options.addAll(http2JettyDependencies()); options.addAll(TestOSGiUtil.coreJettyDependencies()); @@ -92,7 +91,7 @@ public class TestJettyOSGiBootHTTP2JDK9 { List