001/**
002 * Copyright (C) 2006-2021 Talend Inc. - www.talend.com
003 *
004 * Licensed under the Apache License, Version 2.0 (the "License");
005 * you may not use this file except in compliance with the License.
006 * You may obtain a copy of the License at
007 *
008 * http://www.apache.org/licenses/LICENSE-2.0
009 *
010 * Unless required by applicable law or agreed to in writing, software
011 * distributed under the License is distributed on an "AS IS" BASIS,
012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
013 * See the License for the specific language governing permissions and
014 * limitations under the License.
015 */
016package org.talend.sdk.component.junit.http.internal.impl;
017
018import org.talend.sdk.component.junit.http.api.HttpApiHandler;
019
020import io.netty.channel.ChannelHandlerAdapter;
021import io.netty.channel.ChannelInitializer;
022import io.netty.channel.ChannelPipeline;
023import io.netty.channel.socket.SocketChannel;
024import io.netty.handler.codec.http.HttpContentCompressor;
025import io.netty.handler.codec.http.HttpContentDecompressor;
026import io.netty.handler.codec.http.HttpObjectAggregator;
027import io.netty.handler.codec.http.HttpRequestDecoder;
028import io.netty.handler.codec.http.HttpResponseEncoder;
029import io.netty.handler.logging.LogLevel;
030import io.netty.handler.logging.LoggingHandler;
031import io.netty.handler.stream.ChunkedWriteHandler;
032
033import lombok.AllArgsConstructor;
034
035@AllArgsConstructor
036public class ProxyInitializer extends ChannelInitializer<SocketChannel> {
037
038    private final HttpApiHandler api;
039
040    @Override
041    protected void initChannel(final SocketChannel channel) {
042        final ChannelPipeline pipeline = channel.pipeline();
043        final ChannelHandlerAdapter handler;
044        final boolean degzip;
045        if (Handlers.isActive("capture")) {
046            degzip = true;
047            handler = new DefaultResponseLocatorCapturingHandler(api);
048        } else if (Handlers.isActive("passthrough")) {
049            degzip = false;
050            handler = new PassthroughHandler(api);
051        } else {
052            degzip = true;
053            handler = new ServingProxyHandler(api);
054        }
055        pipeline
056                .addLast("logging", new LoggingHandler(LogLevel.valueOf(api.getLogLevel())))
057                .addLast("http-decoder", new HttpRequestDecoder());
058        if (degzip) {
059            pipeline.addLast("gzip-decompressor", new HttpContentDecompressor());
060        }
061        pipeline
062                .addLast("http-encoder", new HttpResponseEncoder())
063                .addLast("gzip-compressor", new HttpContentCompressor())
064                .addLast("aggregator", new HttpObjectAggregator(Integer.MAX_VALUE))
065                .addLast("chunked-writer", new ChunkedWriteHandler())
066                .addLast("talend-junit-api-server", handler);
067    }
068}