This is an automated email from the ASF dual-hosted git repository.
ffang pushed a commit to branch 3.6.x-fixes
in repository https://gitbox.apache.org/repos/asf/cxf.git
The following commit(s) were added to refs/heads/3.6.x-fixes by this push:
new ad571a53e9 [CXF-9170]avoid unecessary MetricsContext being created and
added to the MessageExchange (#2669)
ad571a53e9 is described below
commit ad571a53e98dbf6bc3901eede908f07f9d4f8892
Author: Freeman(Yue) Fang <[email protected]>
AuthorDate: Tue Oct 21 09:01:14 2025 -0400
[CXF-9170]avoid unecessary MetricsContext being created and added to the
MessageExchange (#2669)
(cherry picked from commit 44e7a08283da59df8cbd66f785831c78f4b2ecb2)
(cherry picked from commit fa7fc1214d1c50be6eaef4be18f46dd3f00dbae9)
---
.../org/apache/cxf/metrics/ExchangeMetrics.java | 8 +-
.../interceptors/AbstractMetricsInterceptor.java | 15 +-
.../jaxws/MicrometerMetricsHttpProvider.java | 120 +++++++++++++
...ionWithoutViolationMetricsClientServerTest.java | 187 +++++++++++++++++++++
4 files changed, 326 insertions(+), 4 deletions(-)
diff --git
a/rt/features/metrics/src/main/java/org/apache/cxf/metrics/ExchangeMetrics.java
b/rt/features/metrics/src/main/java/org/apache/cxf/metrics/ExchangeMetrics.java
index b8407955ce..221467c7bd 100644
---
a/rt/features/metrics/src/main/java/org/apache/cxf/metrics/ExchangeMetrics.java
+++
b/rt/features/metrics/src/main/java/org/apache/cxf/metrics/ExchangeMetrics.java
@@ -40,9 +40,11 @@ public class ExchangeMetrics {
}
public ExchangeMetrics addContext(MetricsContext ctx) {
- contexts.addLast(ctx);
- if (started) {
- ctx.start(exchange);
+ if (!contexts.contains(ctx)) {
+ contexts.addLast(ctx);
+ if (started) {
+ ctx.start(exchange);
+ }
}
return this;
}
diff --git
a/rt/features/metrics/src/main/java/org/apache/cxf/metrics/interceptors/AbstractMetricsInterceptor.java
b/rt/features/metrics/src/main/java/org/apache/cxf/metrics/interceptors/AbstractMetricsInterceptor.java
index b5e7000f3b..e4ff43934e 100644
---
a/rt/features/metrics/src/main/java/org/apache/cxf/metrics/interceptors/AbstractMetricsInterceptor.java
+++
b/rt/features/metrics/src/main/java/org/apache/cxf/metrics/interceptors/AbstractMetricsInterceptor.java
@@ -184,7 +184,20 @@ public abstract class AbstractMetricsInterceptor extends
AbstractPhaseIntercepto
return o;
}
private Object createMetricsContextForOperation(Message message,
BindingOperationInfo boi) {
- Object o = boi.getProperty(MetricsContext.class.getName());
+ Object o = null;
+ if (isRequestor(message)) {
+ o = boi.getProperty(MetricsContext.class.getName());
+ } else {
+ //on the client side the MetricsContext may already be created
+ //at endpoint level; avoid recreating another one
+ o =
message.getExchange().getEndpoint().get(MetricsContext.class.getName());
+ if (o == null) {
+ o = boi.getProperty(MetricsContext.class.getName());
+ } else {
+ boi.setProperty(MetricsContext.class.getName(), o);
+ }
+ }
+
if (o == null) {
List<MetricsContext> contexts = new ArrayList<>();
for (MetricsProvider p :
getMetricProviders(message.getExchange().getBus())) {
diff --git
a/systests/jaxws/src/test/java/org/apache/cxf/systest/jaxws/MicrometerMetricsHttpProvider.java
b/systests/jaxws/src/test/java/org/apache/cxf/systest/jaxws/MicrometerMetricsHttpProvider.java
new file mode 100644
index 0000000000..b9ac531ae5
--- /dev/null
+++
b/systests/jaxws/src/test/java/org/apache/cxf/systest/jaxws/MicrometerMetricsHttpProvider.java
@@ -0,0 +1,120 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.cxf.systest.jaxws;
+
+import java.io.StringReader;
+
+import javax.xml.transform.Source;
+import javax.xml.transform.stream.StreamSource;
+
+
+import jakarta.annotation.Resource;
+import jakarta.xml.ws.BindingType;
+import jakarta.xml.ws.Provider;
+import jakarta.xml.ws.Service;
+import jakarta.xml.ws.ServiceMode;
+import jakarta.xml.ws.WebServiceContext;
+import jakarta.xml.ws.WebServiceProvider;
+import org.apache.cxf.message.Message;
+
+import io.micrometer.core.instrument.Counter;
+import io.micrometer.core.instrument.DistributionSummary;
+import io.micrometer.core.instrument.FunctionCounter;
+import io.micrometer.core.instrument.FunctionTimer;
+import io.micrometer.core.instrument.Gauge;
+import io.micrometer.core.instrument.LongTaskTimer;
+import io.micrometer.core.instrument.Meter;
+import io.micrometer.core.instrument.TimeGauge;
+import io.micrometer.core.instrument.Timer;
+
+@WebServiceProvider(serviceName = "MetricsService", portName = "MetricsPort",
targetNamespace = "urn:metrics")
+@ServiceMode(Service.Mode.MESSAGE)
+@BindingType(jakarta.xml.ws.http.HTTPBinding.HTTP_BINDING)
+public class MicrometerMetricsHttpProvider implements Provider<Source> {
+
+ @Resource
+ private WebServiceContext wsContext;
+
+
+ @Override
+ public Source invoke(Source request) {
+ try {
+ var ctx = wsContext.getMessageContext();
+
+ ctx.put(Message.CONTENT_TYPE, "application/xml; charset=UTF-8");
+ ctx.put(Message.RESPONSE_CODE, 200);
+
+ StringBuilder sb = new StringBuilder(8 * 1024);
+ sb.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n");
+ sb.append("<metrics>\n");
+
+ for (Meter meter :
SchemaValidationWithoutViolationMetricsClientServerTest.METER_REGISTER.getMeters())
{
+ final Meter.Id id = meter.getId();
+ final String name = id.getName();
+
+ final long[] countHolder = new long[] {
+ 0L
+ };
+
+ meter.match((Gauge g) -> null, (Counter counter) -> {
+ countHolder[0] = (long)counter.count();
+ return null;
+ }, (Timer timer) -> {
+ countHolder[0] = timer.count();
+ return null;
+ }, (DistributionSummary summary) -> {
+ countHolder[0] = summary.count();
+ return null;
+ }, (LongTaskTimer longTaskTimer) -> {
+ countHolder[0] = longTaskTimer.activeTasks();
+ return null;
+ }, (TimeGauge timeGauge) -> null, (FunctionCounter
functionCounter) -> {
+ countHolder[0] = (long)functionCounter.count();
+ return null;
+ }, (FunctionTimer functionTimer) -> {
+ countHolder[0] = (long)functionTimer.count();
+ return null;
+ }, (Meter other) -> null);
+
+ sb.append(" <meter
name=\"").append(xmlEscape(name)).append("\" count=\"")
+ .append(countHolder[0]).append("\"/>\n");
+ }
+
+ sb.append("</metrics>\n");
+
+ return new StreamSource(new StringReader(sb.toString()));
+ } catch (Exception e) {
+ throw new RuntimeException(e);
+ }
+ }
+
+ private static String xmlEscape(String s) {
+ if (s == null) {
+ return "";
+ }
+ String r = s;
+ r = r.replace("&", "&");
+ r = r.replace("<", "<");
+ r = r.replace(">", ">");
+ r = r.replace("\"", """);
+ r = r.replace("'", "'");
+ return r;
+ }
+
+}
diff --git
a/systests/jaxws/src/test/java/org/apache/cxf/systest/jaxws/SchemaValidationWithoutViolationMetricsClientServerTest.java
b/systests/jaxws/src/test/java/org/apache/cxf/systest/jaxws/SchemaValidationWithoutViolationMetricsClientServerTest.java
new file mode 100644
index 0000000000..9827969b2b
--- /dev/null
+++
b/systests/jaxws/src/test/java/org/apache/cxf/systest/jaxws/SchemaValidationWithoutViolationMetricsClientServerTest.java
@@ -0,0 +1,187 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.cxf.systest.jaxws;
+
+
+import java.io.InputStream;
+import java.net.HttpURLConnection;
+import java.net.URL;
+import java.util.Arrays;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+
+import javax.xml.namespace.QName;
+import javax.xml.parsers.DocumentBuilder;
+import javax.xml.parsers.DocumentBuilderFactory;
+
+import org.w3c.dom.Document;
+import org.w3c.dom.Element;
+import org.w3c.dom.NodeList;
+
+import jakarta.xml.ws.Endpoint;
+import org.apache.cxf.ext.logging.LoggingInInterceptor;
+import org.apache.cxf.ext.logging.LoggingOutInterceptor;
+import org.apache.cxf.jaxws.EndpointImpl;
+import org.apache.cxf.jaxws.schemavalidation.CkRequestType;
+import org.apache.cxf.jaxws.schemavalidation.RequestHeader;
+import org.apache.cxf.jaxws.schemavalidation.RequestIdType;
+import org.apache.cxf.jaxws.schemavalidation.Service;
+import org.apache.cxf.jaxws.schemavalidation.ServicePortType;
+import org.apache.cxf.message.Message;
+import org.apache.cxf.metrics.MetricsFeature;
+import org.apache.cxf.metrics.micrometer.MicrometerMetricsProperties;
+import org.apache.cxf.metrics.micrometer.MicrometerMetricsProvider;
+import
org.apache.cxf.metrics.micrometer.provider.DefaultExceptionClassProvider;
+import
org.apache.cxf.metrics.micrometer.provider.DefaultTimedAnnotationProvider;
+import org.apache.cxf.metrics.micrometer.provider.StandardTags;
+import org.apache.cxf.metrics.micrometer.provider.StandardTagsProvider;
+import org.apache.cxf.metrics.micrometer.provider.jaxws.JaxwsFaultCodeProvider;
+import
org.apache.cxf.metrics.micrometer.provider.jaxws.JaxwsFaultCodeTagsCustomizer;
+import
org.apache.cxf.metrics.micrometer.provider.jaxws.JaxwsOperationTagsCustomizer;
+import org.apache.cxf.metrics.micrometer.provider.jaxws.JaxwsTags;
+import org.apache.cxf.testutil.common.AbstractBusClientServerTestBase;
+import org.apache.cxf.testutil.common.AbstractBusTestServerBase;
+
+
+import io.micrometer.core.instrument.MeterRegistry;
+import io.micrometer.core.instrument.simple.SimpleMeterRegistry;
+
+import org.junit.BeforeClass;
+import org.junit.Test;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.assertTrue;
+
+public class SchemaValidationWithoutViolationMetricsClientServerTest extends
AbstractBusClientServerTestBase {
+
+
+ public static final MeterRegistry METER_REGISTER = new
SimpleMeterRegistry();
+ private static final String PORT = allocatePort(Server.class);
+
+ private final QName portName = new
QName("http://cxf.apache.org/jaxws/schemavalidation", "servicePort");
+
+ public static class Server extends AbstractBusTestServerBase {
+
+ protected void run() {
+ var jaxwsTags = new JaxwsTags();
+ var operationsCustomizer = new
JaxwsOperationTagsCustomizer(jaxwsTags);
+ var faultsCustomizer = new JaxwsFaultCodeTagsCustomizer(jaxwsTags,
new JaxwsFaultCodeProvider());
+ var standardTags = new StandardTags();
+ var tagsProvider = new StandardTagsProvider(new
DefaultExceptionClassProvider(), standardTags);
+ var properties = new MicrometerMetricsProperties();
+
+ var provider = new MicrometerMetricsProvider(
+ METER_REGISTER,
+ tagsProvider,
+ List.of(operationsCustomizer, faultsCustomizer),
+ new DefaultTimedAnnotationProvider(),
+ properties
+ );
+
+ String address;
+ Object implementor = new ServicePortTypeImpl();
+ address = "http://localhost:" + PORT + "/schemavalidation";
+ Endpoint ep = Endpoint.create(implementor);
+ Map<String, Object> map = new HashMap<>();
+ map.put(Message.SCHEMA_VALIDATION_ENABLED, Boolean.TRUE);
+ ep.setProperties(map);
+
((EndpointImpl)ep).setWsdlLocation("wsdl_systest_jaxws/schemaValidation.wsdl");
+ ((EndpointImpl)ep).setServiceName(new QName(
+ "http://cxf.apache.org/jaxws/schemavalidation",
"service"));
+ ((EndpointImpl)ep).getInInterceptors().add(new
LoggingInInterceptor());
+ ((EndpointImpl)ep).getOutInterceptors().add(new
LoggingOutInterceptor());
+ ((EndpointImpl)ep).setFeatures(Arrays.asList(new
MetricsFeature(provider)));
+ ep.publish(address);
+ Endpoint.publish("http://localhost:" + PORT + "/metrics", new
MicrometerMetricsHttpProvider());
+
+ }
+ }
+
+ @BeforeClass
+ public static void startServers() {
+ createStaticBus();
+ assertTrue("server did not launch correctly",
launchServer(Server.class, true));
+ }
+
+ @Test
+ public void testSchemavalildationWithMetrics() throws Exception {
+ testSchemaValidationWithoutViolation();
+ testCxfServerRequestsCount();
+ }
+
+
+
+
+ private void testSchemaValidationWithoutViolation() throws Exception {
+ Service service = new Service();
+ assertNotNull(service);
+
+ try (ServicePortType greeter = service.getPort(portName,
ServicePortType.class)) {
+ greeter.getInInterceptors().add(new LoggingInInterceptor());
+ greeter.getOutInterceptors().add(new LoggingOutInterceptor());
+ updateAddressPort(greeter, PORT);
+
+ RequestIdType requestId = new RequestIdType();
+ requestId.setId("550e8400-e29b-41d4-a716-446655440000");
+ CkRequestType request = new CkRequestType();
+ request.setRequest(requestId);
+ RequestHeader header = new RequestHeader();
+ header.setHeaderValue("AABBCC");
+
+ try {
+ greeter.ckR(request, header);
+ } finally {
+ assertEquals(1, METER_REGISTER.getMeters().size());
+ }
+ }
+ }
+
+
+ private void testCxfServerRequestsCount() throws Exception {
+ String endpoint = "http://localhost:" + PORT + "/metrics";
+ HttpURLConnection conn = (HttpURLConnection) new
URL(endpoint).openConnection();
+ conn.setRequestMethod("GET");
+ conn.setRequestProperty("Accept", "application/xml");
+
+ assertEquals("HTTP response code", 200, conn.getResponseCode());
+
+ try (InputStream in = conn.getInputStream()) {
+ DocumentBuilderFactory factory =
DocumentBuilderFactory.newInstance();
+ factory.setNamespaceAware(false);
+ DocumentBuilder builder = factory.newDocumentBuilder();
+ Document doc = builder.parse(in);
+
+ NodeList meters = doc.getElementsByTagName("meter");
+ boolean found = false;
+ for (int i = 0; i < meters.getLength(); i++) {
+ Element el = (Element) meters.item(i);
+ String name = el.getAttribute("name");
+ if ("cxf.server.requests".equals(name)) {
+ String count = el.getAttribute("count");
+ assertEquals("cxf.server.requests count", "1", count);
+ found = true;
+ break;
+ }
+ }
+ assertTrue(found);
+ }
+ }
+}
\ No newline at end of file