001/** 002 * Copyright (C) 2006-2018 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 static java.util.Optional.ofNullable; 019import static lombok.AccessLevel.PRIVATE; 020 021import java.io.File; 022 023import io.netty.buffer.Unpooled; 024import io.netty.channel.Channel; 025import io.netty.channel.ChannelHandlerContext; 026import io.netty.handler.codec.http.DefaultFullHttpResponse; 027import io.netty.handler.codec.http.FullHttpResponse; 028import io.netty.handler.codec.http.HttpHeaderNames; 029import io.netty.handler.codec.http.HttpResponseStatus; 030import io.netty.handler.codec.http.HttpVersion; 031import io.netty.util.AttributeKey; 032import io.netty.util.CharsetUtil; 033 034import lombok.NoArgsConstructor; 035 036@NoArgsConstructor(access = PRIVATE) 037public class Handlers { 038 039 static final AttributeKey<String> BASE = AttributeKey.newInstance(Handlers.class.getName() + "#BASE"); 040 041 static void closeOnFlush(final Channel ch) { 042 if (ch.isActive()) { 043 ch.writeAndFlush(Unpooled.EMPTY_BUFFER); 044 } 045 } 046 047 static void sendError(final ChannelHandlerContext ctx, final HttpResponseStatus status) { 048 final FullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, status, 049 Unpooled.copiedBuffer("Failure: " + status.toString() + "\r\n", CharsetUtil.UTF_8)); 050 response.headers().set(HttpHeaderNames.CONTENT_TYPE, "text/plain; charset=UTF-8"); 051 response.headers().set("X-Talend-Proxy-JUnit", "default-response"); 052 ctx.writeAndFlush(response); 053 } 054 055 public static boolean isActive(final String handler) { 056 return "capture".equals(handler) ? getBaseCapture() != null 057 : Boolean.parseBoolean(System.getProperty("talend.junit.http." + handler)); 058 } 059 060 // yes, it could be in the API but to avoid to keep it and pass tests in capture mode 061 // we hide it this way for now 062 public static String getBaseCapture() { 063 return ofNullable(System.getProperty("talend.junit.http.capture")).map(value -> { 064 if ("true".equalsIgnoreCase(value)) { // try to guess 065 final File file = new File("src/test/resources"); 066 if (file.isDirectory()) { 067 return file.getAbsolutePath(); 068 } 069 } 070 return value; 071 }).orElse(null); 072 } 073}