|
| 1 | +/* |
| 2 | + * ==================================================================== |
| 3 | + * Licensed to the Apache Software Foundation (ASF) under one |
| 4 | + * or more contributor license agreements. See the NOTICE file |
| 5 | + * distributed with this work for additional information |
| 6 | + * regarding copyright ownership. The ASF licenses this file |
| 7 | + * to you under the Apache License, Version 2.0 (the |
| 8 | + * "License"); you may not use this file except in compliance |
| 9 | + * with the License. You may obtain a copy of the License at |
| 10 | + * |
| 11 | + * http://www.apache.org/licenses/LICENSE-2.0 |
| 12 | + * |
| 13 | + * Unless required by applicable law or agreed to in writing, |
| 14 | + * software distributed under the License is distributed on an |
| 15 | + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY |
| 16 | + * KIND, either express or implied. See the License for the |
| 17 | + * specific language governing permissions and limitations |
| 18 | + * under the License. |
| 19 | + * ==================================================================== |
| 20 | + * |
| 21 | + * This software consists of voluntary contributions made by many |
| 22 | + * individuals on behalf of the Apache Software Foundation. For more |
| 23 | + * information on the Apache Software Foundation, please see |
| 24 | + * <http://www.apache.org/>. |
| 25 | + * |
| 26 | + */ |
| 27 | +package org.apache.hc.core5.http2.examples; |
| 28 | + |
| 29 | +import java.io.BufferedWriter; |
| 30 | +import java.io.OutputStreamWriter; |
| 31 | +import java.net.InetSocketAddress; |
| 32 | +import java.net.URISyntaxException; |
| 33 | +import java.nio.charset.StandardCharsets; |
| 34 | +import java.util.List; |
| 35 | +import java.util.Map; |
| 36 | +import java.util.concurrent.ExecutorService; |
| 37 | +import java.util.concurrent.Executors; |
| 38 | +import java.util.concurrent.Future; |
| 39 | +import java.util.concurrent.TimeUnit; |
| 40 | +import java.util.stream.Collectors; |
| 41 | + |
| 42 | +import org.apache.hc.core5.annotation.Experimental; |
| 43 | +import org.apache.hc.core5.concurrent.DefaultThreadFactory; |
| 44 | +import org.apache.hc.core5.http.ContentType; |
| 45 | +import org.apache.hc.core5.http.Header; |
| 46 | +import org.apache.hc.core5.http.HttpConnection; |
| 47 | +import org.apache.hc.core5.http.HttpEntity; |
| 48 | +import org.apache.hc.core5.http.NameValuePair; |
| 49 | +import org.apache.hc.core5.http.ProtocolException; |
| 50 | +import org.apache.hc.core5.http.URIScheme; |
| 51 | +import org.apache.hc.core5.http.impl.bootstrap.HttpAsyncServer; |
| 52 | +import org.apache.hc.core5.http.impl.routing.RequestRouter; |
| 53 | +import org.apache.hc.core5.http.io.HttpRequestHandler; |
| 54 | +import org.apache.hc.core5.http.io.entity.EntityTemplate; |
| 55 | +import org.apache.hc.core5.http.io.entity.EntityUtils; |
| 56 | +import org.apache.hc.core5.http.nio.support.classic.ClassicToAsyncServerExchangeHandler; |
| 57 | +import org.apache.hc.core5.http2.HttpVersionPolicy; |
| 58 | +import org.apache.hc.core5.http2.frame.RawFrame; |
| 59 | +import org.apache.hc.core5.http2.impl.nio.H2StreamListener; |
| 60 | +import org.apache.hc.core5.http2.impl.nio.bootstrap.H2ServerBootstrap; |
| 61 | +import org.apache.hc.core5.io.CloseMode; |
| 62 | +import org.apache.hc.core5.net.URIBuilder; |
| 63 | +import org.apache.hc.core5.reactor.IOReactorConfig; |
| 64 | +import org.apache.hc.core5.reactor.ListenerEndpoint; |
| 65 | +import org.apache.hc.core5.util.TimeValue; |
| 66 | + |
| 67 | +/** |
| 68 | + * Example of asynchronous embedded HTTP/2 server with a classic I/O API compatibility |
| 69 | + * bridge that enables the use of standard {@link java.io.InputStream} / {@link java.io.OutputStream} |
| 70 | + * based data consumers / producers. |
| 71 | + * <p>> |
| 72 | + * Execution of individual message exchanges is delegated to an {@link java.util.concurrent.Executor} |
| 73 | + * backed by a pool of threads. |
| 74 | + */ |
| 75 | +@Experimental |
| 76 | +public class ClassicH2ServerExample { |
| 77 | + |
| 78 | + public static void main(final String[] args) throws Exception { |
| 79 | + int port = 8080; |
| 80 | + if (args.length >= 1) { |
| 81 | + port = Integer.parseInt(args[0]); |
| 82 | + } |
| 83 | + |
| 84 | + final IOReactorConfig config = IOReactorConfig.custom() |
| 85 | + .setSoTimeout(15, TimeUnit.SECONDS) |
| 86 | + .setTcpNoDelay(true) |
| 87 | + .build(); |
| 88 | + |
| 89 | + final ExecutorService executorService = Executors.newFixedThreadPool( |
| 90 | + 25, |
| 91 | + new DefaultThreadFactory("worker-pool", true)); |
| 92 | + |
| 93 | + final HttpRequestHandler requestHandler = (request, response, context) -> { |
| 94 | + try { |
| 95 | + final HttpEntity requestEntity = request.getEntity(); |
| 96 | + if (requestEntity != null) { |
| 97 | + EntityUtils.consume(requestEntity); |
| 98 | + } |
| 99 | + final Map<String, String> queryParams = new URIBuilder(request.getUri()).getQueryParams().stream() |
| 100 | + .collect(Collectors.toMap( |
| 101 | + NameValuePair::getName, |
| 102 | + NameValuePair::getValue, |
| 103 | + (s, s2) -> s)); |
| 104 | + final int n = Integer.parseInt(queryParams.getOrDefault("n", "10")); |
| 105 | + final String p = queryParams.getOrDefault("pattern", "huh?"); |
| 106 | + final HttpEntity responseEntity = new EntityTemplate( |
| 107 | + ContentType.TEXT_PLAIN.withCharset(StandardCharsets.UTF_8), |
| 108 | + outputStream -> { |
| 109 | + try (BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(outputStream, StandardCharsets.UTF_8))) { |
| 110 | + for (int i = 0; i < n; i++) { |
| 111 | + writer.write(p); |
| 112 | + writer.write("\n"); |
| 113 | + } |
| 114 | + } |
| 115 | + }); |
| 116 | + response.setEntity(responseEntity); |
| 117 | + } catch (final URISyntaxException ex) { |
| 118 | + throw new ProtocolException("Invalid request URI", ex); |
| 119 | + } catch (final NumberFormatException ex) { |
| 120 | + throw new ProtocolException("Invalid query parameter", ex); |
| 121 | + } |
| 122 | + }; |
| 123 | + |
| 124 | + final RequestRouter<HttpRequestHandler> requestRouter = RequestRouter.<HttpRequestHandler>builder() |
| 125 | + .resolveAuthority(RequestRouter.LOCAL_AUTHORITY_RESOLVER) |
| 126 | + .addRoute(RequestRouter.LOCAL_AUTHORITY, "*", requestHandler) |
| 127 | + .build(); |
| 128 | + |
| 129 | + final HttpAsyncServer server = H2ServerBootstrap.bootstrap() |
| 130 | + .setIOReactorConfig(config) |
| 131 | + .setVersionPolicy(HttpVersionPolicy.FORCE_HTTP_2) |
| 132 | + .setStreamListener(new H2StreamListener() { |
| 133 | + |
| 134 | + @Override |
| 135 | + public void onHeaderInput(final HttpConnection connection, final int streamId, final List<? extends Header> headers) { |
| 136 | + for (int i = 0; i < headers.size(); i++) { |
| 137 | + System.out.println(connection.getRemoteAddress() + " (" + streamId + ") << " + headers.get(i)); |
| 138 | + } |
| 139 | + } |
| 140 | + |
| 141 | + @Override |
| 142 | + public void onHeaderOutput(final HttpConnection connection, final int streamId, final List<? extends Header> headers) { |
| 143 | + for (int i = 0; i < headers.size(); i++) { |
| 144 | + System.out.println(connection.getRemoteAddress() + " (" + streamId + ") >> " + headers.get(i)); |
| 145 | + } |
| 146 | + } |
| 147 | + |
| 148 | + @Override |
| 149 | + public void onFrameInput(final HttpConnection connection, final int streamId, final RawFrame frame) { |
| 150 | + } |
| 151 | + |
| 152 | + @Override |
| 153 | + public void onFrameOutput(final HttpConnection connection, final int streamId, final RawFrame frame) { |
| 154 | + } |
| 155 | + |
| 156 | + @Override |
| 157 | + public void onInputFlowControl(final HttpConnection connection, final int streamId, final int delta, final int actualSize) { |
| 158 | + } |
| 159 | + |
| 160 | + @Override |
| 161 | + public void onOutputFlowControl(final HttpConnection connection, final int streamId, final int delta, final int actualSize) { |
| 162 | + } |
| 163 | + |
| 164 | + }) |
| 165 | + .setRequestRouter((request, context) -> { |
| 166 | + final HttpRequestHandler handler = requestRouter.resolve(request, context); |
| 167 | + return () -> new ClassicToAsyncServerExchangeHandler( |
| 168 | + executorService, |
| 169 | + handler, |
| 170 | + e -> e.printStackTrace(System.out)); |
| 171 | + }) |
| 172 | + .setExceptionCallback(e -> e.printStackTrace(System.out)) |
| 173 | + .create(); |
| 174 | + |
| 175 | + Runtime.getRuntime().addShutdownHook(new Thread(() -> { |
| 176 | + System.out.println("HTTP server shutting down"); |
| 177 | + server.close(CloseMode.GRACEFUL); |
| 178 | + executorService.shutdownNow(); |
| 179 | + })); |
| 180 | + |
| 181 | + server.start(); |
| 182 | + final Future<ListenerEndpoint> future = server.listen(new InetSocketAddress(port), URIScheme.HTTP); |
| 183 | + final ListenerEndpoint listenerEndpoint = future.get(); |
| 184 | + System.out.print("Listening on " + listenerEndpoint.getAddress()); |
| 185 | + server.awaitShutdown(TimeValue.ofDays(Long.MAX_VALUE)); |
| 186 | + } |
| 187 | + |
| 188 | +} |
0 commit comments