View Javadoc
1   /*
2    * Copyright 2016 The Lannister Project
3    * 
4    * Licensed under the Apache License, Version 2.0 (the "License");
5    * you may not use this file except in compliance with the License.
6    * You may obtain a copy of the License at
7    * 
8    *     http://www.apache.org/licenses/LICENSE-2.0
9    * 
10   * Unless required by applicable law or agreed to in writing, software
11   * distributed under the License is distributed on an "AS IS" BASIS,
12   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13   * See the License for the specific language governing permissions and
14   * limitations under the License.
15   */
16  
17  package net.anyflow.lannister.http;
18  
19  import org.slf4j.Logger;
20  import org.slf4j.LoggerFactory;
21  
22  import io.netty.channel.ChannelHandlerContext;
23  import io.netty.channel.SimpleChannelInboundHandler;
24  import io.netty.handler.codec.http.FullHttpResponse;
25  
26  public class HttpClientHandler extends SimpleChannelInboundHandler<FullHttpResponse> {
27  
28  	private static final Logger logger = LoggerFactory.getLogger(HttpClientHandler.class);
29  
30  	private final MessageReceiver receiver;
31  	private final HttpRequest request;
32  	private HttpResponse response;
33  
34  	public HttpClientHandler(MessageReceiver receiver, HttpRequest request) {
35  		this.receiver = receiver;
36  		this.request = request;
37  	}
38  
39  	public HttpResponse httpResponse() {
40  		return response;
41  	}
42  
43  	@Override
44  	protected void channelRead0(ChannelHandlerContext ctx, FullHttpResponse msg) throws Exception {
45  		if (!ctx.channel().isActive()) { return; }
46  
47  		response = HttpResponse.createFrom(msg, ctx.channel());
48  
49  		if (logger.isDebugEnabled()) {
50  			logger.debug(response.toString());
51  		}
52  
53  		if (receiver != null) {
54  			receiver.messageReceived(request, response);
55  		}
56  
57  		ctx.channel().close();
58  	}
59  
60  	@Override
61  	public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
62  		logger.error(cause.getMessage(), cause);
63  		ctx.channel().close();
64  	}
65  }