1 /*
2  * Copyright 2008-2019 by Emeric Vernat
3  *
4  *     This file is part of Java Melody.
5  *
6  * Licensed under the Apache License, Version 2.0 (the "License");
7  * you may not use this file except in compliance with the License.
8  * You may obtain a copy of the License at
9  *
10  *     http://www.apache.org/licenses/LICENSE-2.0
11  *
12  * Unless required by applicable law or agreed to in writing, software
13  * distributed under the License is distributed on an "AS IS" BASIS,
14  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15  * See the License for the specific language governing permissions and
16  * limitations under the License.
17  */

18 package net.bull.javamelody;
19
20 import java.io.IOException;
21
22 import org.springframework.http.HttpRequest;
23 import org.springframework.http.client.ClientHttpRequestExecution;
24 import org.springframework.http.client.ClientHttpRequestInterceptor;
25 import org.springframework.http.client.ClientHttpResponse;
26 import org.springframework.web.client.RestTemplate;
27
28 import net.bull.javamelody.internal.model.Counter;
29
30 /**
31  * Interceptor for Spring {@link RestTemplate}.
32  * @author Emeric Vernat
33  */

34 public class SpringRestTemplateInterceptor implements ClientHttpRequestInterceptor {
35     static final ClientHttpRequestInterceptor SINGLETON = new SpringRestTemplateInterceptor();
36
37     private static final Counter SPRING_COUNTER = MonitoringProxy.getSpringCounter();
38
39     /** {@inheritDoc} */
40     @Override
41     public ClientHttpResponse intercept(HttpRequest httpRequest, byte[] body,
42             ClientHttpRequestExecution execution) throws IOException {
43         if (!SPRING_COUNTER.isDisplayed()) {
44             return execution.execute(httpRequest, body);
45         }
46         // nom identifiant la requête
47         final String requestName = getRequestName(httpRequest);
48
49         boolean systemError = false;
50         try {
51             SPRING_COUNTER.bindContextIncludingCpu(requestName);
52             // we could add in httpRequest.getHeaders() a javamelody id
53             // to link, in the collector server, the callers in this jvm to the callees in the jvm called
54             return execution.execute(httpRequest, body);
55         } catch (final IOException | Error e) {
56             // IOException - in case of I/O errors
57             systemError = true;
58             throw e;
59         } finally {
60             // on enregistre la requête dans les statistiques
61             SPRING_COUNTER.addRequestForCurrentContext(systemError);
62         }
63     }
64
65     protected String getRequestName(HttpRequest httpRequest) {
66         String uri = httpRequest.getURI().toString();
67         final int index = uri.indexOf('?');
68         if (index != -1) {
69             uri = uri.substring(0, index);
70         }
71         return uri + ' ' + httpRequest.getMethod();
72     }
73 }
74