Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Chore/cleanup itemstock2 #332

Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view

This file was deleted.

Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,6 @@
import okhttp3.*;
import org.eclipse.tractusx.puris.backend.common.edc.domain.model.EdcContractMapping;
import org.eclipse.tractusx.puris.backend.common.edc.logic.dto.EDR_Dto;
import org.eclipse.tractusx.puris.backend.common.edc.logic.dto.datatype.DT_ApiMethodEnum;
import org.eclipse.tractusx.puris.backend.common.edc.logic.util.EdcRequestBodyBuilder;
import org.eclipse.tractusx.puris.backend.common.util.PatternStore;
import org.eclipse.tractusx.puris.backend.common.util.VariablesService;
Expand Down Expand Up @@ -124,21 +123,15 @@ private Response sendPostRequest(JsonNode requestBody, List<String> pathSegments
* @return true if all registrations were successful, otherwise false
*/
public boolean registerAssetsInitially() {
boolean result;
log.info("Registration of item-stock request api successful " + (result = registerApiAsset(DT_ApiMethodEnum.REQUEST)));
if (!result) return false;
log.info("Registration of item-stock response api successful " + (result = registerApiAsset(DT_ApiMethodEnum.RESPONSE)));
if (!result) return false;
log.info("Registration of item-stock status-request api successful " + (result = registerApiAsset(DT_ApiMethodEnum.STATUS_REQUEST)));
if (!result) return false;
boolean result = true;
if (variablesService.isUseFrameworkPolicy()) {
log.info("Registration of framework agreement policy successful " + (result = createFrameWorkPolicy()));
if (!result) return false;
} else {
log.info("Skipping registration of framework agreement policy");
}
log.info("Registration of DTR Asset successful " + (result = registerDtrAsset()));
log.info("Registration of ItemStock 2.0.0 submodel successful " + (result = registerItemStockSubmodel()));
log.info("Registration of DTR Asset successful " + (result &= registerDtrAsset()));
log.info("Registration of ItemStock 2.0.0 submodel successful " + (result &= registerItemStockSubmodel()));
return result;
}

Expand All @@ -155,38 +148,8 @@ public boolean createPolicyAndContractDefForPartner(Partner partner) {
result &= createItemStockSubmodelContractDefinitionForPartner(partner);
result &= createDtrContractDefinitionForPartner(partner);
result &= registerPartTypeAssetForPartner(partner);
result &= createPartTypeInfoContractDefForPartner(partner);
result &= createContractDefinitionForPartner(partner, DT_ApiMethodEnum.REQUEST);
result &= createContractDefinitionForPartner(partner, DT_ApiMethodEnum.STATUS_REQUEST);
return result & createContractDefinitionForPartner(partner, DT_ApiMethodEnum.RESPONSE);
}
return createPartTypeInfoContractDefForPartner(partner) && result;

/**
* Registers a contract definition using a policy that
* allows only the given partner's BPNL for the given Api Method.
* Prior to this method you must always have successfully completed the
* createPolicyDefinitionForPartner - method first.
*
* @param partner the partner
* @param apiMethod the api method
* @return true, if registration ran successfully
*/
private boolean createContractDefinitionForPartner(Partner partner, DT_ApiMethodEnum apiMethod) {
var body = edcRequestBodyBuilder.buildContractDefinitionWithBpnRestrictedPolicy(partner, apiMethod);
try (var response = sendPostRequest(body, List.of("v2", "contractdefinitions"))) {
if (!response.isSuccessful()) {
log.warn("Contract definition registration failed for partner " + partner.getBpnl() + " and "
+ apiMethod);
if (response.body() != null) {
log.warn("Response: \n" + response.body().string());
}
return false;
}
return true;
} catch (Exception e) {
log.error("Contract definition registration failed for partner " + partner.getBpnl() + " and " + apiMethod);
return false;
}
}

private boolean createItemStockSubmodelContractDefinitionForPartner(Partner partner) {
Expand Down Expand Up @@ -319,31 +282,8 @@ private boolean registerPartTypeAssetForPartner(Partner partner) {
}
}

/**
* Util method to register an API asset to your control plane.
*
* @param apiMethod the api method to register.
* @return true if successful.
*/
private boolean registerApiAsset(DT_ApiMethodEnum apiMethod) {
var body = edcRequestBodyBuilder.buildCreateItemStockAssetBody(apiMethod);
try (var response = sendPostRequest(body, List.of("v3", "assets"))) {
if (!response.isSuccessful()) {
log.warn("Asset registration failed");
if (response.body() != null) {
log.warn("Response: \n" + response.body().string());
}
return false;
}
return true;
} catch (Exception e) {
log.error("Failed to register api asset " + apiMethod.CX_TAXO, e);
return false;
}
}

private boolean registerItemStockSubmodel() {
var body = edcRequestBodyBuilder.buildItemStock2RegistrationBody();
var body = edcRequestBodyBuilder.buildItemStockSubmodelRegistrationBody();
try (var response = sendPostRequest(body, List.of("v3", "assets"))) {
if (!response.isSuccessful()) {
log.warn("ItemStock Submodel Asset registration failed");
Expand Down Expand Up @@ -1054,111 +994,6 @@ public String[] getContractForPartTypeInfoSubmodel(Partner partner) {
}
}

/**
* Tries to negotiate for the given api Method with the given partner
* and also tries to initiate the transfer of the edr token to the given endpoint.
* <p>
* It will return a String array of length 4. The authKey is stored under index 0, the
* authCode under index 1, the endpoint under index 2 and the contractId under index 3.
*
* @param partner the partner
* @param apiMethod the api method
* @return A String array or null, if negotiation or transfer have failed or the authCode did not arrive
*/
public String[] getContractForItemStockApi(Partner partner, DT_ApiMethodEnum apiMethod) {
try {
var responseNode = getCatalog(partner.getEdcUrl());
var catalogArray = responseNode.get("dcat:dataset");
// If there is exactly one asset, the catalogContent will be a JSON object.
// In all other cases catalogContent will be a JSON array.
// For the sake of uniformity we will embed a single object in an array.
if (catalogArray.isObject()) {
catalogArray = objectMapper.createArrayNode().add(catalogArray);
}
JsonNode targetCatalogEntry = null;

for (var entry : catalogArray) {
var dctTypeObject = entry.get("dct:type");
if (dctTypeObject != null) {
if (("https://w3id.org/catenax/taxonomy#" + apiMethod.CX_TAXO).equals(dctTypeObject.get("@id").asText())) {
if (apiMethod.TYPE.equals(entry.get("asset:prop:type").asText())) {
if ("1.0".equals(entry.get("https://w3id.org/catenax/ontology/common#version").asText())) {
if (targetCatalogEntry == null) {
if (variablesService.isUseFrameworkPolicy()) {
if (testFrameworkAgreementConstraint(entry)) {
targetCatalogEntry = entry;
} else {
log.error("Contract Negotiation with partner " + partner.getBpnl() + " has " +
"been aborted. This partner's contract policy does not match the policy " +
"supported by this application. \n Supported Policy: " + variablesService.getPurisFrameworkAgreement() +
"\n Received offer from Partner: \n" + entry.toPrettyString());
break;
}
} else {
targetCatalogEntry = entry;
}
} else {
log.warn("Ambiguous catalog entries found! \n" + catalogArray.toPrettyString());
}
}
}
}
}
}
if (targetCatalogEntry == null) {
log.error("Could not find api asset " + apiMethod + " at partner " + partner.getBpnl() + " 's catalog");
return null;
}
String assetApiId = targetCatalogEntry.get("@id").asText();
JsonNode negotiationResponse = initiateNegotiation(partner, targetCatalogEntry);
String negotiationId = negotiationResponse.get("@id").asText();
// Await confirmation of contract and contractId
String contractId = null;
for (int i = 0; i < 100; i++) {
Thread.sleep(100);
var responseObject = getNegotiationState(negotiationId);
if ("FINALIZED".equals(responseObject.get("edc:state").asText())) {
contractId = responseObject.get("edc:contractAgreementId").asText();
break;
}
}
if (contractId == null) {
var negotiationState = getNegotiationState(negotiationId);
log.warn("no contract id, last negotiation state: \n" + negotiationState.toPrettyString());
log.error("Failed to obtain " + assetApiId + " from " + partner.getEdcUrl());
return null;
}

// Initiate transfer of edr
var transferResp = initiateProxyPullTransfer(partner, contractId, assetApiId);
String transferId = transferResp.get("@id").asText();
for (int i = 0; i < 100; i++) {
Thread.sleep(100);
transferResp = getTransferState(transferId);
if ("STARTED".equals(transferResp.get("edc:state").asText())) {
break;
}
}

// Await arrival of edr
for (int i = 0; i < 100; i++) {
Thread.sleep(100);
EDR_Dto edr_Dto = edrService.findByTransferId(transferId);
if (edr_Dto != null) {
log.info("Successfully negotiated for " + assetApiId + " with " + partner.getEdcUrl());
return new String[]{edr_Dto.authKey(), edr_Dto.authCode(), edr_Dto.endpoint(), contractId};
}
}
log.warn("did not receive authCode");
log.error("Failed to obtain " + assetApiId + " from " + partner.getEdcUrl());
return null;

} catch (Exception e) {
log.error("Failed to get contract for " + apiMethod + " from " + partner.getBpnl(), e);
return null;
}
}

/**
* Helper method to check whether you and the contract offer from the other party have the
* same framework agreement policy.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,6 @@
import com.fasterxml.jackson.databind.node.ObjectNode;
import lombok.extern.slf4j.Slf4j;
import org.eclipse.tractusx.puris.backend.common.util.VariablesService;
import org.eclipse.tractusx.puris.backend.common.edc.logic.dto.datatype.DT_ApiMethodEnum;
import org.eclipse.tractusx.puris.backend.masterdata.domain.model.Partner;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
Expand Down Expand Up @@ -77,35 +76,6 @@ public ObjectNode buildBasicCatalogRequestBody(String counterPartyDspUrl, Map<St
return objectNode;
}

public JsonNode buildCreateItemStockAssetBody(DT_ApiMethodEnum apiMethod) {
var body = getAssetRegistrationContext();
body.put("@id", variablesService.getApiAssetId(apiMethod));
var propertiesObject = MAPPER.createObjectNode();
body.set("properties", propertiesObject);
var dctTypeObject = MAPPER.createObjectNode();
propertiesObject.set("dct:type", dctTypeObject);
dctTypeObject.put("@id", "cx-taxo:" + apiMethod.CX_TAXO);
propertiesObject.put("asset:prop:type", apiMethod.TYPE);
propertiesObject.put("cx-common:version", "1.0");
propertiesObject.put("description", apiMethod.DESCRIPTION);

var dataAddress = MAPPER.createObjectNode();
String url = switch (apiMethod) {
case REQUEST -> variablesService.getRequestServerEndpoint();
case RESPONSE -> variablesService.getResponseServerEndpoint();
case STATUS_REQUEST -> variablesService.getStatusRequestServerEndpoint();
};
dataAddress.put("baseUrl", url);
dataAddress.put("type", "HttpData");
dataAddress.put("proxyPath", "true");
dataAddress.put("proxyBody", "true");
dataAddress.put("proxyMethod", "true");
dataAddress.put("authKey", "x-api-key");
dataAddress.put("authCode", variablesService.getApiKey());
body.set("dataAddress", dataAddress);
return body;
}

/**
* Creates a request body in order to register a policy that
* allows only the BPNL of the given partner.
Expand Down Expand Up @@ -171,34 +141,6 @@ public JsonNode buildFrameworkAgreementPolicy() {
return body;
}

/**
* Creates a request body in order to register a contract definition for the given partner and the given
* api method that uses the BPNL-restricted policy created with the buildBpnRestrictedPolicy - method.
* Depending on your configuration, it will also use the Framework Agreement Policy as the contract policy.
*
* @param partner the partner
* @param apiMethod the api method
* @return the request body
*/
public JsonNode buildContractDefinitionWithBpnRestrictedPolicy(Partner partner, DT_ApiMethodEnum apiMethod) {
var body = getEdcContextObject();
body.put("@id", partner.getBpnl() + "_contractdefinition_for_" + apiMethod);
body.put("accessPolicyId", getBpnPolicyId(partner));
if(variablesService.isUseFrameworkPolicy()) {
body.put("contractPolicyId", FRAMEWORK_POLICY_ID);
} else {
body.put("contractPolicyId", getBpnPolicyId(partner));
}
var assetsSelector = MAPPER.createObjectNode();
body.set("assetsSelector", assetsSelector);
assetsSelector.put("@type", "CriterionDto");
assetsSelector.put("operandLeft", EDC_NAMESPACE + "id");
assetsSelector.put("operator", "=");
assetsSelector.put("operandRight", variablesService.getApiAssetId(apiMethod));
return body;
}


public JsonNode buildItemStockSubmodelContractDefinitionWithBpnRestrictedPolicy(Partner partner) {
var body = getEdcContextObject();
body.put("@id", partner.getBpnl() + "_contractdefinition_for_" + getItemStockSubmodelAssetId());
Expand Down Expand Up @@ -373,7 +315,7 @@ public JsonNode buildDtrRegistrationBody() {
return body;
}

public JsonNode buildItemStock2RegistrationBody() {
public JsonNode buildItemStockSubmodelRegistrationBody() {
var body = getAssetRegistrationContext();
body.put("@id", getItemStockSubmodelAssetId());
var propertiesObject = MAPPER.createObjectNode();
Expand All @@ -387,7 +329,7 @@ public JsonNode buildItemStock2RegistrationBody() {
semanticId.put("@id", "urn:samm:io.catenax.item_stock:2.0.0#ItemStock");
body.set("privateProperties", MAPPER.createObjectNode());

String url = variablesService.getRequestServerEndpoint();
String url = variablesService.getItemStockSubmodelEndpoint();
var dataAddress = MAPPER.createObjectNode();
dataAddress.put("@type", "DataAddress");
dataAddress.put("proxyPath", "true");
Expand Down
Loading
Loading