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" "github.com/hyperledger/fabric-contract-api-go/v2/contractapi"
) )
// SmartContract provides functions for managing an Asset
type SmartContract struct { type SmartContract struct {
contractapi.Contract contractapi.Contract
} }
// Asset describes basic details of what makes up a simple asset type Receta struct {
// 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 {
ID string `json:"id"` ID string `json:"id"`
Owner string `json:"owner"` Owner string `json:"owner"`
PrescripcionAnteriorId string `json:"prescripcionAnteriorId"` PrescripcionAnteriorId string `json:"prescripcionAnteriorId"`
@ -34,41 +30,39 @@ type Asset struct {
ExpectedSupplyDuration string `json:"expectedSupplyDuration"` 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 { func (s *SmartContract) InitLedger(ctx contractapi.TransactionContextInterface) error {
assets := []Asset{ recetas := []Receta{
{ {
ID: "asset1", ID: "receta1",
Owner: "Tomoko", Owner: "Tomoko",
PrescripcionAnteriorId: "presc123", PrescripcionAnteriorId: "presc123",
Status: "active", Status: "active",
StatusChange: "2024-01-15T10:00:00Z", StatusChange: "2024-01-15T10:00:00Z",
Prioridad: "high", Prioridad: "high",
Medicacion: "medication1", Medicacion: "medicacion1",
Razon: "reason1", Razon: "razon1",
Notas: "some notes", Notas: "algunas notas",
PeriodoDeTratamiento: "30 days", PeriodoDeTratamiento: "30 dias",
InstruccionesTratamiento: "take daily", InstruccionesTratamiento: "una por dia",
PeriodoDeValidez: "1 year", PeriodoDeValidez: "1 anio",
DniPaciente: "12345678", DniPaciente: "12345678",
FechaDeAutorizacion: "2024-01-01T09:00:00Z", FechaDeAutorizacion: "2024-01-01T09:00:00Z",
Cantidad: "5", Cantidad: "5",
ExpectedSupplyDuration: "2024-02-01T09:00:00Z", ExpectedSupplyDuration: "2024-02-01T09:00:00Z",
}, },
{ {
ID: "asset2", ID: "receta2",
Owner: "Alice", Owner: "Alice",
PrescripcionAnteriorId: "presc456", PrescripcionAnteriorId: "presc456",
Status: "completed", Status: "completed",
StatusChange: "2024-02-20T11:00:00Z", StatusChange: "2024-02-20T11:00:00Z",
Prioridad: "medium", Prioridad: "medium",
Medicacion: "medication2", Medicacion: "medicacion2",
Razon: "reason2", Razon: "razon2",
Notas: "other notes", Notas: "otras notas",
PeriodoDeTratamiento: "60 days", PeriodoDeTratamiento: "60 dias",
InstruccionesTratamiento: "take twice daily", InstruccionesTratamiento: "dos por dia",
PeriodoDeValidez: "2 years", PeriodoDeValidez: "2 anios",
DniPaciente: "87654321", DniPaciente: "87654321",
FechaDeAutorizacion: "2024-01-10T10:00:00Z", FechaDeAutorizacion: "2024-01-10T10:00:00Z",
Cantidad: "10", Cantidad: "10",
@ -76,152 +70,108 @@ func (s *SmartContract) InitLedger(ctx contractapi.TransactionContextInterface)
}, },
} }
for _, asset := range assets { for _, receta := range recetas {
assetJSON, err := json.Marshal(asset) recetaJSON, err := json.Marshal(receta)
if err != nil { if err != nil {
return err return err
} }
err = ctx.GetStub().PutState(asset.ID, assetJSON) err = ctx.GetStub().PutState(receta.ID, recetaJSON)
if err != nil { 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 return nil
} }
// CreateAsset issues a new asset to the world state with given details. func (s *SmartContract) CreateReceta(ctx contractapi.TransactionContextInterface, receta Receta) error {
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.RecetaExists(ctx, receta.ID)
exists, err := s.AssetExists(ctx, id)
if err != nil { if err != nil {
return err return err
} }
if exists { if exists {
return fmt.Errorf("the asset %s already exists", id) return fmt.Errorf("la receta %s ya existe", receta.ID)
} }
asset := Asset{ recetaJSON, err := json.Marshal(receta)
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)
if err != nil { if err != nil {
return err 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) UpdateReceta(ctx contractapi.TransactionContextInterface, receta Receta) error {
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.RecetaExists(ctx, receta.ID)
exists, err := s.AssetExists(ctx, id)
if err != nil { if err != nil {
return err return err
} }
if !exists { 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 recetaJSON, err := json.Marshal(receta)
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)
if err != nil { if err != nil {
return err 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) ReadReceta(ctx contractapi.TransactionContextInterface, id string) (*Receta, error) {
func (s *SmartContract) ReadAsset(ctx contractapi.TransactionContextInterface, id string) (*Asset, error) { recetaJSON, err := ctx.GetStub().GetState(id)
assetJSON, err := ctx.GetStub().GetState(id)
if err != nil { 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 { if recetaJSON == nil {
return nil, fmt.Errorf("the asset %s does not exist", id) return nil, fmt.Errorf("la receta %s no existe", id)
} }
var asset Asset var receta Receta
err = json.Unmarshal(assetJSON, &asset) err = json.Unmarshal(recetaJSON, &receta)
if err != nil { if err != nil {
return nil, err return nil, err
} }
return &asset, nil return &receta, nil
} }
// DeleteAsset deletes an given asset from the world state. func (s *SmartContract) DeleteReceta(ctx contractapi.TransactionContextInterface, id string) error {
func (s *SmartContract) DeleteAsset(ctx contractapi.TransactionContextInterface, id string) error { exists, err := s.RecetaExists(ctx, id)
exists, err := s.AssetExists(ctx, id)
if err != nil { if err != nil {
return err return err
} }
if !exists { 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) return ctx.GetStub().DelState(id)
} }
// AssetExists returns true when asset with given ID exists in world state func (s *SmartContract) RecetaExists(ctx contractapi.TransactionContextInterface, id string) (bool, error) {
func (s *SmartContract) AssetExists(ctx contractapi.TransactionContextInterface, id string) (bool, error) { recetaJSON, err := ctx.GetStub().GetState(id)
assetJSON, err := ctx.GetStub().GetState(id)
if err != nil { 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 recetaJSON != nil, nil
return assetJSON != nil, nil
} }
// TransferAsset updates the owner field of asset with given id in world state, and returns the old owner. func (s *SmartContract) TransferirReceta(ctx contractapi.TransactionContextInterface, id string, nuevoOwner string) (string, error) {
func (s *SmartContract) TransferAsset(ctx contractapi.TransactionContextInterface, id string, newOwner string) (string, error) { receta, err := s.ReadReceta(ctx, id)
asset, err := s.ReadAsset(ctx, id)
if err != nil { if err != nil {
return "", err return "", err
} }
oldOwner := asset.Owner oldOwner := receta.Owner
asset.Owner = newOwner receta.Owner = nuevoOwner
assetJSON, err := json.Marshal(asset) recetaJSON, err := json.Marshal(receta)
if err != nil { if err != nil {
return "", err return "", err
} }
err = ctx.GetStub().PutState(id, assetJSON) err = ctx.GetStub().PutState(id, recetaJSON)
if err != nil { if err != nil {
return "", err return "", err
} }
@ -229,54 +179,48 @@ func (s *SmartContract) TransferAsset(ctx contractapi.TransactionContextInterfac
return oldOwner, nil return oldOwner, nil
} }
// GetAllAssets returns all assets found in world state func (s *SmartContract) GetAllRecetas(ctx contractapi.TransactionContextInterface) ([]*Receta, error) {
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.
resultsIterator, err := ctx.GetStub().GetStateByRange("", "") resultsIterator, err := ctx.GetStub().GetStateByRange("", "")
if err != nil { if err != nil {
return nil, err return nil, err
} }
defer resultsIterator.Close() defer resultsIterator.Close()
var assets []*Asset var recetas []*Receta
for resultsIterator.HasNext() { for resultsIterator.HasNext() {
queryResponse, err := resultsIterator.Next() queryResponse, err := resultsIterator.Next()
if err != nil { if err != nil {
return nil, err return nil, err
} }
var asset Asset var receta Receta
err = json.Unmarshal(queryResponse.Value, &asset) err = json.Unmarshal(queryResponse.Value, &receta)
if err != nil { if err != nil {
return nil, err 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) GetMultipleRecetas(ctx contractapi.TransactionContextInterface, recetaIDs []string) ([]*Receta, error) {
func (s *SmartContract) GetMultipleAssets(ctx contractapi.TransactionContextInterface, assetIDs []string) ([]*Receta, error) { var recetas []*Receta
var recetas []*Receta for _, id := range recetaIDs {
recetaJSON, err := ctx.GetStub().GetState(id)
for _, id := range assetIDs { if err != nil {
assetJSON, err := ctx.GetStub().GetState(id) return nil, fmt.Errorf("error al leer del ledger: %v", err)
if err != nil { }
return nil, fmt.Errorf("failed to read from world state: %v", err) if recetaJSON == nil {
} continue
if assetJSON == nil { }
continue // o puedes devolver error si prefieres
} var receta Receta
err = json.Unmarshal(recetaJSON, &receta)
var receta Receta if err != nil {
err = json.Unmarshal(assetJSON, &receta) return nil, err
if err != nil { }
return nil, err recetas = append(recetas, &receta)
} }
recetas = append(recetas, &receta) return recetas, nil
}
return recetas, nil
} }

View file

@ -9,18 +9,15 @@ import org.hyperledger.fabric.client.*;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus; import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity; import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.*;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.io.IOException; import java.io.IOException;
import java.time.Instant;
import java.time.LocalDateTime; import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Map; import java.util.Map;
@RestController @RestController
@RequestMapping("/recetas") @RequestMapping("/recetas")
public class RecetaController { public class RecetaController {
@ -29,51 +26,34 @@ public class RecetaController {
@PostMapping("/crear") @PostMapping("/crear")
public ResponseEntity<AssetIdDto> crear(@RequestBody Receta receta) { 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(); String now = LocalDateTime.now().toString();
var dni = receta.getDniPaciente(); String dni = receta.getDniPaciente();
var id = dni + now; String id = dni + now;
String assetId = Hashing.sha256(id); String assetId = Hashing.sha256(id);
receta.setId(assetId); receta.setId(assetId);
var assetIdDto = new AssetIdDto();
AssetIdDto assetIdDto = new AssetIdDto();
assetIdDto.setDni(dni); assetIdDto.setDni(dni);
assetIdDto.setTimeStamp(now); assetIdDto.setTimeStamp(now);
try { try {
recetaService.cargarReceta(receta); recetaService.cargarReceta(receta);
return new ResponseEntity<>(assetIdDto, HttpStatus.OK);
} catch (CommitStatusException | EndorseException | CommitException | SubmitException e) { } catch (CommitStatusException | EndorseException | CommitException | SubmitException e) {
e.printStackTrace();
return new ResponseEntity<>(HttpStatus.UNAUTHORIZED); return new ResponseEntity<>(HttpStatus.UNAUTHORIZED);
} }
return new ResponseEntity<>(assetIdDto, HttpStatus.OK);
} }
@PostMapping("/obtener") @PostMapping("/obtener")
public ResponseEntity<RecetaDto> find(@RequestBody Map<String, String> requestBody) { public ResponseEntity<RecetaDto> find(@RequestBody Map<String, String> requestBody) {
try { try {
System.out.println("requestbody: " + requestBody);
String id = requestBody.get("id"); String id = requestBody.get("id");
System.out.println("id: " + id);
Receta receta = recetaService.obtenerReceta(id); Receta receta = recetaService.obtenerReceta(id);
RecetaDto recetaDto = new RecetaDto();
RecetaDto recetaDto = mapToDto(receta);
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());
return new ResponseEntity<>(recetaDto, HttpStatus.OK); return new ResponseEntity<>(recetaDto, HttpStatus.OK);
} catch (IOException | GatewayException e) { } catch (IOException | GatewayException e) {
e.printStackTrace(); e.printStackTrace();
@ -88,36 +68,38 @@ public class RecetaController {
if (ids == null || ids.isEmpty()) { if (ids == null || ids.isEmpty()) {
return new ResponseEntity<>(HttpStatus.BAD_REQUEST); return new ResponseEntity<>(HttpStatus.BAD_REQUEST);
} }
System.out.println("IDs solicitados: " + ids);
List<Receta> recetas = recetaService.obtenerRecetasPorIds(ids); List<Receta> recetas = recetaService.obtenerRecetasPorIds(ids);
List<RecetaDto> recetasDto = new ArrayList<>(); List<RecetaDto> recetasDto = new ArrayList<>();
for (Receta receta : recetas) { for (Receta receta : recetas) {
RecetaDto recetaDto = new RecetaDto(); recetasDto.add(mapToDto(receta));
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);
} }
return new ResponseEntity<>(recetasDto, HttpStatus.OK); return new ResponseEntity<>(recetasDto, HttpStatus.OK);
} catch (IOException | GatewayException e) { } catch (IOException | GatewayException e) {
e.printStackTrace(); e.printStackTrace();
return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR); 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 org.springframework.stereotype.Service;
import javax.annotation.PostConstruct; import javax.annotation.PostConstruct;
import java.io.Console;
import java.io.IOException; import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files; import java.nio.file.Files;
import java.nio.file.Path; import java.nio.file.Path;
import java.nio.file.Paths; import java.nio.file.Paths;
import java.security.InvalidKeyException; import java.security.InvalidKeyException;
import java.security.cert.CertificateException; import java.security.cert.CertificateException;
import java.time.Instant; import java.util.List;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeUnit;
@Service @Service
@ -34,54 +29,41 @@ public class RecetaService {
private static final String CHANNEL_NAME = System.getenv().getOrDefault("CHANNEL_NAME", "mychannel"); private static final String CHANNEL_NAME = System.getenv().getOrDefault("CHANNEL_NAME", "mychannel");
private static final String CHAINCODE_NAME = System.getenv().getOrDefault("CHAINCODE_NAME", "basic"); 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"); 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("users/User1@org1.example.com/msp/signcerts");
private static final Path CERT_DIR_PATH = CRYPTO_PATH.resolve(Paths.get("users/User1@org1.example.com/msp/signcerts")); private static final Path KEY_DIR_PATH = CRYPTO_PATH.resolve("users/User1@org1.example.com/msp/keystore");
// Path to user private key directory. private static final Path TLS_CERT_PATH = CRYPTO_PATH.resolve("peers/peer0.org1.example.com/tls/ca.crt");
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"));
// Gateway peer end point.
private static final String PEER_ENDPOINT = "localhost:7051"; private static final String PEER_ENDPOINT = "localhost:7051";
private static final String OVERRIDE_AUTH = "peer0.org1.example.com"; private static final String OVERRIDE_AUTH = "peer0.org1.example.com";
private Contract contract; private Contract contract;
//private final String assetId = "asset" + Instant.now().toEpochMilli();
private final Gson gson = new GsonBuilder().setPrettyPrinting().create(); private final Gson gson = new GsonBuilder().setPrettyPrinting().create();
private static Path getFirstFilePath(Path dirPath) throws IOException { private static Path getFirstFilePath(Path dirPath) throws IOException {
try (var keyFiles = Files.list(dirPath)) { try (var keyFiles = Files.list(dirPath)) {
return keyFiles.findFirst().orElseThrow(); return keyFiles.findFirst().orElseThrow();
} }
} }
@SneakyThrows @SneakyThrows
@PostConstruct @PostConstruct
public void init() { public void init() {
System.out.println("LLEGO ACA");
var channel = newGrpcConnection(); var channel = newGrpcConnection();
var builder = Gateway.newInstance().identity(newIdentity()).signer(newSigner()).connection(channel) var builder = Gateway.newInstance()
// Default timeouts for different gRPC calls .identity(newIdentity())
.signer(newSigner())
.connection(channel)
.evaluateOptions(options -> options.withDeadlineAfter(5, TimeUnit.SECONDS)) .evaluateOptions(options -> options.withDeadlineAfter(5, TimeUnit.SECONDS))
.endorseOptions(options -> options.withDeadlineAfter(15, TimeUnit.SECONDS)) .endorseOptions(options -> options.withDeadlineAfter(15, TimeUnit.SECONDS))
.submitOptions(options -> options.withDeadlineAfter(5, TimeUnit.SECONDS)) .submitOptions(options -> options.withDeadlineAfter(5, TimeUnit.SECONDS))
.commitStatusOptions(options -> options.withDeadlineAfter(1, TimeUnit.MINUTES)); .commitStatusOptions(options -> options.withDeadlineAfter(1, TimeUnit.MINUTES));
try (var gateway = builder.connect()) { try (var gateway = builder.connect()) {
System.out.println("LLEGO ACA 2");
this.setContract(gateway); this.setContract(gateway);
System.out.println("LLEGO ACA 3");
this.initLedger(); this.initLedger();
System.out.println("LLEGO ACA 4"); }
} /*finally {
channel.shutdownNow().awaitTermination(5, TimeUnit.SECONDS);
}*/
} }
private static ManagedChannel newGrpcConnection() throws IOException { private static ManagedChannel newGrpcConnection() throws IOException {
@ -93,7 +75,7 @@ public class RecetaService {
.build(); .build();
} }
private Identity newIdentity() throws IOException, CertificateException { private Identity newIdentity() throws IOException, CertificateException {
try (var certReader = Files.newBufferedReader(getFirstFilePath(CERT_DIR_PATH))) { try (var certReader = Files.newBufferedReader(getFirstFilePath(CERT_DIR_PATH))) {
var certificate = Identities.readX509Certificate(certReader); var certificate = Identities.readX509Certificate(certReader);
return new X509Identity(MSP_ID, certificate); return new X509Identity(MSP_ID, certificate);
@ -108,81 +90,54 @@ public class RecetaService {
} }
private void setContract(final Gateway gateway) { 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); var network = gateway.getNetwork(CHANNEL_NAME);
// Get the smart contract from the network.
contract = network.getContract(CHAINCODE_NAME); contract = network.getContract(CHAINCODE_NAME);
} }
private void initLedger() throws EndorseException, SubmitException, CommitStatusException, CommitException { 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"); contract.submitTransaction("InitLedger");
System.out.println("*** Transaction committed successfully");
} }
public void cargarReceta(Receta receta) throws CommitStatusException, EndorseException, CommitException, SubmitException { 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(
"CreateReceta",
contract.submitTransaction( receta.getId(),
"CreateAsset", receta.getOwner(),
receta.getId(), receta.getPrescripcionAnteriorId(),
receta.getOwner(), receta.getStatus(),
receta.getPrescripcionAnteriorId(), receta.getStatusChange(),
receta.getStatus(), receta.getPrioridad(),
receta.getStatusChange(), receta.getMedicacion(),
receta.getPrioridad(), receta.getRazon(),
receta.getMedicacion(), receta.getNotas(),
receta.getRazon(), receta.getPeriodoDeTratamiento(),
receta.getNotas(), receta.getInstruccionesTratamiento(),
receta.getPeriodoDeTratamiento(), receta.getPeriodoDeValidez(),
receta.getInstruccionesTratamiento(), receta.getDniPaciente(),
receta.getPeriodoDeValidez(), receta.getFechaDeAutorizacion(),
receta.getDniPaciente(), Integer.toString(receta.getCantidad()),
receta.getFechaDeAutorizacion(), receta.getExpectedSupplyDuration()
Integer.toString(receta.getCantidad()), );
receta.getExpectedSupplyDuration()
);
System.out.println("*** Transaction committed successfully");
} }
public Receta obtenerReceta(String assetId) throws GatewayException, IOException { public Receta obtenerReceta(String recetaId) throws GatewayException, IOException {
System.out.println("\n--> Evaluate Transaction: ReadAsset, function returns asset attributes"); var evaluateResult = contract.evaluateTransaction("ReadReceta", recetaId);
System.out.println("assetId: " + assetId);
var evaluateResult = contract.evaluateTransaction("ReadAsset", assetId);
System.out.println("evaluate");
ObjectMapper objectMapper = new ObjectMapper(); ObjectMapper objectMapper = new ObjectMapper();
var receta = objectMapper.readValue(evaluateResult, Receta.class); return objectMapper.readValue(evaluateResult, Receta.class);
System.out.println("mapper:" + receta.getDniPaciente());
return receta;
} }
public List<Receta> obtenerTodosLosAssets() throws GatewayException, IOException { public List<Receta> obtenerTodasLasRecetas() throws GatewayException, IOException {
System.out.println("\n--> Evaluate Transaction: GetAllAssets"); var evaluateResult = contract.evaluateTransaction("GetAllRecetas");
var evaluateResult = contract.evaluateTransaction("GetAllAssets");
ObjectMapper objectMapper = new ObjectMapper(); ObjectMapper objectMapper = new ObjectMapper();
return objectMapper.readValue(evaluateResult,
// Leer como array de Recetas objectMapper.getTypeFactory().constructCollectionType(List.class, Receta.class));
List<Receta> recetas = objectMapper.readValue(evaluateResult,
objectMapper.getTypeFactory().constructCollectionType(List.class, Receta.class));
return recetas;
} }
public List<Receta> obtenerRecetasPorIds(List<String> assetIds) throws GatewayException, IOException { public List<Receta> obtenerRecetasPorIds(List<String> recetaIds) throws GatewayException, IOException {
System.out.println("\n--> Evaluate Transaction: GetMultipleAssets");
ObjectMapper objectMapper = new ObjectMapper(); ObjectMapper objectMapper = new ObjectMapper();
String idsJson = objectMapper.writeValueAsString(assetIds); String idsJson = objectMapper.writeValueAsString(recetaIds);
var evaluateResult = contract.evaluateTransaction("GetMultipleRecetas", idsJson);
var evaluateResult = contract.evaluateTransaction("GetMultipleAssets", idsJson); return objectMapper.readValue(evaluateResult,
return objectMapper.readValue(evaluateResult, objectMapper.getTypeFactory().constructCollectionType(List.class, Receta.class));
objectMapper.getTypeFactory().constructCollectionType(List.class, Receta.class));
} }
} }