cambios en los parametros de los contratos, ahora se llaman recetas y no assets

This commit is contained in:
luc662 2025-04-05 20:04:03 +00:00
parent 462ad74cd2
commit 866a2ecb03
3 changed files with 156 additions and 275 deletions

View file

@ -7,15 +7,11 @@ import (
"github.com/hyperledger/fabric-contract-api-go/v2/contractapi"
)
// SmartContract provides functions for managing an Asset
type SmartContract struct {
contractapi.Contract
}
// Asset describes basic details of what makes up a simple asset
// Insert struct field in alphabetic order => to achieve determinism across languages
// golang keeps the order when marshal to json but doesn't order automatically
type Asset struct {
type Receta struct {
ID string `json:"id"`
Owner string `json:"owner"`
PrescripcionAnteriorId string `json:"prescripcionAnteriorId"`
@ -34,41 +30,39 @@ type Asset struct {
ExpectedSupplyDuration string `json:"expectedSupplyDuration"`
}
// InitLedger adds a base set of assets to the ledger
// InitLedger adds a base set of assets to the ledger
func (s *SmartContract) InitLedger(ctx contractapi.TransactionContextInterface) error {
assets := []Asset{
recetas := []Receta{
{
ID: "asset1",
ID: "receta1",
Owner: "Tomoko",
PrescripcionAnteriorId: "presc123",
Status: "active",
StatusChange: "2024-01-15T10:00:00Z",
Prioridad: "high",
Medicacion: "medication1",
Razon: "reason1",
Notas: "some notes",
PeriodoDeTratamiento: "30 days",
InstruccionesTratamiento: "take daily",
PeriodoDeValidez: "1 year",
Medicacion: "medicacion1",
Razon: "razon1",
Notas: "algunas notas",
PeriodoDeTratamiento: "30 dias",
InstruccionesTratamiento: "una por dia",
PeriodoDeValidez: "1 anio",
DniPaciente: "12345678",
FechaDeAutorizacion: "2024-01-01T09:00:00Z",
Cantidad: "5",
ExpectedSupplyDuration: "2024-02-01T09:00:00Z",
},
{
ID: "asset2",
ID: "receta2",
Owner: "Alice",
PrescripcionAnteriorId: "presc456",
Status: "completed",
StatusChange: "2024-02-20T11:00:00Z",
Prioridad: "medium",
Medicacion: "medication2",
Razon: "reason2",
Notas: "other notes",
PeriodoDeTratamiento: "60 days",
InstruccionesTratamiento: "take twice daily",
PeriodoDeValidez: "2 years",
Medicacion: "medicacion2",
Razon: "razon2",
Notas: "otras notas",
PeriodoDeTratamiento: "60 dias",
InstruccionesTratamiento: "dos por dia",
PeriodoDeValidez: "2 anios",
DniPaciente: "87654321",
FechaDeAutorizacion: "2024-01-10T10:00:00Z",
Cantidad: "10",
@ -76,152 +70,108 @@ func (s *SmartContract) InitLedger(ctx contractapi.TransactionContextInterface)
},
}
for _, asset := range assets {
assetJSON, err := json.Marshal(asset)
for _, receta := range recetas {
recetaJSON, err := json.Marshal(receta)
if err != nil {
return err
}
err = ctx.GetStub().PutState(asset.ID, assetJSON)
err = ctx.GetStub().PutState(receta.ID, recetaJSON)
if err != nil {
return fmt.Errorf("failed to put to world state. %v", err)
return fmt.Errorf("error al guardar receta en el ledger: %v", err)
}
}
return nil
}
// CreateAsset issues a new asset to the world state with given details.
func (s *SmartContract) CreateAsset(ctx contractapi.TransactionContextInterface, id string, owner string, prescripcionAnteriorId string, status string, statusChange string, prioridad string, medicacion string, razon string, notas string, periodoDeTratamiento string, instruccionesTratamiento string, periodoDeValidez string, dniPaciente string, fechaDeAutorizacion string, cantidad string, expectedSupplyDuration string) error {
exists, err := s.AssetExists(ctx, id)
func (s *SmartContract) CreateReceta(ctx contractapi.TransactionContextInterface, receta Receta) error {
exists, err := s.RecetaExists(ctx, receta.ID)
if err != nil {
return err
}
if exists {
return fmt.Errorf("the asset %s already exists", id)
return fmt.Errorf("la receta %s ya existe", receta.ID)
}
asset := Asset{
ID: id,
Owner: owner,
PrescripcionAnteriorId: prescripcionAnteriorId,
Status: status,
StatusChange: statusChange,
Prioridad: prioridad,
Medicacion: medicacion,
Razon: razon,
Notas: notas,
PeriodoDeTratamiento: periodoDeTratamiento,
InstruccionesTratamiento: instruccionesTratamiento,
PeriodoDeValidez: periodoDeValidez,
DniPaciente: dniPaciente,
FechaDeAutorizacion: fechaDeAutorizacion,
Cantidad: cantidad,
ExpectedSupplyDuration: expectedSupplyDuration,
}
assetJSON, err := json.Marshal(asset)
recetaJSON, err := json.Marshal(receta)
if err != nil {
return err
}
return ctx.GetStub().PutState(id, assetJSON)
return ctx.GetStub().PutState(receta.ID, recetaJSON)
}
// UpdateAsset updates an existing asset in the world state with provided parameters.
func (s *SmartContract) UpdateAsset(ctx contractapi.TransactionContextInterface, id string, owner string, prescripcionAnteriorId string, status string, statusChange string, prioridad string, medicacion string, razon string, notas string, periodoDeTratamiento string, instruccionesTratamiento string, periodoDeValidez string, dniPaciente string, fechaDeAutorizacion string, cantidad string, expectedSupplyDuration string) error {
exists, err := s.AssetExists(ctx, id)
func (s *SmartContract) UpdateReceta(ctx contractapi.TransactionContextInterface, receta Receta) error {
exists, err := s.RecetaExists(ctx, receta.ID)
if err != nil {
return err
}
if !exists {
return fmt.Errorf("the asset %s does not exist", id)
return fmt.Errorf("la receta %s no existe", receta.ID)
}
// overwriting original asset with new asset
asset := Asset{
ID: id,
Owner: owner,
PrescripcionAnteriorId: prescripcionAnteriorId,
Status: status,
StatusChange: statusChange,
Prioridad: prioridad,
Medicacion: medicacion,
Razon: razon,
Notas: notas,
PeriodoDeTratamiento: periodoDeTratamiento,
InstruccionesTratamiento: instruccionesTratamiento,
PeriodoDeValidez: periodoDeValidez,
DniPaciente: dniPaciente,
FechaDeAutorizacion: fechaDeAutorizacion,
Cantidad: cantidad,
ExpectedSupplyDuration: expectedSupplyDuration,
}
assetJSON, err := json.Marshal(asset)
recetaJSON, err := json.Marshal(receta)
if err != nil {
return err
}
return ctx.GetStub().PutState(id, assetJSON)
return ctx.GetStub().PutState(receta.ID, recetaJSON)
}
// ReadAsset returns the asset stored in the world state with given id.
func (s *SmartContract) ReadAsset(ctx contractapi.TransactionContextInterface, id string) (*Asset, error) {
assetJSON, err := ctx.GetStub().GetState(id)
func (s *SmartContract) ReadReceta(ctx contractapi.TransactionContextInterface, id string) (*Receta, error) {
recetaJSON, err := ctx.GetStub().GetState(id)
if err != nil {
return nil, fmt.Errorf("failed to read from world state: %v", err)
return nil, fmt.Errorf("error al leer del ledger: %v", err)
}
if assetJSON == nil {
return nil, fmt.Errorf("the asset %s does not exist", id)
if recetaJSON == nil {
return nil, fmt.Errorf("la receta %s no existe", id)
}
var asset Asset
err = json.Unmarshal(assetJSON, &asset)
var receta Receta
err = json.Unmarshal(recetaJSON, &receta)
if err != nil {
return nil, err
}
return &asset, nil
return &receta, nil
}
// DeleteAsset deletes an given asset from the world state.
func (s *SmartContract) DeleteAsset(ctx contractapi.TransactionContextInterface, id string) error {
exists, err := s.AssetExists(ctx, id)
func (s *SmartContract) DeleteReceta(ctx contractapi.TransactionContextInterface, id string) error {
exists, err := s.RecetaExists(ctx, id)
if err != nil {
return err
}
if !exists {
return fmt.Errorf("the asset %s does not exist", id)
return fmt.Errorf("la receta %s no existe", id)
}
return ctx.GetStub().DelState(id)
}
// AssetExists returns true when asset with given ID exists in world state
func (s *SmartContract) AssetExists(ctx contractapi.TransactionContextInterface, id string) (bool, error) {
assetJSON, err := ctx.GetStub().GetState(id)
func (s *SmartContract) RecetaExists(ctx contractapi.TransactionContextInterface, id string) (bool, error) {
recetaJSON, err := ctx.GetStub().GetState(id)
if err != nil {
return false, fmt.Errorf("failed to read from world state: %v", err)
return false, fmt.Errorf("error al acceder al ledger: %v", err)
}
return assetJSON != nil, nil
return recetaJSON != nil, nil
}
// TransferAsset updates the owner field of asset with given id in world state, and returns the old owner.
func (s *SmartContract) TransferAsset(ctx contractapi.TransactionContextInterface, id string, newOwner string) (string, error) {
asset, err := s.ReadAsset(ctx, id)
func (s *SmartContract) TransferirReceta(ctx contractapi.TransactionContextInterface, id string, nuevoOwner string) (string, error) {
receta, err := s.ReadReceta(ctx, id)
if err != nil {
return "", err
}
oldOwner := asset.Owner
asset.Owner = newOwner
oldOwner := receta.Owner
receta.Owner = nuevoOwner
assetJSON, err := json.Marshal(asset)
recetaJSON, err := json.Marshal(receta)
if err != nil {
return "", err
}
err = ctx.GetStub().PutState(id, assetJSON)
err = ctx.GetStub().PutState(id, recetaJSON)
if err != nil {
return "", err
}
@ -229,54 +179,48 @@ func (s *SmartContract) TransferAsset(ctx contractapi.TransactionContextInterfac
return oldOwner, nil
}
// GetAllAssets returns all assets found in world state
func (s *SmartContract) GetAllAssets(ctx contractapi.TransactionContextInterface) ([]*Asset, error) {
// range query with empty string for startKey and endKey does an
// open-ended query of all assets in the chaincode namespace.
func (s *SmartContract) GetAllRecetas(ctx contractapi.TransactionContextInterface) ([]*Receta, error) {
resultsIterator, err := ctx.GetStub().GetStateByRange("", "")
if err != nil {
return nil, err
}
defer resultsIterator.Close()
var assets []*Asset
var recetas []*Receta
for resultsIterator.HasNext() {
queryResponse, err := resultsIterator.Next()
if err != nil {
return nil, err
}
var asset Asset
err = json.Unmarshal(queryResponse.Value, &asset)
var receta Receta
err = json.Unmarshal(queryResponse.Value, &receta)
if err != nil {
return nil, err
}
assets = append(assets, &asset)
recetas = append(recetas, &receta)
}
return assets, nil
return recetas, nil
}
// GetMultipleAssets devuelve múltiples activos basados en sus IDs
func (s *SmartContract) GetMultipleAssets(ctx contractapi.TransactionContextInterface, assetIDs []string) ([]*Receta, error) {
var recetas []*Receta
for _, id := range assetIDs {
assetJSON, err := ctx.GetStub().GetState(id)
if err != nil {
return nil, fmt.Errorf("failed to read from world state: %v", err)
}
if assetJSON == nil {
continue // o puedes devolver error si prefieres
}
var receta Receta
err = json.Unmarshal(assetJSON, &receta)
if err != nil {
return nil, err
}
recetas = append(recetas, &receta)
}
return recetas, nil
func (s *SmartContract) GetMultipleRecetas(ctx contractapi.TransactionContextInterface, recetaIDs []string) ([]*Receta, error) {
var recetas []*Receta
for _, id := range recetaIDs {
recetaJSON, err := ctx.GetStub().GetState(id)
if err != nil {
return nil, fmt.Errorf("error al leer del ledger: %v", err)
}
if recetaJSON == nil {
continue
}
var receta Receta
err = json.Unmarshal(recetaJSON, &receta)
if err != nil {
return nil, err
}
recetas = append(recetas, &receta)
}
return recetas, nil
}

View file

@ -9,18 +9,15 @@ import org.hyperledger.fabric.client.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.*;
import java.io.IOException;
import java.time.Instant;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
@RestController
@RequestMapping("/recetas")
public class RecetaController {
@ -29,51 +26,34 @@ public class RecetaController {
@PostMapping("/crear")
public ResponseEntity<AssetIdDto> crear(@RequestBody Receta receta) {
System.out.println("\n--> Submit Transaction: CreateAsset, creates new asset with all arguments");
System.out.println("\n--> Submit Transaction: CrearReceta");
var now = LocalDateTime.now().toString();
var dni = receta.getDniPaciente();
var id = dni + now;
String now = LocalDateTime.now().toString();
String dni = receta.getDniPaciente();
String id = dni + now;
String assetId = Hashing.sha256(id);
receta.setId(assetId);
var assetIdDto = new AssetIdDto();
AssetIdDto assetIdDto = new AssetIdDto();
assetIdDto.setDni(dni);
assetIdDto.setTimeStamp(now);
try {
recetaService.cargarReceta(receta);
return new ResponseEntity<>(assetIdDto, HttpStatus.OK);
} catch (CommitStatusException | EndorseException | CommitException | SubmitException e) {
e.printStackTrace();
return new ResponseEntity<>(HttpStatus.UNAUTHORIZED);
}
return new ResponseEntity<>(assetIdDto, HttpStatus.OK);
}
@PostMapping("/obtener")
public ResponseEntity<RecetaDto> find(@RequestBody Map<String, String> requestBody) {
try {
System.out.println("requestbody: " + requestBody);
String id = requestBody.get("id");
System.out.println("id: " + id);
Receta receta = recetaService.obtenerReceta(id);
RecetaDto recetaDto = new RecetaDto();
recetaDto.setOwner(receta.getOwner());
recetaDto.setPrescripcionAnteriorId(receta.getPrescripcionAnteriorId());
recetaDto.setStatus(receta.getStatus());
recetaDto.setStatusChange(receta.getStatusChange());
recetaDto.setPrioridad(receta.getPrioridad());
recetaDto.setMedicacion(receta.getMedicacion());
recetaDto.setRazon(receta.getRazon());
recetaDto.setNotas(receta.getNotas());
recetaDto.setPeriodoDeTratamiento(receta.getPeriodoDeTratamiento());
recetaDto.setInstruccionesTratamiento(receta.getInstruccionesTratamiento());
recetaDto.setPeriodoDeValidez(receta.getPeriodoDeValidez());
recetaDto.setDniPaciente(receta.getDniPaciente());
recetaDto.setFechaDeAutorizacion(receta.getFechaDeAutorizacion());
recetaDto.setCantidad(receta.getCantidad());
recetaDto.setExpectedSupplyDuration(receta.getExpectedSupplyDuration());
RecetaDto recetaDto = mapToDto(receta);
return new ResponseEntity<>(recetaDto, HttpStatus.OK);
} catch (IOException | GatewayException e) {
e.printStackTrace();
@ -88,36 +68,38 @@ public class RecetaController {
if (ids == null || ids.isEmpty()) {
return new ResponseEntity<>(HttpStatus.BAD_REQUEST);
}
System.out.println("IDs solicitados: " + ids);
List<Receta> recetas = recetaService.obtenerRecetasPorIds(ids);
List<RecetaDto> recetasDto = new ArrayList<>();
for (Receta receta : recetas) {
RecetaDto recetaDto = new RecetaDto();
recetaDto.setOwner(receta.getOwner());
recetaDto.setPrescripcionAnteriorId(receta.getPrescripcionAnteriorId());
recetaDto.setStatus(receta.getStatus());
recetaDto.setStatusChange(receta.getStatusChange());
recetaDto.setPrioridad(receta.getPrioridad());
recetaDto.setMedicacion(receta.getMedicacion());
recetaDto.setRazon(receta.getRazon());
recetaDto.setNotas(receta.getNotas());
recetaDto.setPeriodoDeTratamiento(receta.getPeriodoDeTratamiento());
recetaDto.setInstruccionesTratamiento(receta.getInstruccionesTratamiento());
recetaDto.setPeriodoDeValidez(receta.getPeriodoDeValidez());
recetaDto.setDniPaciente(receta.getDniPaciente());
recetaDto.setFechaDeAutorizacion(receta.getFechaDeAutorizacion());
recetaDto.setCantidad(receta.getCantidad());
recetaDto.setExpectedSupplyDuration(receta.getExpectedSupplyDuration());
recetasDto.add(recetaDto);
recetasDto.add(mapToDto(receta));
}
return new ResponseEntity<>(recetasDto, HttpStatus.OK);
} catch (IOException | GatewayException e) {
e.printStackTrace();
return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR);
}
}
private RecetaDto mapToDto(Receta receta) {
RecetaDto dto = new RecetaDto();
dto.setOwner(receta.getOwner());
dto.setPrescripcionAnteriorId(receta.getPrescripcionAnteriorId());
dto.setStatus(receta.getStatus());
dto.setStatusChange(receta.getStatusChange());
dto.setPrioridad(receta.getPrioridad());
dto.setMedicacion(receta.getMedicacion());
dto.setRazon(receta.getRazon());
dto.setNotas(receta.getNotas());
dto.setPeriodoDeTratamiento(receta.getPeriodoDeTratamiento());
dto.setInstruccionesTratamiento(receta.getInstruccionesTratamiento());
dto.setPeriodoDeValidez(receta.getPeriodoDeValidez());
dto.setDniPaciente(receta.getDniPaciente());
dto.setFechaDeAutorizacion(receta.getFechaDeAutorizacion());
dto.setCantidad(receta.getCantidad());
dto.setExpectedSupplyDuration(receta.getExpectedSupplyDuration());
return dto;
}
}

View file

@ -13,18 +13,13 @@ import org.hyperledger.fabric.client.identity.*;
import org.springframework.stereotype.Service;
import javax.annotation.PostConstruct;
import java.io.Console;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.security.InvalidKeyException;
import java.security.cert.CertificateException;
import java.time.Instant;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.List;
import java.util.concurrent.TimeUnit;
@Service
@ -34,54 +29,41 @@ public class RecetaService {
private static final String CHANNEL_NAME = System.getenv().getOrDefault("CHANNEL_NAME", "mychannel");
private static final String CHAINCODE_NAME = System.getenv().getOrDefault("CHAINCODE_NAME", "basic");
// Path to crypto materials.
private static final Path CRYPTO_PATH = Paths.get("../../test-network/organizations/peerOrganizations/org1.example.com");
// Path to user certificate.
private static final Path CERT_DIR_PATH = CRYPTO_PATH.resolve(Paths.get("users/User1@org1.example.com/msp/signcerts"));
// Path to user private key directory.
private static final Path KEY_DIR_PATH = CRYPTO_PATH.resolve(Paths.get("users/User1@org1.example.com/msp/keystore"));
// Path to peer tls certificate.
private static final Path TLS_CERT_PATH = CRYPTO_PATH.resolve(Paths.get("peers/peer0.org1.example.com/tls/ca.crt"));
private static final Path CERT_DIR_PATH = CRYPTO_PATH.resolve("users/User1@org1.example.com/msp/signcerts");
private static final Path KEY_DIR_PATH = CRYPTO_PATH.resolve("users/User1@org1.example.com/msp/keystore");
private static final Path TLS_CERT_PATH = CRYPTO_PATH.resolve("peers/peer0.org1.example.com/tls/ca.crt");
// Gateway peer end point.
private static final String PEER_ENDPOINT = "localhost:7051";
private static final String OVERRIDE_AUTH = "peer0.org1.example.com";
private Contract contract;
//private final String assetId = "asset" + Instant.now().toEpochMilli();
private final Gson gson = new GsonBuilder().setPrettyPrinting().create();
private static Path getFirstFilePath(Path dirPath) throws IOException {
try (var keyFiles = Files.list(dirPath)) {
return keyFiles.findFirst().orElseThrow();
}
}
@SneakyThrows
@PostConstruct
public void init() {
System.out.println("LLEGO ACA");
var channel = newGrpcConnection();
var builder = Gateway.newInstance().identity(newIdentity()).signer(newSigner()).connection(channel)
// Default timeouts for different gRPC calls
var builder = Gateway.newInstance()
.identity(newIdentity())
.signer(newSigner())
.connection(channel)
.evaluateOptions(options -> options.withDeadlineAfter(5, TimeUnit.SECONDS))
.endorseOptions(options -> options.withDeadlineAfter(15, TimeUnit.SECONDS))
.submitOptions(options -> options.withDeadlineAfter(5, TimeUnit.SECONDS))
.commitStatusOptions(options -> options.withDeadlineAfter(1, TimeUnit.MINUTES));
try (var gateway = builder.connect()) {
System.out.println("LLEGO ACA 2");
this.setContract(gateway);
System.out.println("LLEGO ACA 3");
this.initLedger();
System.out.println("LLEGO ACA 4");
} /*finally {
channel.shutdownNow().awaitTermination(5, TimeUnit.SECONDS);
}*/
}
}
private static ManagedChannel newGrpcConnection() throws IOException {
@ -93,7 +75,7 @@ public class RecetaService {
.build();
}
private Identity newIdentity() throws IOException, CertificateException {
private Identity newIdentity() throws IOException, CertificateException {
try (var certReader = Files.newBufferedReader(getFirstFilePath(CERT_DIR_PATH))) {
var certificate = Identities.readX509Certificate(certReader);
return new X509Identity(MSP_ID, certificate);
@ -108,81 +90,54 @@ public class RecetaService {
}
private void setContract(final Gateway gateway) {
// Get a network instance representing the channel where the smart contract is
// deployed.
var network = gateway.getNetwork(CHANNEL_NAME);
// Get the smart contract from the network.
contract = network.getContract(CHAINCODE_NAME);
}
private void initLedger() throws EndorseException, SubmitException, CommitStatusException, CommitException {
System.out.println("\n--> Submit Transaction: InitLedger, function creates the initial set of assets on the ledger");
contract.submitTransaction("InitLedger");
System.out.println("*** Transaction committed successfully");
}
public void cargarReceta(Receta receta) throws CommitStatusException, EndorseException, CommitException, SubmitException {
System.out.println("\n--> Submit Transaction: CreateAsset, creates new asset with all arguments");
contract.submitTransaction(
"CreateAsset",
receta.getId(),
receta.getOwner(),
receta.getPrescripcionAnteriorId(),
receta.getStatus(),
receta.getStatusChange(),
receta.getPrioridad(),
receta.getMedicacion(),
receta.getRazon(),
receta.getNotas(),
receta.getPeriodoDeTratamiento(),
receta.getInstruccionesTratamiento(),
receta.getPeriodoDeValidez(),
receta.getDniPaciente(),
receta.getFechaDeAutorizacion(),
Integer.toString(receta.getCantidad()),
receta.getExpectedSupplyDuration()
);
System.out.println("*** Transaction committed successfully");
contract.submitTransaction(
"CreateReceta",
receta.getId(),
receta.getOwner(),
receta.getPrescripcionAnteriorId(),
receta.getStatus(),
receta.getStatusChange(),
receta.getPrioridad(),
receta.getMedicacion(),
receta.getRazon(),
receta.getNotas(),
receta.getPeriodoDeTratamiento(),
receta.getInstruccionesTratamiento(),
receta.getPeriodoDeValidez(),
receta.getDniPaciente(),
receta.getFechaDeAutorizacion(),
Integer.toString(receta.getCantidad()),
receta.getExpectedSupplyDuration()
);
}
public Receta obtenerReceta(String assetId) throws GatewayException, IOException {
System.out.println("\n--> Evaluate Transaction: ReadAsset, function returns asset attributes");
System.out.println("assetId: " + assetId);
var evaluateResult = contract.evaluateTransaction("ReadAsset", assetId);
System.out.println("evaluate");
public Receta obtenerReceta(String recetaId) throws GatewayException, IOException {
var evaluateResult = contract.evaluateTransaction("ReadReceta", recetaId);
ObjectMapper objectMapper = new ObjectMapper();
var receta = objectMapper.readValue(evaluateResult, Receta.class);
System.out.println("mapper:" + receta.getDniPaciente());
return receta;
return objectMapper.readValue(evaluateResult, Receta.class);
}
public List<Receta> obtenerTodosLosAssets() throws GatewayException, IOException {
System.out.println("\n--> Evaluate Transaction: GetAllAssets");
var evaluateResult = contract.evaluateTransaction("GetAllAssets");
public List<Receta> obtenerTodasLasRecetas() throws GatewayException, IOException {
var evaluateResult = contract.evaluateTransaction("GetAllRecetas");
ObjectMapper objectMapper = new ObjectMapper();
// Leer como array de Recetas
List<Receta> recetas = objectMapper.readValue(evaluateResult,
objectMapper.getTypeFactory().constructCollectionType(List.class, Receta.class));
return recetas;
return objectMapper.readValue(evaluateResult,
objectMapper.getTypeFactory().constructCollectionType(List.class, Receta.class));
}
public List<Receta> obtenerRecetasPorIds(List<String> assetIds) throws GatewayException, IOException {
System.out.println("\n--> Evaluate Transaction: GetMultipleAssets");
public List<Receta> obtenerRecetasPorIds(List<String> recetaIds) throws GatewayException, IOException {
ObjectMapper objectMapper = new ObjectMapper();
String idsJson = objectMapper.writeValueAsString(assetIds);
var evaluateResult = contract.evaluateTransaction("GetMultipleAssets", idsJson);
return objectMapper.readValue(evaluateResult,
objectMapper.getTypeFactory().constructCollectionType(List.class, Receta.class));
String idsJson = objectMapper.writeValueAsString(recetaIds);
var evaluateResult = contract.evaluateTransaction("GetMultipleRecetas", idsJson);
return objectMapper.readValue(evaluateResult,
objectMapper.getTypeFactory().constructCollectionType(List.class, Receta.class));
}
}