Skip to content

Commit

Permalink
Merge pull request #177 from eclipse-tractusx/feat/connect-backend-to…
Browse files Browse the repository at this point in the history
…-bpdm-pool

Adjust new logic to be compatible with new EDC of BPDM
  • Loading branch information
fabiodmota authored May 14, 2024
2 parents c0f9d47 + d4c50d4 commit 5b8a2b1
Show file tree
Hide file tree
Showing 9 changed files with 188 additions and 115 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@ public class SecurityConfiguration {
public SecurityFilterChain securityFilterChain(final HttpSecurity httpSecurity) throws Exception {
httpSecurity.cors(withDefaults())
.authorizeHttpRequests((auth-> auth
.requestMatchers("/error","/api/dashboard/**","/api/sharing/**","/api/edc/**")
.requestMatchers("/error","/api/dashboard/**","/api/negotiation/**","/api/sharing/**","/api/edc/**")
.authenticated()
.requestMatchers("/v3/api-docs/**", "/swagger-ui.html", "/swagger-ui/**","/management/**")
.permitAll()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -44,5 +44,9 @@ public class CatalogItemDTO {

@Schema(description = "Description of the catalog item", example = "Grants the Catena-X Member read access to the Pool API...")
private String description;

@Schema(description = "Specific usage purpose or partner category", example = "cx.bpdm.pool:1")
private String usagePurpose;
}


Original file line number Diff line number Diff line change
Expand Up @@ -36,4 +36,7 @@ public class NegotiationRequestDTO {
@Schema(description = "Identifier of the offer associated with the catalog item", example = "offer123", required = true)
private String offerId;

@Schema(description = "Specific usage purpose or partner category", example = "cx.bpdm.pool:1")
private String usagePurpose;

}
Original file line number Diff line number Diff line change
Expand Up @@ -57,19 +57,21 @@ public class EdcLogicService {
@Value("${application.bpdm.apiKey}")
private String apiKey;

@Value("${application.bpdm.gateProviderId}")
private String gateProviderId;

@Autowired
private EdcProperties edcProperties;

@Autowired
ObjectMapper objectMapper;



public Mono<String> sendFinalRequest(NegotiationResponseDTO edrResponse, Object body) {
public Mono<String> sendFinalRequest(NegotiationResponseDTO edrResponse, Object body,String path) {
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
headers.set("Authorization", edrResponse.getAuthCode());
return executePostRequest(edrResponse.getEndpoint(), body, headers, response -> response);
return executePostRequest(edrResponse.getEndpoint()+path, body, headers, response -> response);
}


Expand All @@ -83,13 +85,13 @@ public List<CatalogItemDTO> queryCatalog() {
log.debug("Request Body: " + requestBody);


return invokeService.executeRequest("default",consumerManagementUrl + "/v2/catalog/request/", HttpMethod.POST, httpEntity, this::mapResponseFromQueryCatalog).block();
return invokeService.executeRequest("default", consumerManagementUrl + "/v2/catalog/request/", HttpMethod.POST, httpEntity, this::mapResponseFromQueryCatalog).block();
}

// Helper methods
private <T> Mono<T> executePostRequest(String url, Object body, HttpHeaders headers, Function<String, T> responseMapper) {
HttpEntity<Object> httpEntity = new HttpEntity<>(body, headers);
return invokeService.executeRequest("default",url, HttpMethod.POST, httpEntity, responseMapper);
return invokeService.executeRequest("default", url, HttpMethod.POST, httpEntity, responseMapper);
}

private HttpHeaders createHttpHeaders() {
Expand All @@ -101,22 +103,32 @@ private HttpHeaders createHttpHeaders() {

private Map<String, Object> createCatalogRequestBody() {
Map<String, Object> requestBody = new HashMap<>();
requestBody.put("@context", new HashMap<>());

// Definindo @context
Map<String, String> context = new HashMap<>();
context.put("@vocab", "https://w3id.org/edc/v0.0.1/ns/");
requestBody.put("@context", context);

// Adicionando @type
requestBody.put("@type", "CatalogRequest");

// Adicionando counterPartyAddress e counterPartyId
requestBody.put("counterPartyAddress", gateProviderProtocolUrl); // Use a variável correta para o URL
requestBody.put("counterPartyId", gateProviderId); // Adicione uma variável ou valor fixo para o ID

// Protocolo
requestBody.put("protocol", "dataspace-protocol-http");
requestBody.put("providerUrl", gateProviderProtocolUrl);

// querySpec conforme definido no JSON
Map<String, Object> querySpec = new HashMap<>();
querySpec.put("offset", 0);
querySpec.put("limit", 100);
querySpec.put("filter", "");

Map<String, Integer> range = new HashMap<>();
range.put("from", 0);
range.put("to", 100);
querySpec.put("range", range);
querySpec.put("criterion", "");
querySpec.put("limit", 50); // ajuste conforme necessário
querySpec.put("sortOrder", "DESC");
querySpec.put("sortField", "fieldName");
querySpec.put("filterExpression", new ArrayList<>()); // Lista vazia como no JSON original

requestBody.put("querySpec", querySpec);

return requestBody;
}

Expand All @@ -129,36 +141,47 @@ private List<CatalogItemDTO> mapResponseFromQueryCatalog(String response) {
JsonNode datasets = responseJson.path("dcat:dataset");

if (datasets.isArray()) {
datasets.forEach(dataset -> {
String type = dataset.path("dct:type").asText().replace("cx-taxo:", "");
for (JsonNode dataset : datasets) {
String fullType = dataset.path("https://purl.org/dc/terms/type").asText();
String type = fullType.replace("cx-taxo:", "");
if (edcProperties.getProviders().contains(type)) {
catalogItems.add(processDatasetAndCreateDTO(dataset));
catalogItems.add(processDatasetAndCreateDTO(dataset, type));
}
});
} else if (!datasets.isMissingNode()) {
String type = datasets.path("dct:type").asText().replace("cx-taxo:", "");
if (edcProperties.getProviders().contains(type)) {
catalogItems.add(processDatasetAndCreateDTO(datasets));
}
}
} catch (IOException e) {
log.error("Error parsing response JSON: {}", e.getMessage());
log.error("Error parsing response JSON: " + e.getMessage());
}

return catalogItems;
}

private CatalogItemDTO processDatasetAndCreateDTO(JsonNode dataset) {
private CatalogItemDTO processDatasetAndCreateDTO(JsonNode dataset, String provider) {
String id = dataset.get("@id").asText();
String offerId = dataset.path("odrl:hasPolicy").get("@id").asText();
String subject = dataset.path("dct:subject").asText().replace("cx-taxo:","");
String description = dataset.path("dct:description").asText();
String provider = dataset.path("dct:type").asText().replace("cx-taxo:","");
String subject = dataset.path("https://purl.org/dc/terms/subject").asText();
String description = dataset.path("https://purl.org/dc/terms/description").asText();

// Buscar dinamicamente a restrição de "UsagePurpose"
JsonNode constraints = dataset.path("odrl:hasPolicy")
.path("odrl:permission")
.path("odrl:constraint")
.path("odrl:and");
String usagePurpose = "";

if (constraints.isArray()) {
for (JsonNode constraint : constraints) {
String leftOperand = constraint.path("odrl:leftOperand").asText();
if ("https://w3id.org/catenax/policy/UsagePurpose".equals(leftOperand)) {
usagePurpose = constraint.path("odrl:rightOperand").asText();
break;
}
}
}

return new CatalogItemDTO(id, offerId, provider, subject, description);
return new CatalogItemDTO(id, offerId, provider, subject, description, usagePurpose);
}




}
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,9 @@
import org.springframework.web.reactive.function.BodyInserters;
import org.springframework.web.reactive.function.client.WebClient;
import reactor.core.publisher.Mono;
import reactor.util.retry.Retry;

import java.time.Duration;
import java.util.List;
import java.util.function.Function;

Expand All @@ -48,7 +50,7 @@ public void ExternalService(@Qualifier("poolWebClient") WebClient poolWebClient,
this.gateWebClient = gateWebClient;
}

public <T> Mono<List<T>> executeRequest(String clientType,String url, HttpMethod httpMethod, HttpEntity<?> httpEntity, Class<T> responseType, Function<String, List<T>> mappingFunction) {
public <T> Mono<List<T>> executeRequest(String clientType, String url, HttpMethod httpMethod, HttpEntity<?> httpEntity, Class<T> responseType, Function<String, List<T>> mappingFunction) {
WebClient webClient = getWebClient(clientType);
return webClient.method(httpMethod)
.uri(url)
Expand All @@ -60,6 +62,11 @@ public <T> Mono<List<T>> executeRequest(String clientType,String url, HttpMethod
.onErrorResume(e -> {
log.error("error url {} message {}", url, e.getMessage());
throw new RuntimeException(e.getMessage());
})
.retryWhen(Retry.fixedDelay(3, Duration.ofSeconds(5))) // tenta 3 vezes com um intervalo de 5 segundos
.onErrorResume(e -> {
log.error("Persistent error after retries: {} {}", url, e.getMessage());
return Mono.error(new RuntimeException("Failed after retries", e));
});
}

Expand All @@ -75,6 +82,11 @@ public <T> Mono<T> executeRequest(String clientType,String url, HttpMethod httpM
.onErrorResume(e -> {
log.error("error url {} message {}", url, e.getMessage());
throw new RuntimeException(e.getMessage());
})
.retryWhen(Retry.fixedDelay(3, Duration.ofSeconds(2)))
.onErrorResume(e -> {
log.error("Persistent error after retries: {} {}", url, e.getMessage());
return Mono.error(new RuntimeException("Failed after retries", e));
});
}

Expand Down Expand Up @@ -130,6 +142,11 @@ public <T> Mono<List<T>> executeRequest(String url, HttpMethod httpMethod, HttpE
.onErrorResume(e -> {
log.error("error url {} message {}", url, e.getMessage());
throw new RuntimeException(e.getMessage());
})
.retryWhen(Retry.fixedDelay(3, Duration.ofSeconds(5))) // tenta 3 vezes com um intervalo de 5 segundos
.onErrorResume(e -> {
log.error("Persistent error after retries: {} {}", url, e.getMessage());
return Mono.error(new RuntimeException("Failed after retries", e));
});
}
}
Expand Down
Loading

0 comments on commit 5b8a2b1

Please sign in to comment.