001/*
002 * (C) Copyright 2019 Nuxeo SA (http://nuxeo.com/) and others.
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 *
016 * Contributors:
017 *     bdelbosc
018 */
019package org.nuxeo.ecm.core.management.jtajca.internal;
020
021import java.io.IOException;
022import java.security.Principal;
023import java.util.HashMap;
024import java.util.Map;
025
026import javax.servlet.FilterChain;
027import javax.servlet.FilterConfig;
028import javax.servlet.ServletException;
029import javax.servlet.http.HttpFilter;
030import javax.servlet.http.HttpServletRequest;
031import javax.servlet.http.HttpServletResponse;
032import javax.servlet.http.HttpSession;
033
034import io.opencensus.trace.AttributeValue;
035import io.opencensus.trace.BlankSpan;
036import io.opencensus.trace.Span;
037import io.opencensus.trace.Tracing;
038
039/**
040 * Add some tags to span created by OcHttpServletFilter
041 */
042public class TracingWebFilter extends HttpFilter {
043
044    protected FilterConfig config;
045
046    protected static final String USER_KEY = "http.user";
047
048    protected static final String THREAD_KEY = "http.thread";
049
050    protected static final String SESSION_KEY = "http.session";
051
052    @Override
053    public void init(FilterConfig filterConfig) {
054        config = filterConfig;
055    }
056
057    @Override
058    protected void doFilter(HttpServletRequest req, HttpServletResponse res, FilterChain chain)
059            throws IOException, ServletException {
060        Span span = Tracing.getTracer().getCurrentSpan();
061        addTags(span, req);
062        chain.doFilter(req, res);
063    }
064
065    protected void addTags(Span span, HttpServletRequest httpRequest) {
066        if (span instanceof BlankSpan) {
067            return;
068        }
069        Map<String, AttributeValue> map = new HashMap<>();
070        map.put(THREAD_KEY, AttributeValue.stringAttributeValue(Thread.currentThread().getName()));
071        Principal principal = httpRequest.getUserPrincipal();
072        if (principal != null) {
073            map.put(USER_KEY, AttributeValue.stringAttributeValue(principal.getName()));
074        }
075        HttpSession session = httpRequest.getSession(false);
076        if (session != null) {
077            map.put(SESSION_KEY, AttributeValue.stringAttributeValue(session.getId()));
078        }
079        span.putAttributes(map);
080    }
081}