You are viewing a plain text version of this content. The canonical link for it is here.
Posted to dev@hc.apache.org by GitBox <gi...@apache.org> on 2019/05/27 13:22:12 UTC

[GitHub] [httpcomponents-core] ok2c commented on a change in pull request #128: Added Greeting Example

ok2c commented on a change in pull request #128: Added Greeting Example
URL: https://github.com/apache/httpcomponents-core/pull/128#discussion_r287787021
 
 

 ##########
 File path: httpcore5-h2/src/test/java/org/apache/hc/core5/http2/examples/Http2GreetingServer.java
 ##########
 @@ -0,0 +1,181 @@
+package org.apache.hc.core5.http2.examples;
+
+import org.apache.hc.core5.function.Supplier;
+import org.apache.hc.core5.http.*;
+import org.apache.hc.core5.http.impl.bootstrap.HttpAsyncServer;
+import org.apache.hc.core5.http.io.entity.InputStreamEntity;
+import org.apache.hc.core5.http.message.BasicHttpResponse;
+import org.apache.hc.core5.http.nio.*;
+import org.apache.hc.core5.http.nio.entity.NoopEntityConsumer;
+import org.apache.hc.core5.http.nio.entity.StringAsyncEntityProducer;
+import org.apache.hc.core5.http.nio.support.AbstractServerExchangeHandler;
+import org.apache.hc.core5.http.nio.support.classic.AbstractClassicEntityConsumer;
+import org.apache.hc.core5.http.protocol.HttpContext;
+import org.apache.hc.core5.http.protocol.HttpCoreContext;
+import org.apache.hc.core5.http2.HttpVersionPolicy;
+import org.apache.hc.core5.http2.config.H2Config;
+import org.apache.hc.core5.http2.impl.nio.bootstrap.H2ServerBootstrap;
+import org.apache.hc.core5.io.CloseMode;
+import org.apache.hc.core5.net.URLEncodedUtils;
+import org.apache.hc.core5.reactor.IOReactorConfig;
+import org.apache.hc.core5.reactor.ListenerEndpoint;
+import org.apache.hc.core5.util.TimeValue;
+
+import java.io.*;
+import java.net.InetSocketAddress;
+import java.nio.charset.Charset;
+import java.util.Date;
+import java.util.List;
+import java.util.concurrent.ExecutionException;
+import java.util.concurrent.Executors;
+import java.util.concurrent.Future;
+
+/**
+ * Example HTTP2 server that reads an entity body and responds back with a greeting.
+ *
+ * <pre>
+ * {@code
+ * $ curl  -id name=bob localhost:8080
+ * HTTP/1.1 200 OK
+ * Date: Sat, 25 May 2019 03:44:49 GMT
+ * Server: Apache-HttpCore/5.0-beta8-SNAPSHOT (Java/1.8.0_202)
+ * Transfer-Encoding: chunked
+ * Content-Type: text/plain; charset=ISO-8859-1
+ *
+ * Hello bob
+ * }</pre>
+ * <p>
+ * This examples uses a {@link AbstractServerExchangeHandler} for the basic Request/Response cycle (consuming requests
+ * and producing responses) and either a {@link NoopEntityConsumer} or {@link InputStreamEntity} depending if the
+ * request has a body/content or not.
+ * </p>
+ * Further improvements left as an exercise for the reader:
+ * <ul>
+ * <li>TLS</li>
+ * <li>Handle of multipart requests</li>
+ * </ul>
+ */
+public class Http2GreetingServer {
+    public static void main(String[] args) throws ExecutionException, InterruptedException {
+        int port = 8080;
+        if (args.length >= 1) {
+            port = Integer.parseInt(args[0]);
+        }
+
+        final HttpAsyncServer server = H2ServerBootstrap.bootstrap()
+                .setH2Config(H2Config.DEFAULT)
+                .setIOReactorConfig(IOReactorConfig.DEFAULT)
+                .setVersionPolicy(HttpVersionPolicy.NEGOTIATE) // fallback to HTTP/1 as needed
+
+                // wildcard path matcher:
+                .register("*", new Supplier<AsyncServerExchangeHandler>() {
+                    @Override
+                    public AsyncServerExchangeHandler get() {
+                        return new CustomServerExchangeHandler();
+                    }
+                })
+                .create();
+
+
+        Runtime.getRuntime().addShutdownHook(new Thread(new Runnable() {
+            @Override
+            public void run() {
+                System.out.println("HTTP server shutting down");
+                server.close(CloseMode.GRACEFUL);
+            }
+        }));
+
+        server.start();
+        final Future<ListenerEndpoint> future = server.listen(new InetSocketAddress(port));
+        final ListenerEndpoint listenerEndpoint = future.get();
+        System.out.println("Listening on " + listenerEndpoint.getAddress());
+        server.awaitShutdown(TimeValue.ofDays(Long.MAX_VALUE));
+    }
+
+    static class CustomServerExchangeHandler extends AbstractServerExchangeHandler<Message<HttpRequest, HttpEntity>> {
+
+
+        @Override
+        protected AsyncRequestConsumer<Message<HttpRequest, HttpEntity>> supplyConsumer(HttpRequest request,
+                                                                                        final EntityDetails
+                                                                                                entityDetails,
+                                                                                        HttpContext context) {
+            AsyncEntityConsumer entityConsumer = new NoopEntityConsumer();
+
+            if (entityDetails != null) {
+                entityConsumer = new AbstractClassicEntityConsumer<HttpEntity>(1024 * 64, Executors.newCachedThreadPool()) {
+                    @Override
+                    protected HttpEntity consumeData(ContentType contentType, InputStream inputStream) {
+                        return new InputStreamEntity(inputStream, entityDetails.getContentLength(), contentType);
+                    }
+                };
+            }
+            return new BasicRequestConsumer<HttpEntity>(entityConsumer);
+
+        }
+
+        @Override
+        protected void handle(Message<HttpRequest, HttpEntity> requestMessage,
+                              AsyncServerRequestHandler.ResponseTrigger responseTrigger,
+                              HttpContext context) throws HttpException, IOException {
+
+            try {
+                final HttpCoreContext coreContext = HttpCoreContext.adapt(context);
+                final EndpointDetails endpoint = coreContext.getEndpointDetails();
+                final HttpRequest req = requestMessage.getHead();
+                final HttpEntity httpEntity = requestMessage.getBody();
+
+                // generic success response:
+                HttpResponse resp = new BasicHttpResponse(200);
+
+                // recording the request
+                System.out.println(String.format("[%s] %s %s %s", new Date(),
+                        endpoint.getRemoteAddress().toString(),
+                        req.getMethod(),
+                        req.getPath()));
+
+                // Request without an entity - GET/HEAD/DELETE
+                if (httpEntity == null) {
+                    responseTrigger.submitResponse(new BasicResponseProducer(resp), context);
+                    return;
+                }
+
+                // Request with an entity - POST/PUT
+                final ContentType entityContentType = ContentType.parse(httpEntity.getContentType());
+                String greeting = "Hello stranger\n";
+
+                if (entityContentType.getMimeType().equals(ContentType.APPLICATION_FORM_URLENCODED.getMimeType())) {
+
+                    Charset charset = ContentType.APPLICATION_FORM_URLENCODED.getCharset();
+                    if (entityContentType.getCharset() != null) {
+                        charset = entityContentType.getCharset();
+                    }
+
+                    StringBuilder contents = new StringBuilder();
+                    try (Reader reader = new BufferedReader(
+                            new InputStreamReader(httpEntity.getContent(), charset))) {
+                        int c;
+                        while ((c = reader.read()) != -1) {
+                            contents.append((char) c);
+                        }
+
+                    }
+
+                    // decoding the form entity into key/value pairs:
+                    List<NameValuePair> args = URLEncodedUtils.parse(contents.toString(),
+                            ContentType.APPLICATION_FORM_URLENCODED.getCharset());
+
+                    // composing greeting:
+                    greeting = String.format("Hello %s\n", args.get(0).getValue());
+                }
+
+                responseTrigger.submitResponse(new BasicResponseProducer(resp,
+                        new StringAsyncEntityProducer(greeting, ContentType.TEXT_PLAIN)), context);
+            } catch (Exception e) {
+                e.printStackTrace();
 
 Review comment:
   @rferreira The exception handling code would also need to be reworked to something more presentable. Spitting exception stack traces to the console is not something we should be doing or recommending.

----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
 
For queries about this service, please contact Infrastructure at:
users@infra.apache.org


With regards,
Apache Git Services

---------------------------------------------------------------------
To unsubscribe, e-mail: dev-unsubscribe@hc.apache.org
For additional commands, e-mail: dev-help@hc.apache.org