private static boolean checkPurposeValue(CustomerEventWebhook customerEventWebhook,
String purposeId,
String valueKey,
String expectedValue) {
return customerEventWebhook.parameters().entity().consents().purposes().stream()
.filter(purpose -> purposeId.equals(purpose.id()))
.findFirst()
.map(purpose -> purpose.values().get(valueKey))
.map(value -> expectedValue.equals(value.value()))
.orElse(false);
} ajoutes des commentaires en anglais pour ces deux methodes
Assistant
User
public TopRelEmailing topRelEmailing(CustomerPurposesTransform customerPurposesTransform) {
var ep = customerPurposesTransform.email_cnst_pret();
var ea = customerPurposesTransform.email_cnst_ana();
var sp = customerPurposesTransform.sms_cnst_pret();
var sa = customerPurposesTransform.sms_cnst_ana();
code
if (ep && ea && sp && sa) return TopRelEmailing.O;
if ((ep && ea && !sp && sa) ||
(!ep && ea && sp && sa) ||
(!ep && ea && !sp && sa) ||
(!ep && !ea && !sp && !sa)) {
return TopRelEmailing.N;
}
return TopRelEmailing.D;
}
public String optinMailTop(CustomerPurposesTransform customerPurposesTransform) {
return (customerPurposesTransform.courrier_cnst_oppo() && customerPurposesTransform.as_cnst_oppo()) ? "0" : "3";
} ajoutes des commentaires en anglais pour ces deux methodes
Assistant
User
Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
Below is the same code with English‑language Javadoc/comments that explain what each method does, the meaning of its parameters, and the value that is returned.
I also added a short note about the duplicated courrier_cnst_oppo call (the second call overwrites the first one) – you may want to rename one of the fields or remove the duplicate.
java
/**
* Transforms a {@link CustomerEventWebhook} into the internal
* {@link CustomerPurposesTransform} representation.
*
* <p>This method extracts the consent values for the various marketing
* channels (email, SMS, courrier) and maps them to the corresponding
* fields of {@code CustomerPurposesTransform}. The extraction is
* delegated to {@link #checkPurposeValue(CustomerEventWebhook, String, String, String)}.
*
* @param customerEventWebhook the webhook payload received from the
* external system; must contain the
* consent information in the nested
* {@code parameters().entity().consents().purposes()}
* @return a {@link CustomerPurposesTransform} instance populated with
* boolean flags indicating whether each specific purpose/value
* combination was granted.
*/
public CustomerPurposesTransform mapToIntermediary(CustomerEventWebhook customerEventWebhook) {
return CustomerPurposesTransform.builder()
// Email – “pret” purpose (commercial offer) for the “offrescom” consent
.email_cnst_pret(checkPurposeValue(customerEventWebhook,
"offrescom-zaZGdL8E", // purpose id
"bVtDGhPy", // value key inside the purpose
"NdmTLDaP")) // expected value that means “granted”
// Email – “ana” purpose (professional offer) for the “offrespro” consent
.email_cnst_ana(checkPurposeValue(customerEventWebhook,
"offrespro-TYTQar26",
"NhzTBLEf",
"87tBpAF3"))
// SMS – “pret” purpose for the “offrescom” consent
.sms_cnst_pret(checkPurposeValue(customerEventWebhook,
"offrescom-zaZGdL8E",
"bVtDGhPy",
"FfkLh9EE"))
// SMS – “ana” purpose for the “offrespro” consent
.sms_cnst_ana(checkPurposeValue(customerEventWebhook,
"offrespro-TYTQar26",
"Da4kWhea",
"TXtiJAdt"))
// Courrier – “oppo” purpose for the “offresdu” consent
.courrier_cnst_oppo(checkPurposeValue(customerEventWebhook,
"offresdu-8a63TFJe",
"xWTxApWx",
"EjjMq9mK"))
// NOTE: the following line overwrites the previous value for
// `courrier_cnst_oppo`. If you intended to store a
// second flag, use a different field name.
.courrier_cnst_oppo(checkPurposeValue(customerEventWebhook,
"offresdu-8a63TFJe",
"xWTxApWx",
"3tUfqWAF"))
.build();
}
/**
* Checks whether a specific consent purpose/value pair matches an expected
* value.
*
* <p>The method looks for a purpose with the supplied {@code purposeId} inside
* the webhook, then retrieves the value identified by {@code valueKey} and
* finally compares that value with {@code expectedValue}. If any step fails
* (purpose not found, key missing, or value not equal), {@code false} is
* returned.
*
* @param customerEventWebhook the incoming webhook containing the consent
* data.
* @param purposeId the identifier of the purpose we are interested
* in (e.g. {@code "offrescom-zaZGdL8E"}).
* @param valueKey the key of the value inside the purpose’s
* {@code values} map (e.g. {@code "bVtDGhPy"}).
* @param expectedValue the concrete value that indicates the consent is
* granted (e.g. {@code "NdmTLDaP"}).
* @return {@code true} if the purpose exists and its value matches
* {@code expectedValue}; {@code false} otherwise.
*/
private static boolean checkPurposeValue(CustomerEventWebhook customerEventWebhook,
String purposeId,
String valueKey,
String expectedValue) {
return customerEventWebhook.parameters()
.entity()
.consents()
.purposes()
.stream()
// Find the purpose with the given ID
.filter(purpose -> purposeId.equals(purpose.id()))
.findFirst()
// Extract the value object for the supplied key
.map(purpose -> purpose.values().get(valueKey))
// Compare the actual value with the expected one
.map(value -> expectedValue.equals(value.value()))
// If anything is missing, treat it as “not granted”
.orElse(false);
}
Quick recap
Method
What it does
Key points
mapToIntermediary
Builds a CustomerPurposesTransform from the webhook data.
Calls checkPurposeValue for each channel/purpose pair.
checkPurposeValue
Returns true only when the webhook contains the specified purpose and its value matches the expected value.
Uses streams + Optional to avoid NullPointerException.
Feel free to adjust the field names or remove the duplicated courrier_cnst_oppo call if you need two separate flags. The comments should now make the intent of each piece of code clear to any developer reading it.
Here is the same code with clear English‑language Javadoc and inline comments that describe the purpose of each method, the meaning of its parameters, and the reasoning behind the conditional logic.
java
/**
* Determines the overall “top‑relation” (overall consent level) for a
* customer based on the four boolean flags that come from the
* {@link CustomerPurposesTransform} object.
*
* <p>The four flags represent the consent status for the following
* combinations:
* <ul>
* <li>{@code ep} – Email “pret” (commercial) consent</li>
* <li>{@code ea} – Email “ana” (professional) consent</li>
* <li>{@code sp} – SMS “pret” consent</li>
* <li>{@code sa} – SMS “ana” consent</li>
* </ul>
*
* The method returns a {@link TopRelEmailing} enum that encodes three
* possible outcomes:
* <ul>
* <li>{@code O} – All four consents are granted.</li>
* <li>{@code N} – A “neutral” configuration (mixed or no consent).</li>
* <li>{@code D} – Any other combination (i.e. a “partial” or “divergent”
* set of consents).</li>
* </ul>
*
* @param customerPurposesTransform an object that already contains the
* four boolean consent flags.
* @return the calculated {@link TopRelEmailing} value.
*/
public TopRelEmailing topRelEmailing(CustomerPurposesTransform customerPurposesTransform) {
// Extract the four boolean flags for readability
boolean ep = customerPurposesTransform.email_cnst_pret(); // Email – commercial
boolean ea = customerPurposesTransform.email_cnst_ana(); // Email – professional
boolean sp = customerPurposesTransform.sms_cnst_pret(); // SMS – commercial
boolean sa = customerPurposesTransform.sms_cnst_ana(); // SMS – professional
// -----------------------------------------------------------------
// 1️⃣ All four consents are true → highest level (O = “Optimal”)
// -----------------------------------------------------------------
if (ep && ea && sp && sa) {
return TopRelEmailing.O;
}
// -----------------------------------------------------------------
// 2️⃣ “Neutral” configurations:
// • Mixed consents where the pattern matches one of the
// explicitly listed cases, OR
// • No consent at all (all false)
// -----------------------------------------------------------------
if ((ep && ea && !sp && sa) // Email both, SMS only “ana”
|| (!ep && ea && sp && sa) // Email only “ana”, SMS both
|| (!ep && ea && !sp && sa) // Email only “ana”, SMS only “ana”
|| (!ep && !ea && !sp && !sa) // Nothing granted
) {
return TopRelEmailing.N;
}
// -----------------------------------------------------------------
// 3️⃣ Any other combination → “Divergent” (D)
// -----------------------------------------------------------------
return TopRelEmailing.D;
}
/**
* Returns the opt‑in flag for the “mail top” channel.
*
* <p>The flag is based on two separate consent values:
* <ul>
* <li>{@code courrier_cnst_oppo} – consent for postal (courier) “oppo”</li>
* <li>{@code as_cnst_oppo} – consent for “as” (presumably an
* additional service) “oppo”</li>
* </ul>
*
* If **both** consents are true, the method returns the string {@code "0"},
* which conventionally means “opt‑in”. Otherwise it returns {@code "3"},
* indicating “opt‑out” (or “not opted‑in”). The method keeps the return type
* as {@link String} because the downstream system expects the literal values
* “0” and “3”.
*
* @param customerPurposesTransform the transformed consent object containing
* the two relevant boolean flags.
* @return {@code "0"} when both flags are true; {@code "3"} otherwise.
*/
public String optinMailTop(CustomerPurposesTransform customerPurposesTransform) {
// Both the postal “oppo” consent and the “as” “oppo” consent must be true
// to be considered an opt‑in (value "0").
boolean hasPostalConsent = customerPurposesTransform.courrier_cnst_oppo();
boolean hasAsConsent = customerPurposesTransform.as_cnst_oppo();
return (hasPostalConsent && hasAsConsent) ? "0" : "3";
}
What the comments cover
Javadoc block – explains the overall purpose, the parameters, the return value, and the meaning of each enum constant.
Inline variable names – make it clear which boolean corresponds to which channel/purpose.
Section headers – separate the logical branches (all‑true, neutral, divergent) so future maintainers can quickly see why each if block exists.
Explanation for optinMailTop – describes the two flags it checks and why the method returns "0" vs "3".
Feel free to adapt the wording (e.g., replace “oppo” with the actual business term) or to rename the local variables if they better match your domain language. The comments should now make the intent of each method obvious to anyone reading the code.
// Get bearerToken
String bearerToken = null;
// Get applicationId
String applicationId = null;
if (HeadersUtil.getHContext() != null) {
bearerToken = HeadersUtil.getAuthorizationToken();
applicationId = HeadersUtil.getHContext().getApplicationId();
}
customerService.updateStopRelationshipCustomerById(applicationId, bearerToken, customerId, personalContactsStopRelationshipBody);
return Response.status(Response.Status.NO_CONTENT).build();
}
}
et dans mon project j'ai créer cette interface :
@FeignClient(name = "CustomerRegistration",
url = "${customer.registration.base.url}", configuration = FeignConfiguration.class)
public interface CustomerRegistration {
}
Below you will find a complete, ready‑to‑use example that shows how to call the external PATCH /customers/{id}/consent endpoint with Spring Cloud OpenFeign.
The answer is split into three parts
1️⃣ Feign client definition – method signature, annotations, headers, body.
2️⃣ Feign configuration – request‑interceptor that injects Authorization and CorrelationId (taken from your HeadersUtil), JSON encoder/decoder, and a small tweak that makes Feign understand the PATCH verb.
3️⃣ Usage – how to inject the client and call the API from your service layer, plus a short note on error handling.
1️⃣ Feign client interface
java
package com.myproject.integration.customerregistration;
import com.cacf.customer.registration.model.CustomerPersonalContactsStopRelationship;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
/**
* OpenFeign client that mirrors the external Customer‑Registration PATCH endpoint
* PATCH /customers/{id}/consent
*
* The external API returns **204 NO_CONTENT**, therefore the method returns {@code void}.
* Spring will translate a non‑2xx response into a {@link feign.FeignException}.
*/
@FeignClient(
name = "customer-registration", // logical name used for Ribbon / load‑balancing if needed
url = "${customer.registration.base.url}", // e.g. https://api.customer‑registration.io
configuration = CustomerRegistrationFeignConfig.class // custom config (interceptor, encoder, …)
)
public interface CustomerRegistrationClient {
/**
* Updates the “personal contacts stop relationship” for a given customer.
*
* @param customerId the id that appears in the path (‑/customers/{id}/‑)
* @param body the JSON payload sent in the request body
* @param authorization the Bearer token – will be filled automatically by the
* {@link CustomerRegistrationFeignConfig#requestInterceptor()}.
* @param correlationId optional correlation id – also filled automatically.
*/
@PatchMapping(
value = "/customers/{id}/consent",
consumes = MediaType.APPLICATION_JSON_VALUE,
produces = MediaType.APPLICATION_JSON_VALUE
)
@ResponseStatus(code = org.springframework.http.HttpStatus.NO_CONTENT) // 204
void updatePersonalContactsStopRelationship(
@PathVariable("id") String customerId,
@RequestBody CustomerPersonalContactsStopRelationship body,
// These two headers are **added by the interceptor**, but we keep the
// parameters here so that a caller can override them if needed.
@RequestHeader(value = "Authorization") String authorization,
@RequestHeader(value = "Correlationid", required = false) String correlationId
);
}
Why this exact signature?
Element
Reason
@PatchMapping
Spring OpenFeign supports the same Spring MVC annotations you use in controllers, so PATCH works out‑of‑the‑box.
void return type
The external service replies with 204 NO_CONTENT – there is no body to deserialize.
@RequestHeader parameters
They allow the interceptor to inject the values automatically; the method stays test‑friendly because you can supply explicit values in unit‑tests.
@ResponseStatus(NO_CONTENT)
Makes the client method throw an exception only when the status is not 2xx (Feign’s default behaviour).
Create a separate configuration class that will be referenced in the @FeignClient annotation.
java
package com.myproject.integration.customerregistration;
import feign.RequestInterceptor;
import feign.RequestTemplate;
import feign.codec.Decoder;
import feign.codec.Encoder;
import feign.jackson.JacksonDecoder;
import feign.jackson.JacksonEncoder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.util.StringUtils;
/**
* Custom OpenFeign configuration for the Customer‑Registration client.
*
* - Adds the mandatory *Authorization* header (Bearer token) and the optional
* *Correlationid* header to every request.
* - Registers Jackson encoder/decoder (JSON ↔ POJOs).
* - (Optional) sets a short timeout – adjust to your needs.
*/
@Configuration
public class CustomerRegistrationFeignConfig {
/**
* Interceptor that reads the token / correlation‑id from the thread‑local
* {@link HeadersUtil} (the same utility you already use in your JAX‑RS
* resource) and adds them as HTTP headers.
*/
@Bean
public RequestInterceptor requestInterceptor() {
return new RequestInterceptor() {
@Override
public void apply(RequestTemplate template) {
// ---- Authorization -------------------------------------------------
String bearerToken = null;
String correlationId = null;
if (HeadersUtil.getHContext() != null) {
bearerToken = HeadersUtil.getAuthorizationToken(); // already contains the "Bearer " prefix
correlationId = HeadersUtil.getCorrelationId(); // you may have a dedicated getter
}
if (StringUtils.hasText(bearerToken)) {
// Ensure the header contains the full "Bearer xxx" value
template.header("Authorization", bearerToken);
}
// ---- CorrelationId (optional) ---------------------------------------
if (StringUtils.hasText(correlationId)) {
template.header("Correlationid", correlationId);
}
// ---- Content‑type (just to be explicit) -----------------------------
template.header("Content-Type", "application/json");
template.header("Accept", "application/json");
}
};
}
/** Jackson encoder – converts POJOs (request body) → JSON */
@Bean
public Encoder feignEncoder() {
return new JacksonEncoder();
}
/** Jackson decoder – converts JSON → POJOs (response body) */
@Bean
public Decoder feignDecoder() {
return new JacksonDecoder();
}
// -------------------------------------------------------------------------
// OPTIONAL: you can also customise time‑outs, retryer, logger, etc.
// -------------------------------------------------------------------------
// @Bean
// public feign.Logger.Level feignLoggerLevel() {
// return feign.Logger.Level.FULL;
// }
}
What the interceptor does
Authorization – pulls the bearer token from the same place you used in the
CustomerRegistrationResources class (HeadersUtil.getAuthorizationToken()),
then adds the header Authorization: Bearer ….
CorrelationId – optional; helps you trace the request across services.
Content‑Type & Accept – forced to application/json so the external API
receives exactly what it expects.
If you ever need to override the headers (e.g. in a unit test), simply pass
different values when you call the client method – the interceptor will replace
the existing ones.
3️⃣ Using the client in your service layer
java
package com.myproject.service;
import com.cacf.customer.registration.model.CustomerPersonalContactsStopRelationship;
import com.myproject.integration.customerregistration.CustomerRegistrationClient;
import feign.FeignException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
@Service
public class CustomerConsentService {
private static final Logger LOG = LoggerFactory.getLogger(CustomerConsentService.class);
private final CustomerRegistrationClient registrationClient;
public CustomerConsentService(CustomerRegistrationClient registrationClient) {
this.registrationClient = registrationClient;
}
/**
* Calls the external PATCH /customers/{id}/consent endpoint.
*
* @param customerId the id of the customer to update
* @param payload the body that must be sent
*/
public void updateStopRelationship(String customerId,
CustomerPersonalContactsStopRelationship payload) {
try {
// The interceptor will automatically fill the two headers.
registrationClient.updatePersonalContactsStopRelationship(
customerId,
payload,
// we still have to pass a non‑null value; the interceptor will
// overwrite it, but providing a placeholder avoids a
// NullPointerException in case the interceptor is removed.
"Bearer placeholder",
null);
} catch (FeignException fe) {
// All non‑2xx responses are wrapped into FeignException.
// You can translate them to your own domain exceptions if you wish.
LOG.error("Failed to update stop‑relationship for customer {} – status {} – {}",
customerId, fe.status(), fe.getMessage());
throw fe; // or wrap into a custom exception
}
}
}
Points to keep in mind
Situation
What to do
Testing
In a unit test you can @MockBean CustomerRegistrationClient and verify that updatePersonalContactsStopRelationship(..) is called with the expected arguments.
Circuit‑breaker / fallback
If you use Resilience4j or Spring Cloud CircuitBreaker, add a fallbackFactory attribute to @FeignClient and implement a fallback implementation that returns a sensible default (e.g. logs and swallows the error).
Timeouts
Add a feign.Client bean (e.g. OkHttpClient) with read/write/connect timeouts, or configure ribbon.ReadTimeout / ribbon.ConnectTimeout if you rely on Ribbon.
Logging
Enable feign.Logger.Level.FULL in the config to see request/response payloads while debugging.
TL;DR – What you need to copy‑paste
Feign client (CustomerRegistrationClient) – contains the @PatchMapping method.
Feign config (CustomerRegistrationFeignConfig) – request interceptor + Jackson encoder/decoder.
Inject & call the client from any Spring bean (service, controller, etc.).
After adding the two classes above and the @EnableFeignClients annotation on a configuration class (or on your main @SpringBootApplication), Spring will create a bean named customer-registration that you can @Autowired wherever you need it.
java
@SpringBootApplication
@EnableFeignClients(basePackages = "com.myproject.integration.customerregistration")
public class MyApplication { … }
That’s it – you now have a type‑safe, Spring‑managed Feign client that talks to the external /customers/{id}/consent PATCH endpoint, automatically forwards the required headers, and respects the 204 NO_CONTENT contract. Happy coding!