Skip to content

Commit

Permalink
refactor: fixing codesmells from sonarcloud (#149)
Browse files Browse the repository at this point in the history
* refactor: fixing codesmells from sonarcloud

* refactor: fixing spotless

* refactor: adding mapper for minUtxo

* refactor: sonarcloud issue

* refactor: further code smells

* refactor: added break
  • Loading branch information
Kammerlo committed May 8, 2024
1 parent 40e62d9 commit bc72d97
Show file tree
Hide file tree
Showing 19 changed files with 52 additions and 66 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ public class BlockTx {
protected String hash;
protected String blockHash;
protected Long blockNo;
protected String fee; // TODO can be removed if we found another way to calculate the size
protected String fee;
protected Long size;
protected Long scriptSize;
protected List<Utxo> inputs;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@ public class ProtocolParams {
private ExtraEntropy extraEntropy; //13
private ProtocolVersion protocolVersion; //14
@JsonProperty("minUTxOValue")
private BigInteger minUtxo; //TODO //15
private BigInteger minUtxoValue; //15

private BigInteger minPoolCost; //16
private BigInteger adaPerUtxoByte; //17
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@ public class ProtocolParamsEntity {
private String extraEntropy; //13
private Integer protocolMajorVer; //14
private Integer protocolMinorVer; //14
private BigInteger minUtxo; //TODO //15
private BigInteger minUtxo; //15

private BigInteger minPoolCost; //16
private BigInteger adaPerUtxoByte; //17
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,7 @@
import java.io.IOException;

import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.PostMapping;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.media.Content;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
Expand All @@ -28,8 +27,7 @@ public interface NetworkApiDelegate {
@ApiResponse(responseCode = "400", description = "Invalid `body`")
}
)
@RequestMapping(
method = RequestMethod.POST,
@PostMapping(
value = "/network/list",
produces = { "application/json;charset=utf-8" },
consumes = { "application/json;charset=utf-8" }
Expand All @@ -45,8 +43,7 @@ ResponseEntity<NetworkListResponse> networkList(MetadataRequest metadataRequest)
@ApiResponse(responseCode = "400", description = "Invalid `body`")
}
)
@RequestMapping(
method = RequestMethod.POST,
@PostMapping(
value = "/network/options",
produces = { "application/json;charset=utf-8" },
consumes = { "application/json;charset=utf-8" }
Expand All @@ -62,8 +59,7 @@ ResponseEntity<NetworkOptionsResponse> networkOptions(NetworkRequest networkRequ
@ApiResponse(responseCode = "400", description = "Invalid `body`")
}
)
@RequestMapping(
method = RequestMethod.POST,
@PostMapping(
value = "/network/status",
produces = { "application/json;charset=utf-8" },
consumes = { "application/json;charset=utf-8" }
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,6 @@
import org.cardanofoundation.rosetta.common.enumeration.OperationType;
import org.cardanofoundation.rosetta.common.enumeration.OperationTypeStatus;
import org.cardanofoundation.rosetta.common.exception.ExceptionFactory;
import org.cardanofoundation.rosetta.common.exception.ServerException;
import org.cardanofoundation.rosetta.common.mapper.DataMapper;
import org.cardanofoundation.rosetta.common.model.cardano.network.Producer;
import org.cardanofoundation.rosetta.common.model.cardano.network.PublicRoot;
Expand Down Expand Up @@ -64,13 +63,12 @@ public class NetworkServiceImpl implements NetworkService {
private final ResourceLoader resourceLoader;

@PostConstruct
public void filePathExistingValidator() throws ServerException {
public void filePathExistingValidator() {
validator(topologyFilepath);
validator(genesisPath);
// validator(cardanoNodeVersion);
}

private void validator( String path) throws ServerException {
private void validator( String path) {
if(!new File(path).exists()) {
throw ExceptionFactory.configNotFoundException();
}
Expand Down Expand Up @@ -124,7 +122,6 @@ public NetworkOptionsResponse getNetworkOptions(NetworkRequest networkRequest)
.toList())
.historicalBalanceLookup(true)
.callMethods(new ArrayList<>())
// .balanceExemptions(loadExemptionsFile()) // TODO Removed to get it working clean - add balance exemptions
.mempoolCoins(false))
.build();
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -29,24 +29,23 @@ public ResponseEntity<Error> handleGlobalException(Exception exception,
}

Error errorResponse;

if (exception instanceof ApiException apiException) {

errorResponse = apiException.getError();

} else if ( exception instanceof MethodArgumentNotValidException methodArgumentNotValidException){
List<String> errors = methodArgumentNotValidException.getBindingResult().getFieldErrors()
.stream().map(FieldError::getDefaultMessage).toList();
errorResponse = RosettaErrorType.UNSPECIFIED_ERROR.toRosettaError(true,
Details.builder().message(
"An error occurred for request " + request.getRequestId() + ": "
+ errors ).build());
}
else {
errorResponse = RosettaErrorType.UNSPECIFIED_ERROR.toRosettaError(true,
Details.builder().message(
"An error occurred for request " + request.getRequestId() + ": "
+ exception.getMessage()).build());
switch (exception) {
case ApiException apiException:
errorResponse = apiException.getError();
break;
case MethodArgumentNotValidException methodArgumentNotValidException:
List<String> errors = methodArgumentNotValidException.getBindingResult().getFieldErrors()
.stream().map(FieldError::getDefaultMessage).toList();
errorResponse = RosettaErrorType.UNSPECIFIED_ERROR.toRosettaError(true,
Details.builder().message(
"An error occurred for request " + request.getRequestId() + ": "
+ errors ).build());
break;
default:
errorResponse = RosettaErrorType.UNSPECIFIED_ERROR.toRosettaError(true,
Details.builder().message(
"An error occurred for request " + request.getRequestId() + ": "
+ exception.getMessage()).build());
}

return new ResponseEntity<>(errorResponse, HttpStatus.INTERNAL_SERVER_ERROR);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,6 @@
import org.springframework.http.HttpMethod;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import org.cardanofoundation.rosetta.common.services.LoggingService;

Expand All @@ -28,14 +27,4 @@ public boolean preHandle(HttpServletRequest request, HttpServletResponse respons

return true;
}

@Override
public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {

}

@Override
public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {

}
}
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,8 @@

public class CborMapToOperation {

private CborMapToOperation() {}

public static Operation cborMapToOperation(Map operationMap) {
Operation operation = new Operation();

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,8 @@

public class CborMapToTransactionExtraData {

private CborMapToTransactionExtraData() {}

public static TransactionExtraData convertCborMapToTransactionExtraData(Map map) {
String transactionMetadataHex = getTransactionMetadataHexFromMap(map);

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -141,7 +141,7 @@ public static Amount mapAmount(String value, String symbol, Integer decimals,
amount.setCurrency(Currency.builder()
.symbol(symbol)
.decimals(decimals)
.metadata(metadata) // TODO check metadata for Amount
.metadata(metadata)
.build());
return amount;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,8 @@

public class OperationToCborMap {

private OperationToCborMap() {}

public static Map convertToCborMap(Operation operation) {
Map operationMap = new Map();
// fill with nested objects
Expand Down Expand Up @@ -441,8 +443,8 @@ private static DataItem objectToDataItem(Object metadata) {
Map map = new Map();
HashMap<String, Object> metadataMap = (HashMap<String, Object>) metadata;
metadataMap.forEach((key, value) -> {
if (value instanceof String) {
map.put(new UnicodeString(key), new UnicodeString((String) value));
if (value instanceof String valueString) {
map.put(new UnicodeString(key), new UnicodeString(valueString));
} else {
map.put(new UnicodeString(key), objectToDataItem(value));
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ public ProtocolParams fromEntity(ProtocolParamsEntity entity){
mapper.map(ProtocolParamsEntity::getMaxBlockSize, ProtocolParams::setMaxBlockBodySize);
mapper.<Integer>map(ProtocolParamsEntity::getProtocolMajorVer, (dest, v) -> dest.getProtocolVersion().setMajor(v));
mapper.<Integer>map(ProtocolParamsEntity::getProtocolMinorVer, (dest, v) -> dest.getProtocolVersion().setMinor(v));
mapper.map(ProtocolParamsEntity::getMinUtxo, ProtocolParams::setMinUtxoValue);
})
.map(entity);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -81,7 +81,7 @@ private String toIndentedString(Object o) {

public ProtocolParameters fromEntity(ProtocolParams entity) {
return ProtocolParameters.builder()
.coinsPerUtxoSize(entity.getAdaPerUtxoByte().toString()) // TODO check if it's the right value
.coinsPerUtxoSize(entity.getAdaPerUtxoByte().toString())
.maxTxSize(entity.getMaxTxSize())
.maxValSize(BigInteger.valueOf(entity.getMaxValSize()))
.keyDeposit(entity.getKeyDeposit().toString())
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -69,9 +69,9 @@ private Map<String, String> buildParametersMap(HttpServletRequest httpServletReq
private Map<String, String> buildHeadersMap(HttpServletRequest request) {
Map<String, String> map = new HashMap<>();

Enumeration headerNames = request.getHeaderNames();
Enumeration<String> headerNames = request.getHeaderNames();
while (headerNames.hasMoreElements()) {
String key = (String) headerNames.nextElement();
String key = headerNames.nextElement();
String value = request.getHeader(key);
map.put(key, value);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -233,13 +233,11 @@ public static PoolRegistationParametersReturn validateAndParsePoolRegistationPar
}
}
try {
PoolRegistationParametersReturn poolRegistationParametersReturnDto = new PoolRegistationParametersReturn(
return new PoolRegistationParametersReturn(
valueOf(Long.parseLong(poolRegistrationParameters.getCost())),
valueOf(Long.parseLong(poolRegistrationParameters.getPledge())),
valueOf(Long.parseLong(numerator)),
valueOf(Long.parseLong(denominator)));

return poolRegistationParametersReturnDto;
} catch (Exception error) {
log.error("[validateAndParsePoolRegistationParameters] Given pool parameters are invalid");
throw ExceptionFactory.invalidPoolRegistrationParameters(error.getMessage());
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -269,7 +269,7 @@ void toDto_Test_getOutputsAsOperations() {

assertThat(opInto.getRelatedOperations()).isNotNull();
assertThat(opInto.getRelatedOperations().size()).isEqualTo(1);
assertThat(opInto.getRelatedOperations().getFirst().getIndex()).isEqualTo(0);
assertThat(opInto.getRelatedOperations().getFirst().getIndex()).isZero();

CoinChange coinChange = opInto.getCoinChange();
assertThat(coinChange.getCoinAction()).isEqualTo(CoinAction.CREATED);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,19 +14,19 @@
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;

public class NetworkServiceImplTest extends IntegrationTest {
class NetworkServiceImplTest extends IntegrationTest {

@Autowired
private NetworkService networkService;

@Test
public void verifyCorrectNetworkTest() {
void verifyCorrectNetworkTest() {
// void function, no exception expected
networkService.verifyNetworkRequest(createNetworkIdentifier(Constants.CARDANO_BLOCKCHAIN, Constants.DEVKIT));
}

@Test
public void verifyWrongNetworkTest() {
void verifyWrongNetworkTest() {
ApiException apiException = assertThrows(ApiException.class,
() -> networkService.verifyNetworkRequest(createNetworkIdentifier(Constants.CARDANO_BLOCKCHAIN,
Constants.MAINNET)));
Expand All @@ -35,7 +35,7 @@ public void verifyWrongNetworkTest() {
}

@Test
public void verifyWrongBlockchainTest() {
void verifyWrongBlockchainTest() {
ApiException apiException = assertThrows(ApiException.class,
() -> networkService.verifyNetworkRequest(createNetworkIdentifier("Wrong Blockchain",
Constants.DEVKIT)));
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -130,7 +130,7 @@ private void assertProtocolParameters(ProtocolParams into, ProtocolParamsEntity
assertThat(into.getMinFeeA()).isEqualTo(param.getMinFeeA());
assertThat(into.getMinFeeB()).isEqualTo(param.getMinFeeB());
assertThat(into.getMinPoolCost()).isEqualTo(param.getMinPoolCost());
assertThat(into.getMinUtxo()).isEqualTo(param.getMinUtxo());
assertThat(into.getMinUtxoValue()).isEqualTo(param.getMinUtxo());
assertThat(into.getNOpt()).isEqualTo(param.getNOpt());
assertThat(into.getPoolDeposit()).isEqualTo(param.getPoolDeposit());
assertThat(into.getPoolPledgeInfluence()).isEqualTo(param.getPoolPledgeInfluence());
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -247,9 +247,9 @@ void submitTransactionTest_tx_error() {
} catch (ApiException e) {
//then
Error error = e.getError();
assertEquals(error.getCode(), 5006);
assertEquals(error.getMessage(), "Error when sending the transaction");
assertEquals(error.getDescription(), "Transaction hash format error: err");
assertEquals(5006, error.getCode());
assertEquals("Error when sending the transaction", error.getMessage());
assertEquals("Transaction hash format error: err", error.getDescription());
}
}

Expand All @@ -266,9 +266,9 @@ void submitTransactionTest_tx_submit_error() {
} catch (ApiException e) {
//then
Error error = e.getError();
assertEquals(error.getCode(), 5006);
assertEquals(error.getMessage(), "Error when sending the transaction");
assertEquals(error.getDescription(), "Transaction submit error: err");
assertEquals(5006, error.getCode());
assertEquals("Error when sending the transaction", error.getMessage());
assertEquals("Transaction submit error: err", error.getDescription());
}
}

Expand Down

0 comments on commit bc72d97

Please sign in to comment.