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