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

Feat: Erpadapter Trigger Service #474

Merged
Original file line number Diff line number Diff line change
Expand Up @@ -21,19 +21,23 @@
package org.eclipse.tractusx.puris.backend.common.edc.domain.model;

public enum AssetType {
DTR("none", "none"),
ITEM_STOCK_SUBMODEL("urn:samm:io.catenax.item_stock:2.0.0#ItemStock", "$value"),
PRODUCTION_SUBMODEL("urn:samm:io.catenax.planned_production_output:2.0.0#PlannedProductionOutput", "$value"),
DEMAND_SUBMODEL("urn:samm:io.catenax.short_term_material_demand:1.0.0#ShortTermMaterialDemand", "$value"),
DELIVERY_SUBMODEL("urn:samm:io.catenax.delivery_information:2.0.0#DeliveryInformation", "$value"),
NOTIFICATION("urn:samm:io.catenax.demand_and_capacity_notification:2.0.0#DemandAndCapacityNotification", "none"),
PART_TYPE_INFORMATION_SUBMODEL("urn:samm:io.catenax.part_type_information:1.0.0#PartTypeInformation", "$value");
DTR("none", "none", "none", "none"),
ITEM_STOCK_SUBMODEL("urn:samm:io.catenax.item_stock:2.0.0#ItemStock", "$value", "ItemStock", "2.0"),
PRODUCTION_SUBMODEL("urn:samm:io.catenax.planned_production_output:2.0.0#PlannedProductionOutput", "$value", "PlannedProductionOutput", "2.0"),
DEMAND_SUBMODEL("urn:samm:io.catenax.short_term_material_demand:1.0.0#ShortTermMaterialDemand", "$value", "ShortTermMaterialDemand", "1.0"),
DELIVERY_SUBMODEL("urn:samm:io.catenax.delivery_information:2.0.0#DeliveryInformation", "$value", "DeliveryInformation", "2.0"),
NOTIFICATION("urn:samm:io.catenax.demand_and_capacity_notification:2.0.0#DemandAndCapacityNotification", "none", "none", "2.0"),
PART_TYPE_INFORMATION_SUBMODEL("urn:samm:io.catenax.part_type_information:1.0.0#PartTypeInformation", "$value", "none", "1.0");

public final String URN_SEMANTIC_ID;
public final String REPRESENTATION;
public final String ERP_KEYWORD;
public final String ERP_SAMMVERSION;

AssetType(String URN_SEMANTIC_ID, String REPRESENTATION) {
AssetType(String URN_SEMANTIC_ID, String REPRESENTATION, String ERP_KEYWORD, String ERP_SAMMVERSION) {
this.URN_SEMANTIC_ID = URN_SEMANTIC_ID;
this.REPRESENTATION = REPRESENTATION;
this.ERP_KEYWORD = ERP_KEYWORD;
this.ERP_SAMMVERSION = ERP_SAMMVERSION;
}
}
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
package org.eclipse.tractusx.puris.backend.erpadapter;

import lombok.AccessLevel;
import lombok.Getter;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
Expand Down Expand Up @@ -40,4 +41,28 @@ public class ErpAdapterConfiguration {
*/
@Value("${puris.erpadapter.authsecret}")
private String erpAdapterAuthSecret;

@Value("${puris.erpadapter.refreshinterval}")
@Getter(AccessLevel.NONE)
private long refreshInterval;

@Value("${puris.erpadapter.timelimit}")
@Getter(AccessLevel.NONE)
private long refreshTimeLimit;

/**
* @return The refresh time limit in milliseconds
*/
public long getRefreshTimeLimit() {
tom-rm-meyer-ISST marked this conversation as resolved.
Show resolved Hide resolved
// translate days to milliseconds
return refreshTimeLimit * 24 * 60 * 60 * 1000;
}

/**
* @return The refresh interval in milliseconds
*/
public long getRefreshInterval() {
// translate minutes to milliseconds
return refreshInterval * 60 * 1000;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -28,12 +28,13 @@
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import io.swagger.v3.oas.annotations.responses.ApiResponses;
import lombok.extern.slf4j.Slf4j;
import org.eclipse.tractusx.puris.backend.common.edc.domain.model.AssetType;
import org.eclipse.tractusx.puris.backend.erpadapter.logic.service.ItemStockErpAdapterService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.Arrays;
import java.util.Date;
import java.util.UUID;

Expand Down Expand Up @@ -73,24 +74,25 @@ public ResponseEntity<?> putMethod(
@RequestParam("response-type") String responseType,
@RequestParam("samm-version") String sammVersion,
@RequestParam(value = "response-timestamp")
@Parameter(example = "2024-05-28T15:00:00")
@DateTimeFormat(pattern = "yyyy-MM-dd'T'HH:mm:ss") Date responseTimestamp,
@Parameter(example = "1719295545654", description = "Represented as the number of milliseconds since January 1, 1970, 00:00:00 GMT")
long responseTimestamp,
@io.swagger.v3.oas.annotations.parameters.RequestBody(content = {@Content(examples = {
@ExampleObject(itemStock20Sample)
})})
@RequestBody JsonNode requestBody
) {
boolean valid = BPNL_PATTERN.matcher(partnerBpnl).matches();
valid = valid && NON_EMPTY_NON_VERTICAL_WHITESPACE_PATTERN.matcher(responseType).matches();
valid = valid && NON_EMPTY_NON_VERTICAL_WHITESPACE_PATTERN.matcher(sammVersion).matches();
boolean valid = BPNL_PATTERN.matcher(partnerBpnl).matches()
&& NON_EMPTY_NON_VERTICAL_WHITESPACE_PATTERN.matcher(responseType).matches()
&& NON_EMPTY_NON_VERTICAL_WHITESPACE_PATTERN.matcher(sammVersion).matches();
if (!valid) {
return ResponseEntity.badRequest().build();
}
Dto dto = new Dto(requestId, partnerBpnl, responseType, sammVersion, responseTimestamp, requestBody);
Dto dto = new Dto(requestId, partnerBpnl, responseType, sammVersion, new Date(responseTimestamp), requestBody);
AssetType assetType = Arrays.stream(AssetType.values()).filter(type -> type.ERP_KEYWORD.equals(responseType)).findFirst().orElse(null);
int responseCode = 501;
switch (responseType) {
case "ItemStock" -> responseCode = itemStockErpAdapterService.receiveItemStockUpdate(dto);
default -> {
switch (assetType) {
case ITEM_STOCK_SUBMODEL -> responseCode = itemStockErpAdapterService.receiveItemStockUpdate(dto);
case null, default -> {
return ResponseEntity.status(responseCode).body("Unsupported response type: " + responseType);
}
}
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,82 @@
/*
* Copyright (c) 2024 Volkswagen AG
tom-rm-meyer-ISST marked this conversation as resolved.
Show resolved Hide resolved
* Copyright (c) 2024 Contributors to the Eclipse Foundation
*
* See the NOTICE file(s) distributed with this work for additional
* information regarding copyright ownership.
*
* This program and the accompanying materials are made available under the
* terms of the Apache License, Version 2.0 which is available at
* https://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.
*
* SPDX-License-Identifier: Apache-2.0
*/

package org.eclipse.tractusx.puris.backend.erpadapter.domain.model;

import jakarta.persistence.Entity;
import jakarta.persistence.Id;
import jakarta.persistence.IdClass;
import lombok.*;
import org.eclipse.tractusx.puris.backend.common.edc.domain.model.AssetType;

import java.io.Serializable;
import java.util.Date;

@Entity
@IdClass(ErpAdapterTriggerDataset.Key.class)
@Getter
@Setter
@AllArgsConstructor
@NoArgsConstructor
@EqualsAndHashCode
public class ErpAdapterTriggerDataset {

@Id
private String partnerBpnl;

@Id
private String ownMaterialNumber;

@Id
private AssetType assetType;

@Id
private String directionCharacteristic;

private long lastPartnerRequest;

private long nextErpRequestScheduled;

@Override
public String toString() {
return "ErpAdapterTriggerDataset{" +
"partnerBpnl='" + partnerBpnl + '\'' +
", ownMaterialNumber='" + ownMaterialNumber + '\'' +
", assetType=" + assetType +
", directionCharacteristic='" + directionCharacteristic + '\'' +
", lastPartnerRequest=" + new Date(lastPartnerRequest) +
", nextErpRequestScheduled=" + new Date(nextErpRequestScheduled) +
'}';
}

@Getter
@Setter
@AllArgsConstructor
@NoArgsConstructor
@EqualsAndHashCode
@ToString
public static class Key implements Serializable {
private String partnerBpnl;
private String ownMaterialNumber;
private AssetType assetType;
private String directionCharacteristic;

}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
/*
* Copyright (c) 2024 Volkswagen AG
* Copyright (c) 2024 Contributors to the Eclipse Foundation
*
* See the NOTICE file(s) distributed with this work for additional
* information regarding copyright ownership.
*
* This program and the accompanying materials are made available under the
* terms of the Apache License, Version 2.0 which is available at
* https://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.
*
* SPDX-License-Identifier: Apache-2.0
*/

package org.eclipse.tractusx.puris.backend.erpadapter.domain.repository;

import org.eclipse.tractusx.puris.backend.erpadapter.domain.model.ErpAdapterTriggerDataset;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;

@Repository
public interface ErpAdapterTriggerDatasetRepository extends JpaRepository<ErpAdapterTriggerDataset, ErpAdapterTriggerDataset.Key> {
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,146 @@
/*
* Copyright (c) 2024 Volkswagen AG
* Copyright (c) 2024 Contributors to the Eclipse Foundation
*
* See the NOTICE file(s) distributed with this work for additional
* information regarding copyright ownership.
*
* This program and the accompanying materials are made available under the
* terms of the Apache License, Version 2.0 which is available at
* https://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.
*
* SPDX-License-Identifier: Apache-2.0
*/

package org.eclipse.tractusx.puris.backend.erpadapter.logic.service;

import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.eclipse.tractusx.puris.backend.common.edc.domain.model.AssetType;
import org.eclipse.tractusx.puris.backend.erpadapter.ErpAdapterConfiguration;
import org.eclipse.tractusx.puris.backend.erpadapter.domain.model.ErpAdapterRequest;
import org.eclipse.tractusx.puris.backend.erpadapter.domain.model.ErpAdapterTriggerDataset;
import org.eclipse.tractusx.puris.backend.erpadapter.domain.repository.ErpAdapterTriggerDatasetRepository;
import org.eclipse.tractusx.puris.backend.stock.logic.dto.itemstocksamm.DirectionCharacteristic;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Future;

@Service
@RequiredArgsConstructor
@Slf4j
public class ErpAdapterTriggerService {

@Autowired
private ErpAdapterTriggerDatasetRepository repository;
@Autowired
private ErpAdapterConfiguration erpAdapterConfiguration;
@Autowired
private ErpAdapterRequestService erpAdapterRequestService;
@Autowired
private ExecutorService executorService;

private final long daemonActivityInterval = 1 * 60 * 1000; // daemon wakes up every five minutes

private Future<?> daemonObject;

private final Runnable daemon = () -> {
log.info("Daemon thread started");
while (true) {
try {
// sleep for the defined period minutes
Thread.sleep(daemonActivityInterval);
} catch (InterruptedException ignore) {
}
if (!erpAdapterConfiguration.isErpAdapterEnabled()) {
log.info("Erp Trigger Daemon signing off because it's not enabled");
// leave loop if erp adapter requests are not configured
break;
}
long timeLimit = erpAdapterConfiguration.getRefreshTimeLimit();
var allDatasets = repository.findAll();
long now = new Date().getTime();
log.info("Daemon waking up, found {} datasets", allDatasets.size());
for (var dataset : allDatasets) {
if (dataset.getLastPartnerRequest() + timeLimit <= now) {
// too much time has passed since last request of this kind, so
// we will stop triggering further updates from the erp adapter
repository.delete(dataset);
log.info("Removed from Erp Trigger: " + dataset);
} else {
if (dataset.getNextErpRequestScheduled() <= now) {
// the time has come for a new erp adapter request
ErpAdapterRequest request = new ErpAdapterRequest();
request.setOwnMaterialNumber(dataset.getOwnMaterialNumber());
request.setPartnerBpnl(dataset.getPartnerBpnl());
request.setRequestDate(new Date(now));
DirectionCharacteristic directionCharacteristic = dataset.getDirectionCharacteristic().isEmpty() ?
null : DirectionCharacteristic.valueOf(dataset.getDirectionCharacteristic());
request.setDirectionCharacteristic(directionCharacteristic);
request.setRequestType(dataset.getAssetType().ERP_KEYWORD);
request.setSammVersion(dataset.getAssetType().ERP_SAMMVERSION);
erpAdapterRequestService.createAndSend(request);

// schedule next request
dataset.setNextErpRequestScheduled(now + erpAdapterConfiguration.getRefreshInterval());
dataset = repository.save(dataset);
log.info("Scheduled next erp adapter request: " + dataset);
}
}
}
}
};

/**
* Send a notification about a just received request from a partner via this
* method in order to schedule regular updates from the erp adapter.
*
* @param partnerBpnl the BPNL of the requesting partner
* @param ownMaterialNumber the material number of the requested material
* @param type the Asset/Submodel type of the request
* @param direction the direction characteristic (if applicable for the given asset type, may be null)
*/
public void notifyPartnerRequest(String partnerBpnl, String ownMaterialNumber, AssetType type, DirectionCharacteristic direction) {
if (!erpAdapterConfiguration.isErpAdapterEnabled()) {
return;
}
if (daemonObject == null) {
daemonObject = executorService.submit(daemon);
}
String directionString = direction != null ? direction.name() : "";
ErpAdapterTriggerDataset dataset = repository.findById
(new ErpAdapterTriggerDataset.Key(partnerBpnl, ownMaterialNumber, type, directionString)).orElse(null);
long now = new Date().getTime();
if (dataset == null) {
// unknown request specifics, so we trigger a new request right now
ErpAdapterRequest erpAdapterRequest = new ErpAdapterRequest();
erpAdapterRequest.setRequestDate(new Date(now));
erpAdapterRequest.setPartnerBpnl(partnerBpnl);
erpAdapterRequest.setOwnMaterialNumber(ownMaterialNumber);
erpAdapterRequest.setDirectionCharacteristic(direction);
erpAdapterRequest.setRequestType(type.ERP_KEYWORD);
erpAdapterRequest.setSammVersion(type.ERP_SAMMVERSION);
executorService.submit(() -> erpAdapterRequestService.createAndSend(erpAdapterRequest));

// create dataset for the daemon thread to schedule future erp adapter requests
dataset = new ErpAdapterTriggerDataset(partnerBpnl, ownMaterialNumber, type, directionString, now,
now + erpAdapterConfiguration.getRefreshInterval());
dataset = repository.save(dataset);
log.info("Created erp trigger dataset {}", dataset);
} else {
// we had previous requests of that kind, so we just store the timestamp of this latest request
dataset.setLastPartnerRequest(now);
repository.save(dataset);
}
}

}
Loading
Loading