View Javadoc
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  
28  package org.apache.hc.core5.http.examples;
29  
30  import java.io.IOException;
31  import java.util.concurrent.TimeUnit;
32  
33  import org.apache.hc.core5.http.ClassicHttpResponse;
34  import org.apache.hc.core5.http.ContentType;
35  import org.apache.hc.core5.http.HttpException;
36  import org.apache.hc.core5.http.HttpStatus;
37  import org.apache.hc.core5.http.impl.bootstrap.HttpServer;
38  import org.apache.hc.core5.http.impl.bootstrap.ServerBootstrap;
39  import org.apache.hc.core5.http.impl.bootstrap.StandardFilter;
40  import org.apache.hc.core5.http.io.HttpFilterChain;
41  import org.apache.hc.core5.http.io.SocketConfig;
42  import org.apache.hc.core5.http.io.entity.StringEntity;
43  import org.apache.hc.core5.http.io.support.AbstractHttpServerAuthFilter;
44  import org.apache.hc.core5.http.message.BasicClassicHttpResponse;
45  import org.apache.hc.core5.http.protocol.HttpContext;
46  import org.apache.hc.core5.io.CloseMode;
47  import org.apache.hc.core5.net.URIAuthority;
48  import org.apache.hc.core5.util.TimeValue;
49  
50  /**
51   * Example of using classic I/O request filters with an embedded HTTP/1.1 server.
52   */
53  public class ClassicServerFilterExample {
54  
55      public static void main(final String[] args) throws Exception {
56          int port = 8080;
57          if (args.length >= 1) {
58              port = Integer.parseInt(args[0]);
59          }
60          final SocketConfig socketConfig = SocketConfig.custom()
61                  .setSoTimeout(15, TimeUnit.SECONDS)
62                  .setTcpNoDelay(true)
63                  .build();
64  
65          final HttpServer server = ServerBootstrap.bootstrap()
66                  .setListenerPort(port)
67                  .setSocketConfig(socketConfig)
68  
69                  // Replace standard expect-continue handling with a custom auth filter
70  
71                  .replaceFilter(StandardFilter.EXPECT_CONTINUE.name(), new AbstractHttpServerAuthFilter<String>(false) {
72  
73                      @Override
74                      protected String parseChallengeResponse(
75                              final String authorizationValue, final HttpContext context) throws HttpException {
76                          return authorizationValue;
77                      }
78  
79                      @Override
80                      protected boolean authenticate(
81                              final String challengeResponse,
82                              final URIAuthority authority,
83                              final String requestUri,
84                              final HttpContext context) {
85                          return "let me pass".equals(challengeResponse);
86                      }
87  
88                      @Override
89                      protected String generateChallenge(
90                              final String challengeResponse,
91                              final URIAuthority authority,
92                              final String requestUri,
93                              final HttpContext context) {
94                          return "who goes there?";
95                      }
96  
97                  })
98  
99                  // Add a custom request filter at the beginning of the processing pipeline
100 
101                 .addFilterFirst("my-filter", (request, responseTrigger, context, chain) -> {
102                     if (request.getRequestUri().equals("/back-door")) {
103                         final ClassicHttpResponse response = new BasicClassicHttpResponse(HttpStatus.SC_OK);
104                         response.setEntity(new StringEntity("Welcome", ContentType.TEXT_PLAIN));
105                         responseTrigger.submitResponse(response);
106                     } else {
107                         chain.proceed(request, new HttpFilterChain.ResponseTrigger() {
108 
109                             @Override
110                             public void sendInformation(final ClassicHttpResponse response) throws HttpException, IOException {
111                                 responseTrigger.sendInformation(response);
112                             }
113 
114                             @Override
115                             public void submitResponse(final ClassicHttpResponse response) throws HttpException, IOException {
116                                 response.addHeader("X-Filter", "My-Filter");
117                                 responseTrigger.submitResponse(response);
118                             }
119 
120                         }, context);
121                     }
122                 })
123 
124                 // Application request handler
125 
126                 .register("*", (request, response, context) -> {
127                     // do something useful
128                     response.setCode(HttpStatus.SC_OK);
129                     response.setEntity(new StringEntity("Hello"));
130                 })
131                 .create();
132 
133         server.start();
134         Runtime.getRuntime().addShutdownHook(new Thread(() -> server.close(CloseMode.GRACEFUL)));
135         System.out.println("Listening on port " + port);
136 
137         server.awaitTermination(TimeValue.MAX_VALUE);
138 
139     }
140 
141 }