001/** 002 * Copyright (C) 2006-2020 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.server.mdc; 017 018import static java.util.Optional.ofNullable; 019 020import java.io.IOException; 021import java.net.InetAddress; 022import java.net.UnknownHostException; 023import java.util.HashMap; 024import java.util.Map; 025 026import javax.enterprise.inject.Vetoed; 027import javax.servlet.Filter; 028import javax.servlet.FilterChain; 029import javax.servlet.FilterConfig; 030import javax.servlet.ServletException; 031import javax.servlet.ServletRequest; 032import javax.servlet.ServletResponse; 033import javax.servlet.http.HttpServletRequest; 034 035import org.apache.logging.log4j.ThreadContext; 036 037@Vetoed 038public class MdcRequestBinder implements Filter { 039 040 private String hostname; 041 042 @Override 043 public void init(final FilterConfig filterConfig) { 044 try { 045 hostname = InetAddress.getLocalHost().getHostName(); 046 } catch (UnknownHostException e) { 047 hostname = ofNullable(System.getenv("HOST")).orElse("unknown"); 048 } 049 } 050 051 @Override 052 public void doFilter(final ServletRequest request, final ServletResponse response, final FilterChain chain) 053 throws IOException, ServletException { 054 if (HttpServletRequest.class.isInstance(request)) { 055 ThreadContext.putAll(createContext(HttpServletRequest.class.cast(request))); 056 } 057 chain.doFilter(request, response); 058 } 059 060 private Map<String, String> createContext(final HttpServletRequest req) { 061 final Map<String, String> map = new HashMap<>(); 062 ofNullable(req.getHeader("X-B3-TraceId")).ifPresent(v -> map.put("spanId", v)); 063 ofNullable(req.getHeader("X-B3-SpanId")).ifPresent(v -> map.put("traceId", v)); 064 map.put("hostname", hostname); 065 return map; 066 } 067}