From 5798c6944994d1c73b54b0f1b9b3e5b71f78cd8a Mon Sep 17 00:00:00 2001 From: catbref Date: Tue, 15 Oct 2019 17:10:13 +0100 Subject: [PATCH] Code clean-up thanks to SonarLint & bugfix for ByteArray::compareTo! --- src/main/java/org/hsqldb/jdbc/HSQLDBPool.java | 1 - src/main/java/org/qora/ApplyUpdate.java | 5 +- src/main/java/org/qora/ProxyKeys.java | 9 ++- src/main/java/org/qora/VanityGen.java | 13 ++-- src/main/java/org/qora/XorUpdate.java | 2 +- src/main/java/org/qora/account/Account.java | 4 +- src/main/java/org/qora/api/ApiError.java | 2 +- src/main/java/org/qora/api/ApiException.java | 6 +- src/main/java/org/qora/api/ApiService.java | 1 - .../api/TransactionCountMapXmlAdapter.java | 6 +- .../org/qora/api/model/ActivitySummary.java | 5 +- .../qora/api/resource/AddressesResource.java | 1 - .../org/qora/api/resource/AdminResource.java | 19 +++--- .../api/resource/AnnotationPostProcessor.java | 2 +- .../org/qora/api/resource/AssetsResource.java | 2 +- .../org/qora/api/resource/GroupsResource.java | 12 +--- .../org/qora/api/resource/NamesResource.java | 4 +- .../org/qora/api/resource/PeersResource.java | 2 +- .../api/resource/TransactionsResource.java | 2 +- src/main/java/org/qora/asset/Order.java | 13 ++-- src/main/java/org/qora/at/AT.java | 10 +-- src/main/java/org/qora/at/BlockchainAPI.java | 2 +- src/main/java/org/qora/at/QoraATAPI.java | 2 +- src/main/java/org/qora/at/QoraATLogger.java | 1 - .../java/org/qora/at/QoraFunctionCode.java | 14 ++--- .../java/org/qora/block/BlockGenerator.java | 28 +++------ .../java/org/qora/block/GenesisBlock.java | 20 +++--- src/main/java/org/qora/brokenmd160.java | 2 +- .../qora/controller/ArbitraryDataManager.java | 4 +- .../java/org/qora/controller/AutoUpdate.java | 5 +- .../java/org/qora/controller/Controller.java | 62 +++++++++---------- .../org/qora/controller/Synchronizer.java | 4 +- src/main/java/org/qora/crosschain/BTC.java | 7 +-- .../java/org/qora/crypto/BrokenMD160.java | 2 +- .../java/org/qora/data/voting/PollData.java | 2 - .../org/qora/globalization/BIP39WordList.java | 4 +- src/main/java/org/qora/group/Group.java | 2 +- src/main/java/org/qora/gui/SplashFrame.java | 2 +- src/main/java/org/qora/gui/SysTray.java | 52 ++++++---------- src/main/java/org/qora/mintsim.java | 6 +- src/main/java/org/qora/network/Handshake.java | 2 +- src/main/java/org/qora/network/Network.java | 40 +++++------- src/main/java/org/qora/network/Peer.java | 9 ++- .../org/qora/network/message/Message.java | 14 ++--- .../qora/network/message/PeersV2Message.java | 7 ++- .../qora/network/message/VersionMessage.java | 3 +- src/main/java/org/qora/payment/Payment.java | 2 +- .../repository/hsqldb/HSQLDBATRepository.java | 2 +- .../hsqldb/HSQLDBAccountRepository.java | 2 +- .../hsqldb/HSQLDBAssetRepository.java | 16 ++--- .../hsqldb/HSQLDBBlockRepository.java | 2 +- .../hsqldb/HSQLDBDatabaseUpdates.java | 6 +- .../hsqldb/HSQLDBGroupRepository.java | 4 +- .../repository/hsqldb/HSQLDBRepository.java | 44 +++++++------ .../hsqldb/HSQLDBRepositoryFactory.java | 11 ++-- .../qora/repository/hsqldb/HSQLDBSaver.java | 4 +- .../hsqldb/HSQLDBVotingRepository.java | 4 +- .../HSQLDBArbitraryTransactionRepository.java | 1 + ...HSQLDBCreatePollTransactionRepository.java | 2 +- .../HSQLDBTransactionRepository.java | 39 +++++------- src/main/java/org/qora/settings/Settings.java | 6 +- .../transaction/ArbitraryTransaction.java | 4 +- .../org/qora/transaction/AtTransaction.java | 2 +- .../CancelAssetOrderTransaction.java | 2 +- .../CancelSellNameTransaction.java | 2 +- .../CreateAssetOrderTransaction.java | 2 +- .../qora/transaction/DeployAtTransaction.java | 39 +++++------- .../qora/transaction/MessageTransaction.java | 2 +- .../transaction/MultiPaymentTransaction.java | 4 +- .../qora/transaction/SellNameTransaction.java | 2 +- .../org/qora/transaction/Transaction.java | 54 ++++++++-------- .../transaction/VoteOnPollTransaction.java | 8 +-- .../qora/transform/PaymentTransformer.java | 1 - .../transform/block/BlockTransformer.java | 6 +- .../ArbitraryTransactionTransformer.java | 7 ++- .../CreatePollTransactionTransformer.java | 2 +- .../DeployAtTransactionTransformer.java | 7 ++- .../MessageTransactionTransformer.java | 3 +- .../MultiPaymentTransactionTransformer.java | 2 +- .../UpdateAssetTransactionTransformer.java | 4 +- src/main/java/org/qora/utils/BIP39.java | 2 +- src/main/java/org/qora/utils/ByteArray.java | 4 +- src/main/java/org/qora/utils/NTP.java | 6 +- .../java/org/qora/utils/Serialization.java | 9 +-- .../qora/utils/StringLongMapXmlAdapter.java | 2 +- .../java/org/qora/test/ByteArrayTests.java | 10 +++ 86 files changed, 347 insertions(+), 401 deletions(-) diff --git a/src/main/java/org/hsqldb/jdbc/HSQLDBPool.java b/src/main/java/org/hsqldb/jdbc/HSQLDBPool.java index ce130eee..b7cdf653 100644 --- a/src/main/java/org/hsqldb/jdbc/HSQLDBPool.java +++ b/src/main/java/org/hsqldb/jdbc/HSQLDBPool.java @@ -3,7 +3,6 @@ package org.hsqldb.jdbc; import java.sql.Connection; import java.sql.SQLException; -import org.hsqldb.jdbc.JDBCPool; import org.hsqldb.jdbc.pool.JDBCPooledConnection; public class HSQLDBPool extends JDBCPool { diff --git a/src/main/java/org/qora/ApplyUpdate.java b/src/main/java/org/qora/ApplyUpdate.java index c42dbb53..9ba5697e 100644 --- a/src/main/java/org/qora/ApplyUpdate.java +++ b/src/main/java/org/qora/ApplyUpdate.java @@ -34,10 +34,10 @@ public class ApplyUpdate { private static final String NEW_JAR_FILENAME = AutoUpdate.NEW_JAR_FILENAME; private static final String WINDOWS_EXE_LAUNCHER = "qora-core.exe"; - private static final long CHECK_INTERVAL = 5 * 1000; // ms + private static final long CHECK_INTERVAL = 5 * 1000L; // ms private static final int MAX_ATTEMPTS = 5; - public static void main(String args[]) { + public static void main(String[] args) { Security.insertProviderAt(new BouncyCastleProvider(), 0); Security.insertProviderAt(new BouncyCastleJsseProvider(), 1); @@ -114,6 +114,7 @@ public class ApplyUpdate { try { Thread.sleep(CHECK_INTERVAL); } catch (InterruptedException e) { + // Doggedly retry } } diff --git a/src/main/java/org/qora/ProxyKeys.java b/src/main/java/org/qora/ProxyKeys.java index f1cecf1f..a27c3bc5 100644 --- a/src/main/java/org/qora/ProxyKeys.java +++ b/src/main/java/org/qora/ProxyKeys.java @@ -1,6 +1,5 @@ package org.qora; -import java.io.IOException; import java.security.Security; import org.bouncycastle.jce.provider.BouncyCastleProvider; @@ -17,15 +16,15 @@ public class ProxyKeys { System.exit(1); } - public static void main(String argv[]) throws IOException { - if (argv.length != 2) + public static void main(String[] args) { + if (args.length != 2) usage(); Security.insertProviderAt(new BouncyCastleProvider(), 0); Security.insertProviderAt(new BouncyCastleJsseProvider(), 1); - PrivateKeyAccount privateAccount = new PrivateKeyAccount(null, Base58.decode(argv[0])); - PublicKeyAccount publicAccount = new PublicKeyAccount(null, Base58.decode(argv[1])); + PrivateKeyAccount privateAccount = new PrivateKeyAccount(null, Base58.decode(args[0])); + PublicKeyAccount publicAccount = new PublicKeyAccount(null, Base58.decode(args[1])); byte[] proxyPrivateKey = privateAccount.getProxyPrivateKey(publicAccount.getPublicKey()); diff --git a/src/main/java/org/qora/VanityGen.java b/src/main/java/org/qora/VanityGen.java index 917501b5..54dfdf41 100644 --- a/src/main/java/org/qora/VanityGen.java +++ b/src/main/java/org/qora/VanityGen.java @@ -1,6 +1,5 @@ package org.qora; -import java.io.IOException; import java.security.SecureRandom; import java.security.Security; import java.util.Random; @@ -59,22 +58,22 @@ public class VanityGen { } } - public static void main(String argv[]) throws IOException { - if (argv.length == 0) + public static void main(String[] args) { + if (args.length == 0) usage(); int threadCount = 1; int argIndex = 0; - while (argIndex < argv.length) { - String arg = argv[argIndex++]; + while (argIndex < args.length) { + String arg = args[argIndex++]; if (arg.equals("-t")) { - if (argIndex >= argv.length) + if (argIndex >= args.length) usage(); try { - threadCount = Integer.parseInt(argv[argIndex++]); + threadCount = Integer.parseInt(args[argIndex++]); } catch (NumberFormatException e) { usage(); } diff --git a/src/main/java/org/qora/XorUpdate.java b/src/main/java/org/qora/XorUpdate.java index 1df8a7e3..553f8b44 100644 --- a/src/main/java/org/qora/XorUpdate.java +++ b/src/main/java/org/qora/XorUpdate.java @@ -13,7 +13,7 @@ public class XorUpdate { private static final byte XOR_VALUE = AutoUpdate.XOR_VALUE; - public static void main(String args[]) { + public static void main(String[] args) { if (args.length != 2) { System.err.println("usage: XorUpdate "); System.exit(1); diff --git a/src/main/java/org/qora/account/Account.java b/src/main/java/org/qora/account/Account.java index 60ea6a8f..d4df355e 100644 --- a/src/main/java/org/qora/account/Account.java +++ b/src/main/java/org/qora/account/Account.java @@ -142,9 +142,9 @@ public class Account { byte[] reference = null; for (TransactionData transactionData : unconfirmedTransactions) { - String address = PublicKeyAccount.getAddress(transactionData.getCreatorPublicKey()); + String unconfirmedTransactionAddress = PublicKeyAccount.getAddress(transactionData.getCreatorPublicKey()); - if (address.equals(this.address)) + if (unconfirmedTransactionAddress.equals(this.address)) reference = transactionData.getSignature(); } diff --git a/src/main/java/org/qora/api/ApiError.java b/src/main/java/org/qora/api/ApiError.java index ed475e22..17a5912c 100644 --- a/src/main/java/org/qora/api/ApiError.java +++ b/src/main/java/org/qora/api/ApiError.java @@ -118,7 +118,7 @@ public enum ApiError { // Groups GROUP_UNKNOWN(1101, 404); - private final static Map map = stream(ApiError.values()).collect(toMap(apiError -> apiError.code, apiError -> apiError)); + private static final Map map = stream(ApiError.values()).collect(toMap(apiError -> apiError.code, apiError -> apiError)); private final int code; // API error code private final int status; // HTTP status code diff --git a/src/main/java/org/qora/api/ApiException.java b/src/main/java/org/qora/api/ApiException.java index 4e32ce68..28d00551 100644 --- a/src/main/java/org/qora/api/ApiException.java +++ b/src/main/java/org/qora/api/ApiException.java @@ -10,12 +10,12 @@ public class ApiException extends WebApplicationException { private static final long serialVersionUID = 4619299036312089050L; // HTTP status code - public int status; + public final int status; // API error code - public int error; + public final int error; - public String message; + public final String message; public ApiException(int status, int error, String message) { this(status, error, message, null); diff --git a/src/main/java/org/qora/api/ApiService.java b/src/main/java/org/qora/api/ApiService.java index 709039ad..d0a3f0e7 100644 --- a/src/main/java/org/qora/api/ApiService.java +++ b/src/main/java/org/qora/api/ApiService.java @@ -47,7 +47,6 @@ public class ApiService { } public Iterable> getResources() { - // return resources; return this.config.getClasses(); } diff --git a/src/main/java/org/qora/api/TransactionCountMapXmlAdapter.java b/src/main/java/org/qora/api/TransactionCountMapXmlAdapter.java index 506a5e78..1be6a61a 100644 --- a/src/main/java/org/qora/api/TransactionCountMapXmlAdapter.java +++ b/src/main/java/org/qora/api/TransactionCountMapXmlAdapter.java @@ -1,7 +1,7 @@ package org.qora.api; import java.util.ArrayList; -import java.util.HashMap; +import java.util.EnumMap; import java.util.List; import java.util.Map; import java.util.Map.Entry; @@ -17,7 +17,7 @@ public class TransactionCountMapXmlAdapter extends XmlAdapter entries = new ArrayList(); + List entries = new ArrayList<>(); } public static class MapEntry { @@ -30,7 +30,7 @@ public class TransactionCountMapXmlAdapter extends XmlAdapter unmarshal(StringIntegerMap stringIntegerMap) throws Exception { - Map map = new HashMap<>(stringIntegerMap.entries.size()); + Map map = new EnumMap<>(TransactionType.class); for (MapEntry entry : stringIntegerMap.entries) map.put(TransactionType.valueOf(entry.key), entry.value); diff --git a/src/main/java/org/qora/api/model/ActivitySummary.java b/src/main/java/org/qora/api/model/ActivitySummary.java index 62a91e22..37cb566d 100644 --- a/src/main/java/org/qora/api/model/ActivitySummary.java +++ b/src/main/java/org/qora/api/model/ActivitySummary.java @@ -1,6 +1,6 @@ package org.qora.api.model; -import java.util.HashMap; +import java.util.EnumMap; import java.util.Map; import javax.xml.bind.annotation.XmlAccessType; @@ -20,9 +20,10 @@ public class ActivitySummary { // Assuming TransactionType values are contiguous so 'length' equals count @XmlJavaTypeAdapter(TransactionCountMapXmlAdapter.class) - public Map transactionCountByType = new HashMap<>(); + public Map transactionCountByType = new EnumMap<>(TransactionType.class); public ActivitySummary() { + // Needed for JAXB } } diff --git a/src/main/java/org/qora/api/resource/AddressesResource.java b/src/main/java/org/qora/api/resource/AddressesResource.java index d3783501..b4cd11a1 100644 --- a/src/main/java/org/qora/api/resource/AddressesResource.java +++ b/src/main/java/org/qora/api/resource/AddressesResource.java @@ -30,7 +30,6 @@ import org.qora.api.ApiException; import org.qora.api.ApiExceptionFactory; import org.qora.api.model.ApiOnlineAccount; import org.qora.api.model.ProxyKeyRequest; -import org.qora.api.resource.TransactionsResource; import org.qora.asset.Asset; import org.qora.controller.Controller; import org.qora.crypto.Crypto; diff --git a/src/main/java/org/qora/api/resource/AdminResource.java b/src/main/java/org/qora/api/resource/AdminResource.java index 2d36202f..ebea9e8b 100644 --- a/src/main/java/org/qora/api/resource/AdminResource.java +++ b/src/main/java/org/qora/api/resource/AdminResource.java @@ -134,18 +134,15 @@ public class AdminResource { public String shutdown() { Security.checkApiCallAllowed(request); - new Thread(new Runnable() { - @Override - public void run() { - // Short sleep to allow HTTP response body to be emitted - try { - Thread.sleep(1000); - } catch (InterruptedException e) { - // Not important - } - - Controller.getInstance().shutdownAndExit(); + new Thread(() -> { + // Short sleep to allow HTTP response body to be emitted + try { + Thread.sleep(1000); + } catch (InterruptedException e) { + // Not important } + + Controller.getInstance().shutdownAndExit(); }).start(); return "true"; diff --git a/src/main/java/org/qora/api/resource/AnnotationPostProcessor.java b/src/main/java/org/qora/api/resource/AnnotationPostProcessor.java index 9593c2a9..1e113dae 100644 --- a/src/main/java/org/qora/api/resource/AnnotationPostProcessor.java +++ b/src/main/java/org/qora/api/resource/AnnotationPostProcessor.java @@ -66,7 +66,7 @@ public class AnnotationPostProcessor implements ReaderListener { if (apiErrors == null) continue; - LOGGER.trace("Found @ApiErrors annotation on " + clazz.getSimpleName() + "." + method.getName()); + LOGGER.trace(() -> String.format("Found @ApiErrors annotation on %s.%s", clazz.getSimpleName(), method.getName())); PathItem pathItem = getPathItemFromMethod(openAPI, classPathString, method); if (pathItem == null) { diff --git a/src/main/java/org/qora/api/resource/AssetsResource.java b/src/main/java/org/qora/api/resource/AssetsResource.java index 6b3577bf..ed75b383 100644 --- a/src/main/java/org/qora/api/resource/AssetsResource.java +++ b/src/main/java/org/qora/api/resource/AssetsResource.java @@ -282,7 +282,7 @@ public class AssetsResource { List orders = repository.getAssetRepository().getAggregatedOpenOrders(assetId, otherAssetId, limit, offset, reverse); // Map to aggregated form - return orders.stream().map(orderData -> new AggregatedOrder(orderData)).collect(Collectors.toList()); + return orders.stream().map(AggregatedOrder::new).collect(Collectors.toList()); } catch (DataException e) { throw ApiExceptionFactory.INSTANCE.createException(request, ApiError.REPOSITORY_ISSUE, e); } diff --git a/src/main/java/org/qora/api/resource/GroupsResource.java b/src/main/java/org/qora/api/resource/GroupsResource.java index ae7dec40..ae0ffa0c 100644 --- a/src/main/java/org/qora/api/resource/GroupsResource.java +++ b/src/main/java/org/qora/api/resource/GroupsResource.java @@ -98,9 +98,7 @@ public class GroupsResource { ref = "reverse" ) @QueryParam("reverse") Boolean reverse) { try (final Repository repository = RepositoryManager.getRepository()) { - List groups = repository.getGroupRepository().getAllGroups(limit, offset, reverse); - - return groups; + return repository.getGroupRepository().getAllGroups(limit, offset, reverse); } catch (DataException e) { throw ApiExceptionFactory.INSTANCE.createException(request, ApiError.REPOSITORY_ISSUE, e); } @@ -126,9 +124,7 @@ public class GroupsResource { throw ApiExceptionFactory.INSTANCE.createException(request, ApiError.INVALID_ADDRESS); try (final Repository repository = RepositoryManager.getRepository()) { - List groups = repository.getGroupRepository().getGroupsByOwner(owner); - - return groups; + return repository.getGroupRepository().getGroupsByOwner(owner); } catch (DataException e) { throw ApiExceptionFactory.INSTANCE.createException(request, ApiError.REPOSITORY_ISSUE, e); } @@ -154,9 +150,7 @@ public class GroupsResource { throw ApiExceptionFactory.INSTANCE.createException(request, ApiError.INVALID_ADDRESS); try (final Repository repository = RepositoryManager.getRepository()) { - List groups = repository.getGroupRepository().getGroupsWithMember(member); - - return groups; + return repository.getGroupRepository().getGroupsWithMember(member); } catch (DataException e) { throw ApiExceptionFactory.INSTANCE.createException(request, ApiError.REPOSITORY_ISSUE, e); } diff --git a/src/main/java/org/qora/api/resource/NamesResource.java b/src/main/java/org/qora/api/resource/NamesResource.java index 6da1fbde..20c6c44a 100644 --- a/src/main/java/org/qora/api/resource/NamesResource.java +++ b/src/main/java/org/qora/api/resource/NamesResource.java @@ -73,7 +73,7 @@ public class NamesResource { List names = repository.getNameRepository().getAllNames(limit, offset, reverse); // Convert to summary - return names.stream().map(nameData -> new NameSummary(nameData)).collect(Collectors.toList()); + return names.stream().map(NameSummary::new).collect(Collectors.toList()); } catch (DataException e) { throw ApiExceptionFactory.INSTANCE.createException(request, ApiError.REPOSITORY_ISSUE, e); } @@ -102,7 +102,7 @@ public class NamesResource { try (final Repository repository = RepositoryManager.getRepository()) { List names = repository.getNameRepository().getNamesByOwner(address, limit, offset, reverse); - return names.stream().map(nameData -> new NameSummary(nameData)).collect(Collectors.toList()); + return names.stream().map(NameSummary::new).collect(Collectors.toList()); } catch (DataException e) { throw ApiExceptionFactory.INSTANCE.createException(request, ApiError.REPOSITORY_ISSUE, e); } diff --git a/src/main/java/org/qora/api/resource/PeersResource.java b/src/main/java/org/qora/api/resource/PeersResource.java index 953c1edb..9193218d 100644 --- a/src/main/java/org/qora/api/resource/PeersResource.java +++ b/src/main/java/org/qora/api/resource/PeersResource.java @@ -56,7 +56,7 @@ public class PeersResource { } ) public List getPeers() { - return Network.getInstance().getConnectedPeers().stream().map(peer -> new ConnectedPeer(peer)).collect(Collectors.toList()); + return Network.getInstance().getConnectedPeers().stream().map(ConnectedPeer::new).collect(Collectors.toList()); } @GET diff --git a/src/main/java/org/qora/api/resource/TransactionsResource.java b/src/main/java/org/qora/api/resource/TransactionsResource.java index a1d16171..7e0cb784 100644 --- a/src/main/java/org/qora/api/resource/TransactionsResource.java +++ b/src/main/java/org/qora/api/resource/TransactionsResource.java @@ -311,7 +311,7 @@ public class TransactionsResource { txTypes, null, address, confirmationStatus, limit, offset, reverse); // Expand signatures to transactions - List transactions = new ArrayList(signatures.size()); + List transactions = new ArrayList<>(signatures.size()); for (byte[] signature : signatures) transactions.add(repository.getTransactionRepository().fromSignature(signature)); diff --git a/src/main/java/org/qora/asset/Order.java b/src/main/java/org/qora/asset/Order.java index f3b2c14a..1675d82f 100644 --- a/src/main/java/org/qora/asset/Order.java +++ b/src/main/java/org/qora/asset/Order.java @@ -229,14 +229,15 @@ public class Order { final boolean isOrderNewAssetPricing = orderData.getTimestamp() >= BlockChain.getInstance().getNewAssetPricingTimestamp(); - final long haveAssetId = orderData.getHaveAssetId(); - final long wantAssetId = orderData.getWantAssetId(); + // Cached for readability + final long _haveAssetId = orderData.getHaveAssetId(); + final long _wantAssetId = orderData.getWantAssetId(); - final AssetData haveAssetData = this.repository.getAssetRepository().fromAssetId(haveAssetId); - final AssetData wantAssetData = this.repository.getAssetRepository().fromAssetId(wantAssetId); + final AssetData haveAssetData = this.repository.getAssetRepository().fromAssetId(_haveAssetId); + final AssetData wantAssetData = this.repository.getAssetRepository().fromAssetId(_wantAssetId); - final long amountAssetId = (isOurOrderNewPricing && wantAssetId > haveAssetId) ? wantAssetId : haveAssetId; - final long returnAssetId = (isOurOrderNewPricing && haveAssetId < wantAssetId) ? haveAssetId : wantAssetId; + final long amountAssetId = (isOurOrderNewPricing && _wantAssetId > _haveAssetId) ? _wantAssetId : _haveAssetId; + final long returnAssetId = (isOurOrderNewPricing && _haveAssetId < _wantAssetId) ? _haveAssetId : _wantAssetId; final AssetData amountAssetData = this.repository.getAssetRepository().fromAssetId(amountAssetId); final AssetData returnAssetData = this.repository.getAssetRepository().fromAssetId(returnAssetId); diff --git a/src/main/java/org/qora/at/AT.java b/src/main/java/org/qora/at/AT.java index 2051f215..fcdfc208 100644 --- a/src/main/java/org/qora/at/AT.java +++ b/src/main/java/org/qora/at/AT.java @@ -45,7 +45,7 @@ public class AT { byte[] creationBytes = deployATTransactionData.getCreationBytes(); long assetId = deployATTransactionData.getAssetId(); - short version = (short) (creationBytes[0] | (creationBytes[1] << 8)); // Little-endian + short version = (short) ((creationBytes[0] & 0xff) | (creationBytes[1] << 8)); // Little-endian if (version >= 2) { MachineState machineState = new MachineState(deployATTransactionData.getCreationBytes()); @@ -78,7 +78,7 @@ public class AT { // Extract actual code length, stored in minimal-size form (byte, short or int) if (numCodePages * 256 < 257) { - codeLen = (int) (byteBuffer.get() & 0xff); + codeLen = byteBuffer.get() & 0xff; } else if (numCodePages * 256 < Short.MAX_VALUE + 1) { codeLen = byteBuffer.getShort() & 0xffff; } else if (numCodePages * 256 <= Integer.MAX_VALUE) { @@ -135,14 +135,14 @@ public class AT { byte[] codeBytes = this.atData.getCodeBytes(); // Fetch latest ATStateData for this AT (if any) - ATStateData atStateData = this.repository.getATRepository().getLatestATState(atAddress); + ATStateData latestAtStateData = this.repository.getATRepository().getLatestATState(atAddress); // There should be at least initial AT state data - if (atStateData == null) + if (latestAtStateData == null) throw new IllegalStateException("No initial AT state data found"); // [Re]create AT machine state using AT state data or from scratch as applicable - MachineState state = MachineState.fromBytes(api, logger, atStateData.getStateData(), codeBytes); + MachineState state = MachineState.fromBytes(api, logger, latestAtStateData.getStateData(), codeBytes); state.execute(); int height = this.repository.getBlockRepository().getBlockchainHeight() + 1; diff --git a/src/main/java/org/qora/at/BlockchainAPI.java b/src/main/java/org/qora/at/BlockchainAPI.java index 4a863902..60db2337 100644 --- a/src/main/java/org/qora/at/BlockchainAPI.java +++ b/src/main/java/org/qora/at/BlockchainAPI.java @@ -115,7 +115,7 @@ public enum BlockchainAPI { public final int value; - private final static Map map = stream(BlockchainAPI.values()).collect(toMap(type -> type.value, type -> type)); + private static final Map map = stream(BlockchainAPI.values()).collect(toMap(type -> type.value, type -> type)); BlockchainAPI(int value) { this.value = value; diff --git a/src/main/java/org/qora/at/QoraATAPI.java b/src/main/java/org/qora/at/QoraATAPI.java index dd923083..e001f919 100644 --- a/src/main/java/org/qora/at/QoraATAPI.java +++ b/src/main/java/org/qora/at/QoraATAPI.java @@ -52,7 +52,7 @@ public class QoraATAPI extends API { public QoraATAPI(Repository repository, ATData atData, long blockTimestamp) { this.repository = repository; this.atData = atData; - this.transactions = new ArrayList(); + this.transactions = new ArrayList<>(); this.blockTimestamp = blockTimestamp; } diff --git a/src/main/java/org/qora/at/QoraATLogger.java b/src/main/java/org/qora/at/QoraATLogger.java index 6952928f..cc4bf527 100644 --- a/src/main/java/org/qora/at/QoraATLogger.java +++ b/src/main/java/org/qora/at/QoraATLogger.java @@ -2,7 +2,6 @@ package org.qora.at; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; -import org.qora.at.AT; public class QoraATLogger implements org.ciyam.at.LoggerInterface { diff --git a/src/main/java/org/qora/at/QoraFunctionCode.java b/src/main/java/org/qora/at/QoraFunctionCode.java index 86f134c3..b2b63d78 100644 --- a/src/main/java/org/qora/at/QoraFunctionCode.java +++ b/src/main/java/org/qora/at/QoraFunctionCode.java @@ -1,6 +1,6 @@ package org.qora.at; -import java.io.UnsupportedEncodingException; +import java.nio.charset.StandardCharsets; import java.util.Arrays; import java.util.Map; import java.util.stream.Collectors; @@ -37,14 +37,10 @@ public enum QoraFunctionCode { protected void postCheckExecute(FunctionData functionData, MachineState state, short rawFunctionCode) throws ExecutionException { Timestamp timestamp = new Timestamp(functionData.value2); - try { - String recipient = new String(state.getB(), "UTF-8"); + String recipient = new String(state.getB(), StandardCharsets.UTF_8); - BlockchainAPI blockchainAPI = BlockchainAPI.valueOf(timestamp.blockchainId); - blockchainAPI.putTransactionFromRecipientAfterTimestampInA(recipient, timestamp, state); - } catch (UnsupportedEncodingException e) { - throw new ExecutionException("Couldn't parse recipient from B", e); - } + BlockchainAPI blockchainAPI = BlockchainAPI.valueOf(timestamp.blockchainId); + blockchainAPI.putTransactionFromRecipientAfterTimestampInA(recipient, timestamp, state); } }; @@ -102,6 +98,6 @@ public enum QoraFunctionCode { } /** Actually execute function */ - abstract protected void postCheckExecute(FunctionData functionData, MachineState state, short rawFunctionCode) throws ExecutionException; + protected abstract void postCheckExecute(FunctionData functionData, MachineState state, short rawFunctionCode) throws ExecutionException; } diff --git a/src/main/java/org/qora/block/BlockGenerator.java b/src/main/java/org/qora/block/BlockGenerator.java index 17b08655..cbf3431a 100644 --- a/src/main/java/org/qora/block/BlockGenerator.java +++ b/src/main/java/org/qora/block/BlockGenerator.java @@ -2,6 +2,7 @@ package org.qora.block; import java.util.ArrayList; import java.util.Arrays; +import java.util.Iterator; import java.util.List; import java.util.Random; import java.util.concurrent.locks.ReentrantLock; @@ -204,7 +205,7 @@ public class BlockGenerator extends Thread { ValidationResult validationResult = newBlock.isValid(); if (validationResult != ValidationResult.OK) { // No longer valid? Report and discard - LOGGER.error("Valid, generated block now invalid '" + validationResult.name() + "' after adding unconfirmed transactions?"); + LOGGER.error(String.format("Valid, generated block now invalid '%s' after adding unconfirmed transactions?", validationResult.name())); // Rebuild block candidates, just to be sure newBlocks.clear(); @@ -215,7 +216,7 @@ public class BlockGenerator extends Thread { try { newBlock.process(); - LOGGER.info("Generated new block: " + newBlock.getBlockData().getHeight()); + LOGGER.info(String.format("Generated new block: %d", newBlock.getBlockData().getHeight())); repository.saveChanges(); ProxyForgerData proxyForgerData = repository.getAccountRepository().getProxyForgeData(newBlock.getBlockData().getGeneratorPublicKey()); @@ -292,24 +293,15 @@ public class BlockGenerator extends Thread { // Grab all valid unconfirmed transactions (already sorted) List unconfirmedTransactions = Transaction.getUnconfirmedTransactions(repository); - for (int i = 0; i < unconfirmedTransactions.size(); ++i) { - TransactionData transactionData = unconfirmedTransactions.get(i); + Iterator unconfirmedTransactionsIterator = unconfirmedTransactions.iterator(); + final long newBlockTimestamp = newBlock.getBlockData().getTimestamp(); + while (unconfirmedTransactionsIterator.hasNext()) { + TransactionData transactionData = unconfirmedTransactionsIterator.next(); // Ignore transactions that have timestamp later than block's timestamp (not yet valid) - if (transactionData.getTimestamp() > newBlock.getBlockData().getTimestamp()) { - unconfirmedTransactions.remove(i); - --i; - continue; - } - - Transaction transaction = Transaction.fromData(repository, transactionData); - // Ignore transactions that have expired before this block - they will be cleaned up later - if (transaction.getDeadline() <= newBlock.getBlockData().getTimestamp()) { - unconfirmedTransactions.remove(i); - --i; - continue; - } + if (transactionData.getTimestamp() > newBlockTimestamp || Transaction.getDeadline(transactionData) <= newBlockTimestamp) + unconfirmedTransactionsIterator.remove(); } // Sign to create block's signature, needed by Block.isValid() @@ -324,7 +316,7 @@ public class BlockGenerator extends Thread { // If newBlock is no longer valid then we can't use transaction ValidationResult validationResult = newBlock.isValid(); if (validationResult != ValidationResult.OK) { - LOGGER.debug("Skipping invalid transaction " + Base58.encode(transactionData.getSignature()) + " during block generation"); + LOGGER.debug(() -> String.format("Skipping invalid transaction %s during block generation", Base58.encode(transactionData.getSignature()))); newBlock.deleteTransaction(transactionData); } } diff --git a/src/main/java/org/qora/block/GenesisBlock.java b/src/main/java/org/qora/block/GenesisBlock.java index 770d8eba..2fdbb47e 100644 --- a/src/main/java/org/qora/block/GenesisBlock.java +++ b/src/main/java/org/qora/block/GenesisBlock.java @@ -54,7 +54,7 @@ public class GenesisBlock extends Block { } // Properties - private static BlockData blockData; + private static BlockData genesisBlockData; private static List transactionsData; private static List initialAssets; @@ -65,7 +65,7 @@ public class GenesisBlock extends Block { } public static GenesisBlock getInstance(Repository repository) throws DataException { - return new GenesisBlock(repository, blockData, transactionsData); + return new GenesisBlock(repository, genesisBlockData, transactionsData); } // Construction from JSON @@ -73,7 +73,7 @@ public class GenesisBlock extends Block { /** Construct block data from blockchain config */ public static void newInstance(GenesisInfo info) { // Should be safe to make this call as BlockChain's instance is set - // so we won't be blocked trying to re-enter synchronzied Settings.getInstance() + // so we won't be blocked trying to re-enter synchronized Settings.getInstance() BlockChain blockchain = BlockChain.getInstance(); // Timestamp of zero means "now" but only valid for test nets! @@ -87,7 +87,7 @@ public class GenesisBlock extends Block { info.timestamp = System.currentTimeMillis(); } - transactionsData = new ArrayList(Arrays.asList(info.transactions)); + transactionsData = new ArrayList<>(Arrays.asList(info.transactions)); // Add default values to transactions transactionsData.stream().forEach(transactionData -> { @@ -133,7 +133,7 @@ public class GenesisBlock extends Block { int atCount = 0; BigDecimal atFees = BigDecimal.ZERO.setScale(8); - blockData = new BlockData(info.version, reference, transactionCount, totalFees, transactionsSignature, height, info.timestamp, + genesisBlockData = new BlockData(info.version, reference, transactionCount, totalFees, transactionsSignature, height, info.timestamp, generatorPublicKey, generatorSignature, atCount, atFees); } @@ -246,14 +246,14 @@ public class GenesisBlock extends Block { @Override public boolean isSignatureValid() { - byte[] signature = calcSignature(this.getBlockData()); + byte[] signature = calcSignature(this.blockData); // Validate block signature - if (!Arrays.equals(signature, this.getBlockData().getGeneratorSignature())) + if (!Arrays.equals(signature, this.blockData.getGeneratorSignature())) return false; // Validate transactions signature - if (!Arrays.equals(signature, this.getBlockData().getTransactionsSignature())) + if (!Arrays.equals(signature, this.blockData.getTransactionsSignature())) return false; return true; @@ -275,10 +275,10 @@ public class GenesisBlock extends Block { @Override public void process() throws DataException { - LOGGER.info(String.format("Using genesis block timestamp of %d", blockData.getTimestamp())); + LOGGER.info(String.format("Using genesis block timestamp of %d", this.blockData.getTimestamp())); // If we're a version 1 genesis block, create assets now - if (blockData.getVersion() == 1) + if (this.blockData.getVersion() == 1) for (AssetData assetData : initialAssets) repository.getAssetRepository().save(assetData); diff --git a/src/main/java/org/qora/brokenmd160.java b/src/main/java/org/qora/brokenmd160.java index 729dcd81..a67198fa 100644 --- a/src/main/java/org/qora/brokenmd160.java +++ b/src/main/java/org/qora/brokenmd160.java @@ -6,7 +6,7 @@ import com.google.common.hash.HashCode; @SuppressWarnings("deprecation") public class brokenmd160 { - public static void main(String args[]) { + public static void main(String[] args) { if (args.length == 0) { System.err.println("usage: broken-md160 \noutputs: hex"); System.exit(1); diff --git a/src/main/java/org/qora/controller/ArbitraryDataManager.java b/src/main/java/org/qora/controller/ArbitraryDataManager.java index dbc37938..893b915e 100644 --- a/src/main/java/org/qora/controller/ArbitraryDataManager.java +++ b/src/main/java/org/qora/controller/ArbitraryDataManager.java @@ -64,7 +64,7 @@ public class ArbitraryDataManager extends Thread { } } } catch (InterruptedException e) { - return; + // Fall-through to exit thread... } } @@ -76,7 +76,7 @@ public class ArbitraryDataManager extends Thread { private boolean hasLocalData(final Repository repository, final byte[] signature) { try { TransactionData transactionData = repository.getTransactionRepository().fromSignature(signature); - if (transactionData == null || !(transactionData instanceof ArbitraryTransactionData)) + if (!(transactionData instanceof ArbitraryTransactionData)) return true; ArbitraryTransaction arbitraryTransaction = new ArbitraryTransaction(repository, transactionData); diff --git a/src/main/java/org/qora/controller/AutoUpdate.java b/src/main/java/org/qora/controller/AutoUpdate.java index e2dec23d..6c9f056d 100644 --- a/src/main/java/org/qora/controller/AutoUpdate.java +++ b/src/main/java/org/qora/controller/AutoUpdate.java @@ -39,7 +39,7 @@ public class AutoUpdate extends Thread { public static final String NEW_JAR_FILENAME = "new-" + JAR_FILENAME; private static final Logger LOGGER = LogManager.getLogger(AutoUpdate.class); - private static final long CHECK_INTERVAL = 5 * 60 * 1000; // ms + private static final long CHECK_INTERVAL = 5 * 60 * 1000L; // ms private static final int DEV_GROUP_ID = 1; private static final int UPDATE_SERVICE = 1; @@ -65,6 +65,7 @@ public class AutoUpdate extends Thread { return instance; } + @Override public void run() { Thread.currentThread().setName("Auto-update"); @@ -94,7 +95,7 @@ public class AutoUpdate extends Thread { continue; TransactionData transactionData = repository.getTransactionRepository().fromSignature(signatures.get(0)); - if (transactionData == null || !(transactionData instanceof ArbitraryTransactionData)) + if (!(transactionData instanceof ArbitraryTransactionData)) continue; // Transaction needs to be newer than this build diff --git a/src/main/java/org/qora/controller/Controller.java b/src/main/java/org/qora/controller/Controller.java index 4329b33f..3c9669e5 100644 --- a/src/main/java/org/qora/controller/Controller.java +++ b/src/main/java/org/qora/controller/Controller.java @@ -97,21 +97,21 @@ public class Controller extends Thread { public static final String VERSION_PREFIX = "qora-core-"; private static final Logger LOGGER = LogManager.getLogger(Controller.class); - private static final long MISBEHAVIOUR_COOLOFF = 10 * 60 * 1000; // ms + private static final long MISBEHAVIOUR_COOLOFF = 10 * 60 * 1000L; // ms private static final int MAX_BLOCKCHAIN_TIP_AGE = 5; // blocks private static final Object shutdownLock = new Object(); private static final String repositoryUrlTemplate = "jdbc:hsqldb:file:%s/blockchain;create=true;hsqldb.full_log_replay=true"; - private static final long ARBITRARY_REQUEST_TIMEOUT = 5 * 1000; // ms - private static final long REPOSITORY_BACKUP_PERIOD = 123 * 60 * 1000; // ms - private static final long NTP_PRE_SYNC_CHECK_PERIOD = 5 * 1000; // ms - private static final long NTP_POST_SYNC_CHECK_PERIOD = 5 * 60 * 1000; // ms - private static final long DELETE_EXPIRED_INTERVAL = 5 * 60 * 1000; // ms + private static final long ARBITRARY_REQUEST_TIMEOUT = 5 * 1000L; // ms + private static final long REPOSITORY_BACKUP_PERIOD = 123 * 60 * 1000L; // ms + private static final long NTP_PRE_SYNC_CHECK_PERIOD = 5 * 1000L; // ms + private static final long NTP_POST_SYNC_CHECK_PERIOD = 5 * 60 * 1000L; // ms + private static final long DELETE_EXPIRED_INTERVAL = 5 * 60 * 1000L; // ms // To do with online accounts list - private static final long ONLINE_ACCOUNTS_TASKS_INTERVAL = 10 * 1000; // ms - private static final long ONLINE_ACCOUNTS_BROADCAST_INTERVAL = 1 * 60 * 1000; // ms - private static final long ONLINE_TIMESTAMP_MODULUS = 5 * 60 * 1000; - private static final long LAST_SEEN_EXPIRY_PERIOD = (ONLINE_TIMESTAMP_MODULUS * 2) + (1 * 60 * 1000); + private static final long ONLINE_ACCOUNTS_TASKS_INTERVAL = 10 * 1000L; // ms + private static final long ONLINE_ACCOUNTS_BROADCAST_INTERVAL = 1 * 60 * 1000L; // ms + private static final long ONLINE_TIMESTAMP_MODULUS = 5 * 60 * 1000L; + private static final long LAST_SEEN_EXPIRY_PERIOD = (ONLINE_TIMESTAMP_MODULUS * 2) + (1 * 60 * 1000L); private static volatile boolean isStopping = false; private static BlockGenerator blockGenerator = null; @@ -170,18 +170,18 @@ public class Controller extends Thread { throw new RuntimeException("Can't read build.properties resource", e); } - String buildTimestamp = properties.getProperty("build.timestamp"); - if (buildTimestamp == null) + String buildTimestampProperty = properties.getProperty("build.timestamp"); + if (buildTimestampProperty == null) throw new RuntimeException("Can't read build.timestamp from build.properties resource"); - this.buildTimestamp = LocalDateTime.parse(buildTimestamp, DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ssX")).toEpochSecond(ZoneOffset.UTC); - LOGGER.info(String.format("Build timestamp: %s", buildTimestamp)); + this.buildTimestamp = LocalDateTime.parse(buildTimestampProperty, DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ssX")).toEpochSecond(ZoneOffset.UTC); + LOGGER.info(String.format("Build timestamp: %s", buildTimestampProperty)); - String buildVersion = properties.getProperty("build.version"); - if (buildVersion == null) + String buildVersionProperty = properties.getProperty("build.version"); + if (buildVersionProperty == null) throw new RuntimeException("Can't read build.version from build.properties resource"); - this.buildVersion = VERSION_PREFIX + buildVersion; + this.buildVersion = VERSION_PREFIX + buildVersionProperty; LOGGER.info(String.format("Build version: %s", this.buildVersion)); } @@ -231,7 +231,7 @@ public class Controller extends Thread { // Entry point - public static void main(String args[]) { + public static void main(String[] args) { LOGGER.info("Starting up..."); // Potential GUI startup with splash screen, etc. @@ -282,7 +282,7 @@ public class Controller extends Thread { LOGGER.info("Starting controller"); Controller.getInstance().start(); - LOGGER.info("Starting networking on port " + Settings.getInstance().getListenPort()); + LOGGER.info(String.format("Starting networking on port %d", Settings.getInstance().getListenPort())); try { Network network = Network.getInstance(); network.start(); @@ -312,7 +312,7 @@ public class Controller extends Thread { LOGGER.info("Starting auto-update"); AutoUpdate.getInstance().start(); - LOGGER.info("Starting API on port " + Settings.getInstance().getApiPort()); + LOGGER.info(String.format("Starting API on port %d", Settings.getInstance().getApiPort())); try { ApiService apiService = ApiService.getInstance(); apiService.start(); @@ -321,7 +321,7 @@ public class Controller extends Thread { System.exit(1); } - LOGGER.info("Starting node management UI on port " + Settings.getInstance().getUiPort()); + LOGGER.info(String.format("Starting node management UI on port %d", Settings.getInstance().getUiPort())); try { UiService uiService = UiService.getInstance(); uiService.start(); @@ -335,7 +335,7 @@ public class Controller extends Thread { } /** Called by AdvancedInstaller's launch EXE in single-instance mode, when an instance is already running. */ - public static void secondaryMain(String args[]) { + public static void secondaryMain(String[] args) { // Return as we don't want to run more than one instance } @@ -670,7 +670,7 @@ public class Controller extends Thread { network.broadcast(peer -> network.buildHeightMessage(peer, latestBlockData)); // Send (if outbound) / Request unconfirmed transaction signatures - network.broadcast(peer -> network.buildGetUnconfirmedTransactionsMessage(peer)); + network.broadcast(network::buildGetUnconfirmedTransactionsMessage); } public void onGenerationPossibleChange(boolean isGenerationPossible) { @@ -1002,7 +1002,7 @@ public class Controller extends Thread { // Fetch actual transaction data from peer Message getTransactionMessage = new GetTransactionMessage(signature); Message responseMessage = peer.getResponse(getTransactionMessage); - if (responseMessage == null || !(responseMessage instanceof TransactionMessage)) { + if (!(responseMessage instanceof TransactionMessage)) { // Maybe peer no longer has this transaction LOGGER.trace(() -> String.format("Peer %s didn't send transaction %s", peer, Base58.encode(signature))); continue; @@ -1158,7 +1158,7 @@ public class Controller extends Thread { // Check transaction exists and payload hash is correct try (final Repository repository = RepositoryManager.getRepository()) { TransactionData transactionData = repository.getTransactionRepository().fromSignature(signature); - if (transactionData == null || !(transactionData instanceof ArbitraryTransactionData)) + if (!(transactionData instanceof ArbitraryTransactionData)) break; ArbitraryTransactionData arbitraryTransactionData = (ArbitraryTransactionData) transactionData; @@ -1231,10 +1231,10 @@ public class Controller extends Thread { case ONLINE_ACCOUNTS: { OnlineAccountsMessage onlineAccountsMessage = (OnlineAccountsMessage) message; - List onlineAccounts = onlineAccountsMessage.getOnlineAccounts(); - LOGGER.trace(() -> String.format("Received %d online accounts from %s", onlineAccounts.size(), peer)); + List peersOnlineAccounts = onlineAccountsMessage.getOnlineAccounts(); + LOGGER.trace(() -> String.format("Received %d online accounts from %s", peersOnlineAccounts.size(), peer)); - for (OnlineAccountData onlineAccountData : onlineAccounts) + for (OnlineAccountData onlineAccountData : peersOnlineAccounts) this.verifyAndAddAccount(onlineAccountData); break; @@ -1309,7 +1309,7 @@ public class Controller extends Thread { synchronized (this.onlineAccounts) { message = new GetOnlineAccountsMessage(this.onlineAccounts); } - Network.getInstance().broadcast((peer) -> message); + Network.getInstance().broadcast(peer -> message); } // Refresh our online accounts signatures? @@ -1341,7 +1341,7 @@ public class Controller extends Thread { iterator.remove(); } } catch (DataException e) { - LOGGER.warn("Repository issue trying to fetch forging accounts: " + e.getMessage()); + LOGGER.warn(String.format("Repository issue trying to fetch forging accounts: %s", e.getMessage())); return; } @@ -1389,7 +1389,7 @@ public class Controller extends Thread { return; Message message = new OnlineAccountsMessage(ourOnlineAccounts); - Network.getInstance().broadcast((peer) -> message); + Network.getInstance().broadcast(peer -> message); LOGGER.trace(()-> String.format("Broadcasted %d online account%s with timestamp %d", ourOnlineAccounts.size(), (ourOnlineAccounts.size() != 1 ? "s" : ""), onlineAccountsTimestamp)); } diff --git a/src/main/java/org/qora/controller/Synchronizer.java b/src/main/java/org/qora/controller/Synchronizer.java index 91b96990..6d7c261b 100644 --- a/src/main/java/org/qora/controller/Synchronizer.java +++ b/src/main/java/org/qora/controller/Synchronizer.java @@ -214,7 +214,7 @@ public class Synchronizer { --ourHeight; } - LOGGER.debug(String.format("Orphaned blocks back to height %d, sig %.8s - fetching blocks from peer", commonBlockHeight, commonBlockSig58, peer)); + LOGGER.debug(String.format("Orphaned blocks back to height %d, sig %.8s - fetching blocks from peer %s", commonBlockHeight, commonBlockSig58, peer)); } else { LOGGER.debug(String.format("Fetching new blocks from peer %s", peer)); } @@ -224,7 +224,7 @@ public class Synchronizer { int maxBatchHeight = commonBlockHeight + SYNC_BATCH_SIZE; // Convert any block summaries from above into signatures to request from peer - List peerBlockSignatures = peerBlockSummaries.stream().map(blockSummaryData -> blockSummaryData.getSignature()).collect(Collectors.toList()); + List peerBlockSignatures = peerBlockSummaries.stream().map(BlockSummaryData::getSignature).collect(Collectors.toList()); while (ourHeight < peerHeight && ourHeight < maxBatchHeight) { // Do we need more signatures? diff --git a/src/main/java/org/qora/crosschain/BTC.java b/src/main/java/org/qora/crosschain/BTC.java index f1d3ecf2..009f7c34 100644 --- a/src/main/java/org/qora/crosschain/BTC.java +++ b/src/main/java/org/qora/crosschain/BTC.java @@ -196,12 +196,9 @@ public class BTC { peerGroup.start(); } - public static BTC getInstance() { + public static synchronized BTC getInstance() { if (instance == null) - synchronized (instanceLock) { - if (instance == null) - instance = new BTC(); - } + instance = new BTC(); return instance; } diff --git a/src/main/java/org/qora/crypto/BrokenMD160.java b/src/main/java/org/qora/crypto/BrokenMD160.java index f7372add..90ff6ec9 100644 --- a/src/main/java/org/qora/crypto/BrokenMD160.java +++ b/src/main/java/org/qora/crypto/BrokenMD160.java @@ -6,8 +6,8 @@ package org.qora.crypto; * DO NOT USE in future code as this implementation is BROKEN and returns incorrect digests for some inputs. *

* It is only "grand-fathered" here to produce correct QORA addresses. + * @deprecated */ - @Deprecated public class BrokenMD160 { diff --git a/src/main/java/org/qora/data/voting/PollData.java b/src/main/java/org/qora/data/voting/PollData.java index 79e588e9..8723bfce 100644 --- a/src/main/java/org/qora/data/voting/PollData.java +++ b/src/main/java/org/qora/data/voting/PollData.java @@ -2,8 +2,6 @@ package org.qora.data.voting; import java.util.List; -import org.qora.data.voting.PollOptionData; - public class PollData { // Properties diff --git a/src/main/java/org/qora/globalization/BIP39WordList.java b/src/main/java/org/qora/globalization/BIP39WordList.java index e3707447..134170d0 100644 --- a/src/main/java/org/qora/globalization/BIP39WordList.java +++ b/src/main/java/org/qora/globalization/BIP39WordList.java @@ -33,13 +33,13 @@ public enum BIP39WordList { try (InputStream inputStream = loader.getResourceAsStream("BIP39/wordlist_" + lang + ".txt")) { if (inputStream == null) { - LOGGER.warn("Can't locate '" + lang + "' BIP39 wordlist"); + LOGGER.warn(String.format("Can't locate '%s' BIP39 wordlist", lang)); return null; } wordList = new BufferedReader(new InputStreamReader(inputStream)).lines().collect(Collectors.toList()); } catch (IOException e) { - LOGGER.warn("Error reading '" + lang + "' BIP39 wordlist", e); + LOGGER.warn(String.format("Error reading '%s' BIP39 wordlist", lang), e); return null; } diff --git a/src/main/java/org/qora/group/Group.java b/src/main/java/org/qora/group/Group.java index 7142b97c..6d3de7db 100644 --- a/src/main/java/org/qora/group/Group.java +++ b/src/main/java/org/qora/group/Group.java @@ -46,7 +46,7 @@ public class Group { public final int value; public final boolean isPercentage; - private final static Map map = stream(ApprovalThreshold.values()) + private static final Map map = stream(ApprovalThreshold.values()) .collect(toMap(threshold -> threshold.value, threshold -> threshold)); ApprovalThreshold(int value, boolean isPercentage) { diff --git a/src/main/java/org/qora/gui/SplashFrame.java b/src/main/java/org/qora/gui/SplashFrame.java index 66065ce1..40eba414 100644 --- a/src/main/java/org/qora/gui/SplashFrame.java +++ b/src/main/java/org/qora/gui/SplashFrame.java @@ -41,7 +41,7 @@ public class SplashFrame { private SplashFrame() { this.splashDialog = new JDialog(); - List icons = new ArrayList(); + List icons = new ArrayList<>(); icons.add(Gui.loadImage("icons/icon16.png")); icons.add(Gui.loadImage("icons/icon32.png")); icons.add(Gui.loadImage("icons/icon64.png")); diff --git a/src/main/java/org/qora/gui/SysTray.java b/src/main/java/org/qora/gui/SysTray.java index 71c86e42..ecbe684f 100644 --- a/src/main/java/org/qora/gui/SysTray.java +++ b/src/main/java/org/qora/gui/SysTray.java @@ -4,8 +4,6 @@ import java.awt.AWTError; import java.awt.AWTException; import java.awt.SystemTray; import java.awt.TrayIcon; -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.awt.event.WindowEvent; @@ -37,7 +35,7 @@ import org.qora.utils.URLViewer; public class SysTray { - protected static final Logger LOGGER = LogManager.getLogger(SplashFrame.class); + protected static final Logger LOGGER = LogManager.getLogger(SysTray.class); private static final String NTP_SCRIPT = "ntpcfg.bat"; private static SysTray instance; @@ -147,31 +145,25 @@ public class SysTray { }); JMenuItem openUi = new JMenuItem(Translator.INSTANCE.translate("SysTray", "OPEN_NODE_UI")); - openUi.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - destroyHiddenDialog(); + openUi.addActionListener(actionEvent -> { + destroyHiddenDialog(); - try { - URLViewer.openWebpage(new URL("http://localhost:" + Settings.getInstance().getUiPort())); - } catch (Exception e1) { - LOGGER.error("Unable to open node UI in browser"); - } + try { + URLViewer.openWebpage(new URL("http://localhost:" + Settings.getInstance().getUiPort())); + } catch (Exception e) { + LOGGER.error("Unable to open node UI in browser"); } }); menu.add(openUi); JMenuItem openTimeCheck = new JMenuItem(Translator.INSTANCE.translate("SysTray", "CHECK_TIME_ACCURACY")); - openTimeCheck.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - destroyHiddenDialog(); + openTimeCheck.addActionListener(actionEvent -> { + destroyHiddenDialog(); - try { - URLViewer.openWebpage(new URL("https://time.is")); - } catch (Exception e1) { - LOGGER.error("Unable to open time-check website in browser"); - } + try { + URLViewer.openWebpage(new URL("https://time.is")); + } catch (Exception e) { + LOGGER.error("Unable to open time-check website in browser"); } }); menu.add(openTimeCheck); @@ -179,25 +171,19 @@ public class SysTray { // Only for Windows users if (System.getProperty("os.name").toLowerCase().contains("win")) { JMenuItem syncTime = new JMenuItem(Translator.INSTANCE.translate("SysTray", "SYNCHRONIZE_CLOCK")); - syncTime.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - destroyHiddenDialog(); + syncTime.addActionListener(actionEvent -> { + destroyHiddenDialog(); - new SynchronizeWorker().execute(); - } + new SynchronizeWorker().execute(); }); menu.add(syncTime); } JMenuItem exit = new JMenuItem(Translator.INSTANCE.translate("SysTray", "EXIT")); - exit.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - destroyHiddenDialog(); + exit.addActionListener(actionEvent -> { + destroyHiddenDialog(); - new ClosingWorker().execute(); - } + new ClosingWorker().execute(); }); menu.add(exit); diff --git a/src/main/java/org/qora/mintsim.java b/src/main/java/org/qora/mintsim.java index c179dba2..168815de 100644 --- a/src/main/java/org/qora/mintsim.java +++ b/src/main/java/org/qora/mintsim.java @@ -44,7 +44,7 @@ public class mintsim { } } - public static void main(String args[]) { + public static void main(String[] args) { if (args.length < 2 || (args.length % 2) != 0) { System.err.println("usage: mintsim [ [...]]"); System.exit(1); @@ -53,8 +53,8 @@ public class mintsim { try { int argIndex = 0; do { - int minBlocks = Integer.valueOf(args[argIndex++]); - int maxAccounts = Integer.valueOf(args[argIndex++]); + int minBlocks = Integer.parseInt(args[argIndex++]); + int maxAccounts = Integer.parseInt(args[argIndex++]); tiers.add(new TierInfo(maxAccounts, minBlocks)); } while (argIndex < args.length); diff --git a/src/main/java/org/qora/network/Handshake.java b/src/main/java/org/qora/network/Handshake.java index 950b0274..67af9cd7 100644 --- a/src/main/java/org/qora/network/Handshake.java +++ b/src/main/java/org/qora/network/Handshake.java @@ -201,7 +201,7 @@ public enum Handshake { private static final Logger LOGGER = LogManager.getLogger(Handshake.class); /** Maximum allowed difference between peer's reported timestamp and when they connected, in milliseconds. */ - private static final long MAX_TIMESTAMP_DELTA = 30 * 1000; // ms + private static final long MAX_TIMESTAMP_DELTA = 30 * 1000L; // ms public final MessageType expectedMessageType; diff --git a/src/main/java/org/qora/network/Network.java b/src/main/java/org/qora/network/Network.java index a441fe35..ec7166e3 100644 --- a/src/main/java/org/qora/network/Network.java +++ b/src/main/java/org/qora/network/Network.java @@ -59,22 +59,22 @@ import org.qora.utils.ExecuteProduceConsume; import org.qora.utils.NTP; // For managing peers -public class Network extends Thread { +public class Network { private static final Logger LOGGER = LogManager.getLogger(Network.class); private static Network instance; private static final int LISTEN_BACKLOG = 10; /** How long before retrying after a connection failure, in milliseconds. */ - private static final int CONNECT_FAILURE_BACKOFF = 5 * 60 * 1000; // ms + private static final long CONNECT_FAILURE_BACKOFF = 5 * 60 * 1000L; // ms /** How long between informational broadcasts to all connected peers, in milliseconds. */ - private static final int BROADCAST_INTERVAL = 60 * 1000; // ms + private static final long BROADCAST_INTERVAL = 60 * 1000L; // ms /** Maximum time since last successful connection for peer info to be propagated, in milliseconds. */ - private static final long RECENT_CONNECTION_THRESHOLD = 24 * 60 * 60 * 1000; // ms + private static final long RECENT_CONNECTION_THRESHOLD = 24 * 60 * 60 * 1000L; // ms /** Maximum time since last connection attempt before a peer is potentially considered "old", in milliseconds. */ - private static final long OLD_PEER_ATTEMPTED_PERIOD = 24 * 60 * 60 * 1000; // ms + private static final long OLD_PEER_ATTEMPTED_PERIOD = 24 * 60 * 60 * 1000L; // ms /** Maximum time since last successful connection before a peer is potentially considered "old", in milliseconds. */ - private static final long OLD_PEER_CONNECTION_PERIOD = 7 * 24 * 60 * 60 * 1000; // ms + private static final long OLD_PEER_CONNECTION_PERIOD = 7 * 24 * 60 * 60 * 1000L; // ms /** Maximum time allowed for handshake to complete, in milliseconds. */ private static final long HANDSHAKE_TIMEOUT = 60 * 1000; // ms @@ -135,7 +135,7 @@ public class Network extends Thread { serverChannel.bind(endpoint, LISTEN_BACKLOG); serverChannel.register(channelSelector, SelectionKey.OP_ACCEPT); } catch (UnknownHostException e) { - LOGGER.error("Can't bind listen socket to address " + Settings.getInstance().getBindAddress()); + LOGGER.error(String.format("Can't bind listen socket to address %s", Settings.getInstance().getBindAddress())); throw new RuntimeException("Can't bind listen socket to address"); } catch (IOException e) { LOGGER.error("Can't create listen socket"); @@ -167,7 +167,9 @@ public class Network extends Thread { 10L, TimeUnit.SECONDS, new SynchronousQueue()); networkEPC = new NetworkProcessor(networkExecutor); + } + public void start() { // Start up first networking thread networkEPC.start(); } @@ -244,14 +246,9 @@ public class Network extends Thread { /** Returns list of peers we connected to that have completed handshaking. */ public List getOutboundHandshakedPeers() { - List peers = new ArrayList<>(); - synchronized (this.connectedPeers) { - peers = this.connectedPeers.stream().filter(peer -> peer.isOutbound() && peer.getHandshakeStatus() == Handshake.COMPLETED) - .collect(Collectors.toList()); + return this.connectedPeers.stream().filter(peer -> peer.isOutbound() && peer.getHandshakeStatus() == Handshake.COMPLETED).collect(Collectors.toList()); } - - return peers; } /** Returns Peer with inbound connection and matching ID, or null if none found. */ @@ -359,9 +356,7 @@ public class Network extends Thread { LOGGER.trace(() -> String.format("Network thread %s encountered I/O error: %s", Thread.currentThread().getId(), e.getMessage()), e); peer.disconnect("I/O error"); - return; } - } } @@ -664,7 +659,7 @@ public class Network extends Thread { if (socketChannel == null) return; - if (this.isInterrupted()) + if (Thread.currentThread().isInterrupted()) return; synchronized (this.connectedPeers) { @@ -839,7 +834,7 @@ public class Network extends Thread { // If inbound peer, use listen port and socket address to recreate first entry if (!peer.isOutbound()) { PeerAddress sendingPeerAddress = PeerAddress.fromString(peer.getPeerData().getAddress().getHost() + ":" + peerPort); - LOGGER.trace("PEERS_V2 sending peer's listen address: " + sendingPeerAddress.toString()); + LOGGER.trace(() -> String.format("PEERS_V2 sending peer's listen address: %s", sendingPeerAddress.toString())); peerV2Addresses.add(0, sendingPeerAddress); } @@ -1100,10 +1095,7 @@ public class Network extends Thread { List knownPeers = repository.getNetworkRepository().getAllPeers(); // Filter out duplicates - Predicate isKnownAddress = peerAddress -> { - return knownPeers.stream().anyMatch(knownPeerData -> knownPeerData.getAddress().equals(peerAddress)); - }; - + Predicate isKnownAddress = peerAddress -> knownPeers.stream().anyMatch(knownPeerData -> knownPeerData.getAddress().equals(peerAddress)); peerAddresses.removeIf(isKnownAddress); repository.discardChanges(); @@ -1126,6 +1118,8 @@ public class Network extends Thread { public void broadcast(Function peerMessageBuilder) { class Broadcaster implements Runnable { + private final Random random = new Random(); + private List targetPeers; private Function peerMessageBuilder; @@ -1138,12 +1132,10 @@ public class Network extends Thread { public void run() { Thread.currentThread().setName("Network Broadcast"); - Random random = new Random(); - for (Peer peer : targetPeers) { // Very short sleep to reduce strain, improve multi-threading and catch interrupts try { - Thread.sleep(random.nextInt(20) + 20); + Thread.sleep(random.nextInt(20) + 20L); } catch (InterruptedException e) { break; } diff --git a/src/main/java/org/qora/network/Peer.java b/src/main/java/org/qora/network/Peer.java index ee80b9f4..66655772 100644 --- a/src/main/java/org/qora/network/Peer.java +++ b/src/main/java/org/qora/network/Peer.java @@ -256,7 +256,7 @@ public class Peer { this.socketChannel.configureBlocking(false); this.byteBuffer = ByteBuffer.allocate(Network.getInstance().getMaxMessageSize()); this.replyQueues = Collections.synchronizedMap(new HashMap>()); - this.pendingMessages = new LinkedBlockingQueue(); + this.pendingMessages = new LinkedBlockingQueue<>(); } public SocketChannel connect() { @@ -394,7 +394,7 @@ public class Peer { if (bytesWritten == 0) // Underlying socket's internal buffer probably full, // so wait a short while for bytes to actually be transmitted over the wire - Thread.sleep(1L); + this.socketChannel.wait(1L); } } } catch (MessageException e) { @@ -424,7 +424,7 @@ public class Peer { * @throws InterruptedException */ public Message getResponse(Message message) throws InterruptedException { - BlockingQueue blockingQueue = new ArrayBlockingQueue(1); + BlockingQueue blockingQueue = new ArrayBlockingQueue<>(1); // Assign random ID to this message int id; @@ -443,8 +443,7 @@ public class Peer { } try { - Message response = blockingQueue.poll(RESPONSE_TIMEOUT, TimeUnit.MILLISECONDS); - return response; + return blockingQueue.poll(RESPONSE_TIMEOUT, TimeUnit.MILLISECONDS); } finally { this.replyQueues.remove(id); } diff --git a/src/main/java/org/qora/network/message/Message.java b/src/main/java/org/qora/network/message/Message.java index fd10f8a9..3aadae80 100644 --- a/src/main/java/org/qora/network/message/Message.java +++ b/src/main/java/org/qora/network/message/Message.java @@ -73,7 +73,7 @@ public abstract class Message { ONLINE_ACCOUNTS(26); public final int value; - public final Method fromByteBuffer; + public final Method fromByteBufferMethod; private static final Map map = stream(MessageType.values()) .collect(toMap(messageType -> messageType.value, messageType -> messageType)); @@ -88,16 +88,16 @@ public abstract class Message { String className = String.join("", classNameParts); - Method fromByteBuffer; + Method method; try { Class subclass = Class.forName(String.join("", Message.class.getPackage().getName(), ".", className, "Message")); - fromByteBuffer = subclass.getDeclaredMethod("fromByteBuffer", int.class, ByteBuffer.class); + method = subclass.getDeclaredMethod("fromByteBuffer", int.class, ByteBuffer.class); } catch (ClassNotFoundException | NoSuchMethodException | SecurityException e) { - fromByteBuffer = null; + method = null; } - this.fromByteBuffer = fromByteBuffer; + this.fromByteBufferMethod = method; } public static MessageType valueOf(int value) { @@ -105,11 +105,11 @@ public abstract class Message { } public Message fromByteBuffer(int id, ByteBuffer byteBuffer) throws MessageException { - if (this.fromByteBuffer == null) + if (this.fromByteBufferMethod == null) throw new MessageException("Unsupported message type [" + value + "] during conversion from bytes"); try { - return (Message) this.fromByteBuffer.invoke(null, id, byteBuffer); + return (Message) this.fromByteBufferMethod.invoke(null, id, byteBuffer); } catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException e) { if (e.getCause() instanceof BufferUnderflowException) throw new MessageException("Byte data too short for " + name() + " message"); diff --git a/src/main/java/org/qora/network/message/PeersV2Message.java b/src/main/java/org/qora/network/message/PeersV2Message.java index 8640084a..c50dbe2b 100644 --- a/src/main/java/org/qora/network/message/PeersV2Message.java +++ b/src/main/java/org/qora/network/message/PeersV2Message.java @@ -4,6 +4,7 @@ import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.nio.ByteBuffer; +import java.nio.charset.StandardCharsets; import java.util.ArrayList; import java.util.List; @@ -42,7 +43,7 @@ public class PeersV2Message extends Message { byte[] addressBytes = new byte[addressSize & 0xff]; byteBuffer.get(addressBytes); - String addressString = new String(addressBytes, "UTF-8"); + String addressString = new String(addressBytes, StandardCharsets.UTF_8); try { PeerAddress peerAddress = PeerAddress.fromString(addressString); @@ -63,10 +64,10 @@ public class PeersV2Message extends Message { List addresses = new ArrayList<>(); // First entry represents sending node but contains only port number with empty address. - addresses.add(new String("0.0.0.0:" + Settings.getInstance().getListenPort()).getBytes("UTF-8")); + addresses.add(("0.0.0.0:" + Settings.getInstance().getListenPort()).getBytes(StandardCharsets.UTF_8)); for (PeerAddress peerAddress : this.peerAddresses) - addresses.add(peerAddress.toString().getBytes("UTF-8")); + addresses.add(peerAddress.toString().getBytes(StandardCharsets.UTF_8)); // We can't send addresses that are longer than 255 bytes as length itself is encoded in one byte. addresses.removeIf(addressString -> addressString.length > 255); diff --git a/src/main/java/org/qora/network/message/VersionMessage.java b/src/main/java/org/qora/network/message/VersionMessage.java index 802cee4c..f0550330 100644 --- a/src/main/java/org/qora/network/message/VersionMessage.java +++ b/src/main/java/org/qora/network/message/VersionMessage.java @@ -4,6 +4,7 @@ import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.nio.ByteBuffer; +import java.nio.charset.StandardCharsets; import org.qora.utils.Serialization; @@ -44,7 +45,7 @@ public class VersionMessage extends Message { byte[] versionBytes = new byte[versionStringLength]; bytes.get(versionBytes); - String versionString = new String(versionBytes, "UTF-8"); + String versionString = new String(versionBytes, StandardCharsets.UTF_8); return new VersionMessage(id, buildTimestamp, versionString); } diff --git a/src/main/java/org/qora/payment/Payment.java b/src/main/java/org/qora/payment/Payment.java index 5c506e4e..ee6a63af 100644 --- a/src/main/java/org/qora/payment/Payment.java +++ b/src/main/java/org/qora/payment/Payment.java @@ -45,7 +45,7 @@ public class Payment { return ValidationResult.NEGATIVE_FEE; // Total up payment amounts by assetId - Map amountsByAssetId = new HashMap(); + Map amountsByAssetId = new HashMap<>(); // Add transaction fee to start with amountsByAssetId.put(Asset.QORT, fee); diff --git a/src/main/java/org/qora/repository/hsqldb/HSQLDBATRepository.java b/src/main/java/org/qora/repository/hsqldb/HSQLDBATRepository.java index 57278eb4..74c468d9 100644 --- a/src/main/java/org/qora/repository/hsqldb/HSQLDBATRepository.java +++ b/src/main/java/org/qora/repository/hsqldb/HSQLDBATRepository.java @@ -188,7 +188,7 @@ public class HSQLDBATRepository implements ATRepository { @Override public List getBlockATStatesAtHeight(int height) throws DataException { - List atStates = new ArrayList(); + List atStates = new ArrayList<>(); try (ResultSet resultSet = this.repository.checkedExecute("SELECT AT_address, state_hash, fees FROM ATStates WHERE height = ? ORDER BY creation ASC", height)) { diff --git a/src/main/java/org/qora/repository/hsqldb/HSQLDBAccountRepository.java b/src/main/java/org/qora/repository/hsqldb/HSQLDBAccountRepository.java index 30991fcc..20dcff80 100644 --- a/src/main/java/org/qora/repository/hsqldb/HSQLDBAccountRepository.java +++ b/src/main/java/org/qora/repository/hsqldb/HSQLDBAccountRepository.java @@ -321,7 +321,7 @@ public class HSQLDBAccountRepository implements AccountRepository { } // For no-address queries, or unless specifically requested, only return accounts with non-zero balance - if (addresses.isEmpty() || (excludeZero != null && excludeZero == true)) { + if (addresses.isEmpty() || (excludeZero != null && excludeZero)) { sql.append(assetIds.isEmpty() ? " WHERE " : " AND "); sql.append("balance != 0 "); } diff --git a/src/main/java/org/qora/repository/hsqldb/HSQLDBAssetRepository.java b/src/main/java/org/qora/repository/hsqldb/HSQLDBAssetRepository.java index d48d6a91..641b2c92 100644 --- a/src/main/java/org/qora/repository/hsqldb/HSQLDBAssetRepository.java +++ b/src/main/java/org/qora/repository/hsqldb/HSQLDBAssetRepository.java @@ -104,7 +104,7 @@ public class HSQLDBAssetRepository implements AssetRepository { HSQLDBRepository.limitOffsetSql(sql, limit, offset); - List assets = new ArrayList(); + List assets = new ArrayList<>(); try (ResultSet resultSet = this.repository.checkedExecute(sql.toString())) { if (resultSet == null) @@ -228,7 +228,7 @@ public class HSQLDBAssetRepository implements AssetRepository { @Override public List getOpenOrders(long haveAssetId, long wantAssetId, Integer limit, Integer offset, Boolean reverse) throws DataException { - List orders = new ArrayList(); + List orders = new ArrayList<>(); // Cache have & want asset names for later use, which also saves a table join AssetData haveAssetData = this.fromAssetId(haveAssetId); @@ -305,7 +305,7 @@ public class HSQLDBAssetRepository implements AssetRepository { sql.append(", ordered"); - List orders = new ArrayList(); + List orders = new ArrayList<>(); try (ResultSet resultSet = this.repository.checkedExecute(sql.toString(), bindParams.toArray())) { if (resultSet == null) @@ -336,7 +336,7 @@ public class HSQLDBAssetRepository implements AssetRepository { @Override public List getAggregatedOpenOrders(long haveAssetId, long wantAssetId, Integer limit, Integer offset, Boolean reverse) throws DataException { - List orders = new ArrayList(); + List orders = new ArrayList<>(); // Cache have & want asset names for later use, which also saves a table join AssetData haveAssetData = this.fromAssetId(haveAssetId); @@ -404,7 +404,7 @@ public class HSQLDBAssetRepository implements AssetRepository { HSQLDBRepository.limitOffsetSql(sql, limit, offset); - List orders = new ArrayList(); + List orders = new ArrayList<>(); try (ResultSet resultSet = this.repository.checkedExecute(sql.toString(), publicKey)) { if (resultSet == null) @@ -437,7 +437,7 @@ public class HSQLDBAssetRepository implements AssetRepository { @Override public List getAccountsOrders(byte[] publicKey, long haveAssetId, long wantAssetId, Boolean optIsClosed, Boolean optIsFulfilled, Integer limit, Integer offset, Boolean reverse) throws DataException { - List orders = new ArrayList(); + List orders = new ArrayList<>(); // Cache have & want asset names for later use, which also saves a table join AssetData haveAssetData = this.fromAssetId(haveAssetId); @@ -524,7 +524,7 @@ public class HSQLDBAssetRepository implements AssetRepository { @Override public List getTrades(long haveAssetId, long wantAssetId, Integer limit, Integer offset, Boolean reverse) throws DataException { - List trades = new ArrayList(); + List trades = new ArrayList<>(); // Cache have & want asset names for later use, which also saves a table join AssetData haveAssetData = this.fromAssetId(haveAssetId); @@ -677,7 +677,7 @@ public class HSQLDBAssetRepository implements AssetRepository { HSQLDBRepository.limitOffsetSql(sql, limit, offset); - List trades = new ArrayList(); + List trades = new ArrayList<>(); try (ResultSet resultSet = this.repository.checkedExecute(sql.toString(), orderId)) { if (resultSet == null) diff --git a/src/main/java/org/qora/repository/hsqldb/HSQLDBBlockRepository.java b/src/main/java/org/qora/repository/hsqldb/HSQLDBBlockRepository.java index d2ed8563..027f7c55 100644 --- a/src/main/java/org/qora/repository/hsqldb/HSQLDBBlockRepository.java +++ b/src/main/java/org/qora/repository/hsqldb/HSQLDBBlockRepository.java @@ -153,7 +153,7 @@ public class HSQLDBBlockRepository implements BlockRepository { HSQLDBRepository.limitOffsetSql(sql, limit, offset); - List transactions = new ArrayList(); + List transactions = new ArrayList<>(); try (ResultSet resultSet = this.repository.checkedExecute(sql.toString(), signature)) { if (resultSet == null) diff --git a/src/main/java/org/qora/repository/hsqldb/HSQLDBDatabaseUpdates.java b/src/main/java/org/qora/repository/hsqldb/HSQLDBDatabaseUpdates.java index b1013cf1..141fd32f 100644 --- a/src/main/java/org/qora/repository/hsqldb/HSQLDBDatabaseUpdates.java +++ b/src/main/java/org/qora/repository/hsqldb/HSQLDBDatabaseUpdates.java @@ -29,8 +29,10 @@ public class HSQLDBDatabaseUpdates { * @throws SQLException */ private static void incrementDatabaseVersion(Connection connection) throws SQLException { - connection.createStatement().execute("UPDATE DatabaseInfo SET version = version + 1"); - connection.commit(); + try (Statement stmt = connection.createStatement()) { + stmt.execute("UPDATE DatabaseInfo SET version = version + 1"); + connection.commit(); + } } /** diff --git a/src/main/java/org/qora/repository/hsqldb/HSQLDBGroupRepository.java b/src/main/java/org/qora/repository/hsqldb/HSQLDBGroupRepository.java index a33ce458..c160d7a2 100644 --- a/src/main/java/org/qora/repository/hsqldb/HSQLDBGroupRepository.java +++ b/src/main/java/org/qora/repository/hsqldb/HSQLDBGroupRepository.java @@ -308,9 +308,7 @@ public class HSQLDBGroupRepository implements GroupRepository { if (resultSet == null) return null; - String owner = resultSet.getString(1); - - return owner; + return resultSet.getString(1); } catch (SQLException e) { throw new DataException("Unable to fetch group owner from repository", e); } diff --git a/src/main/java/org/qora/repository/hsqldb/HSQLDBRepository.java b/src/main/java/org/qora/repository/hsqldb/HSQLDBRepository.java index 79e07e01..ee05c513 100644 --- a/src/main/java/org/qora/repository/hsqldb/HSQLDBRepository.java +++ b/src/main/java/org/qora/repository/hsqldb/HSQLDBRepository.java @@ -63,7 +63,7 @@ public class HSQLDBRepository implements Repository { this.slowQueryThreshold = Settings.getInstance().getSlowQueryThreshold(); if (this.slowQueryThreshold != null) - this.sqlStatements = new ArrayList(); + this.sqlStatements = new ArrayList<>(); // Find out our session ID try (Statement stmt = this.connection.createStatement()) { @@ -237,13 +237,13 @@ public class HSQLDBRepository implements Repository { @Override public void backup(boolean quick) throws DataException { - // First perform a CHECKPOINT - try { - if (!quick) - this.connection.createStatement().execute("CHECKPOINT DEFRAG"); - } catch (SQLException e) { - throw new DataException("Unable to prepare repository for backup"); - } + if (!quick) + // First perform a CHECKPOINT + try (Statement stmt = this.connection.createStatement()) { + stmt.execute("CHECKPOINT DEFRAG"); + } catch (SQLException e) { + throw new DataException("Unable to prepare repository for backup"); + } // Clean out any previous backup try { @@ -272,8 +272,8 @@ public class HSQLDBRepository implements Repository { } // Actually create backup - try { - this.connection.createStatement().execute("BACKUP DATABASE TO 'backup/' NOT BLOCKING AS FILES"); + try (Statement stmt = this.connection.createStatement()) { + stmt.execute("BACKUP DATABASE TO 'backup/' NOT BLOCKING AS FILES"); } catch (SQLException e) { throw new DataException("Unable to backup repository"); } @@ -287,8 +287,7 @@ public class HSQLDBRepository implements Repository { if (!matcher.find()) return null; - String pathname = matcher.group(1); - return pathname; + return matcher.group(1); } private static String buildBackupUrl(String dbPathname) { @@ -298,8 +297,7 @@ public class HSQLDBRepository implements Repository { // Try to open backup. We need to remove "create=true" and insert "backup" dir before final filename. String backupUrlTemplate = "jdbc:hsqldb:file:%s/backup/%s;create=false;hsqldb.full_log_replay=true"; - String backupUrl = String.format(backupUrlTemplate, oldRepoDirPath.toString(), oldRepoFilePath.toString()); - return backupUrl; + return String.format(backupUrlTemplate, oldRepoDirPath.toString(), oldRepoFilePath.toString()); } /* package */ static void attemptRecovery(String connectionUrl) throws DataException { @@ -321,11 +319,11 @@ public class HSQLDBRepository implements Repository { .filter(file -> file.getPath().startsWith(dbPathname)) .forEach(File::delete); - try { + try (Statement stmt = connection.createStatement()) { // Now "backup" the backup back to original repository location (the parent) // NOTE: trailing / is OK because HSQLDB checks for both / and O/S-specific separator // textdb.allow_full_path connection property is required to be able to use '..' - connection.createStatement().execute("BACKUP DATABASE TO '../' BLOCKING AS FILES"); + stmt.execute("BACKUP DATABASE TO '../' BLOCKING AS FILES"); } catch (SQLException e) { // We really failed throw new DataException("Failed to recover repository to original location"); @@ -357,9 +355,7 @@ public class HSQLDBRepository implements Repository { if (this.sqlStatements != null) this.sqlStatements.add(sql); - PreparedStatement preparedStatement = this.connection.prepareStatement(sql); - - return preparedStatement; + return this.connection.prepareStatement(sql); } /** @@ -594,7 +590,7 @@ public class HSQLDBRepository implements Repository { return e; do { - long sessionId = resultSet.getLong(1); + long systemSessionId = resultSet.getLong(1); boolean inTransaction = resultSet.getBoolean(2); long transactionSize = resultSet.getLong(3); String waitingForThis = resultSet.getString(4); @@ -602,7 +598,7 @@ public class HSQLDBRepository implements Repository { String currentStatement = resultSet.getString(6); LOGGER.error(String.format("Session %d, %s transaction (size %d), waiting for this '%s', this waiting for '%s', current statement: %s", - sessionId, (inTransaction ? "in" : "not in"), transactionSize, waitingForThis, thisWaitingFor, currentStatement)); + systemSessionId, (inTransaction ? "in" : "not in"), transactionSize, waitingForThis, thisWaitingFor, currentStatement)); } while (resultSet.next()); } catch (SQLException de) { // Throw original exception instead @@ -619,8 +615,10 @@ public class HSQLDBRepository implements Repository { throw new DataException("Unable to check repository status after " + context); try (ResultSet resultSet = stmt.getResultSet()) { - if (resultSet == null || !resultSet.next()) - LOGGER.warn("Unable to check repository status after " + context); + if (resultSet == null || !resultSet.next()) { + LOGGER.warn(String.format("Unable to check repository status after %s", context)); + return; + } boolean inTransaction = resultSet.getBoolean(1); int transactionCount = resultSet.getInt(2); diff --git a/src/main/java/org/qora/repository/hsqldb/HSQLDBRepositoryFactory.java b/src/main/java/org/qora/repository/hsqldb/HSQLDBRepositoryFactory.java index 00040812..7e65b606 100644 --- a/src/main/java/org/qora/repository/hsqldb/HSQLDBRepositoryFactory.java +++ b/src/main/java/org/qora/repository/hsqldb/HSQLDBRepositoryFactory.java @@ -3,6 +3,7 @@ package org.qora.repository.hsqldb; import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; +import java.sql.Statement; import java.util.Properties; import org.apache.logging.log4j.LogManager; @@ -31,9 +32,10 @@ public class HSQLDBRepositoryFactory implements RepositoryFactory { // Check no-one else is accessing database try (Connection connection = DriverManager.getConnection(this.connectionUrl)) { + // We only need to check we can obtain connection. It will be auto-closed. } catch (SQLException e) { Throwable cause = e.getCause(); - if (cause == null || !(cause instanceof HsqlException)) + if (!(cause instanceof HsqlException)) throw new DataException("Unable to open repository: " + e.getMessage()); HsqlException he = (HsqlException) cause; @@ -84,7 +86,7 @@ public class HSQLDBRepositoryFactory implements RepositoryFactory { if (delay > SLOW_CONNECTION_THRESHOLD) // This could be an indication of excessive repository use, or insufficient pool size - LOGGER.warn(String.format("Fetching repository connection from pool took %dms (threshold: %dms)"), delay, SLOW_CONNECTION_THRESHOLD); + LOGGER.warn(() -> String.format("Fetching repository connection from pool took %dms (threshold: %dms)", delay, SLOW_CONNECTION_THRESHOLD)); setupConnection(connection); return connection; @@ -112,8 +114,9 @@ public class HSQLDBRepositoryFactory implements RepositoryFactory { this.connectionPool.close(0); // Now that all connections are closed, create a dedicated connection to shut down repository - try (Connection connection = DriverManager.getConnection(this.connectionUrl)) { - connection.createStatement().execute("SHUTDOWN"); + try (Connection connection = DriverManager.getConnection(this.connectionUrl); + Statement stmt = connection.createStatement()) { + stmt.execute("SHUTDOWN"); } } catch (SQLException e) { throw new DataException("Error during repository shutdown", e); diff --git a/src/main/java/org/qora/repository/hsqldb/HSQLDBSaver.java b/src/main/java/org/qora/repository/hsqldb/HSQLDBSaver.java index a9b49c03..d2222e8e 100644 --- a/src/main/java/org/qora/repository/hsqldb/HSQLDBSaver.java +++ b/src/main/java/org/qora/repository/hsqldb/HSQLDBSaver.java @@ -22,8 +22,8 @@ public class HSQLDBSaver { private String table; - private List columns = new ArrayList(); - private List objects = new ArrayList(); + private List columns = new ArrayList<>(); + private List objects = new ArrayList<>(); /** * Construct a SaveHelper, using SQL Connection and table name. diff --git a/src/main/java/org/qora/repository/hsqldb/HSQLDBVotingRepository.java b/src/main/java/org/qora/repository/hsqldb/HSQLDBVotingRepository.java index d93eca35..b760bf21 100644 --- a/src/main/java/org/qora/repository/hsqldb/HSQLDBVotingRepository.java +++ b/src/main/java/org/qora/repository/hsqldb/HSQLDBVotingRepository.java @@ -41,7 +41,7 @@ public class HSQLDBVotingRepository implements VotingRepository { if (optionsResultSet == null) return null; - List pollOptions = new ArrayList(); + List pollOptions = new ArrayList<>(); // NOTE: do-while because checkedExecute() above has already called rs.next() for us do { @@ -112,7 +112,7 @@ public class HSQLDBVotingRepository implements VotingRepository { @Override public List getVotes(String pollName) throws DataException { String sql = "SELECT voter, option_index FROM PollVotes WHERE poll_name = ?"; - List votes = new ArrayList(); + List votes = new ArrayList<>(); try (ResultSet resultSet = this.repository.checkedExecute(sql, pollName)) { if (resultSet == null) diff --git a/src/main/java/org/qora/repository/hsqldb/transaction/HSQLDBArbitraryTransactionRepository.java b/src/main/java/org/qora/repository/hsqldb/transaction/HSQLDBArbitraryTransactionRepository.java index e4276844..bcf76d3e 100644 --- a/src/main/java/org/qora/repository/hsqldb/transaction/HSQLDBArbitraryTransactionRepository.java +++ b/src/main/java/org/qora/repository/hsqldb/transaction/HSQLDBArbitraryTransactionRepository.java @@ -65,6 +65,7 @@ public class HSQLDBArbitraryTransactionRepository extends HSQLDBTransactionRepos this.savePayments(transactionData.getSignature(), arbitraryTransactionData.getPayments()); } + @Override public void delete(TransactionData transactionData) throws DataException { ArbitraryTransactionData arbitraryTransactionData = (ArbitraryTransactionData) transactionData; diff --git a/src/main/java/org/qora/repository/hsqldb/transaction/HSQLDBCreatePollTransactionRepository.java b/src/main/java/org/qora/repository/hsqldb/transaction/HSQLDBCreatePollTransactionRepository.java index a1ea96f5..39988a3d 100644 --- a/src/main/java/org/qora/repository/hsqldb/transaction/HSQLDBCreatePollTransactionRepository.java +++ b/src/main/java/org/qora/repository/hsqldb/transaction/HSQLDBCreatePollTransactionRepository.java @@ -36,7 +36,7 @@ public class HSQLDBCreatePollTransactionRepository extends HSQLDBTransactionRepo if (optionsResultSet == null) return null; - List pollOptions = new ArrayList(); + List pollOptions = new ArrayList<>(); // NOTE: do-while because checkedExecute() above has already called rs.next() for us do { diff --git a/src/main/java/org/qora/repository/hsqldb/transaction/HSQLDBTransactionRepository.java b/src/main/java/org/qora/repository/hsqldb/transaction/HSQLDBTransactionRepository.java index ca423bf0..f1f921d6 100644 --- a/src/main/java/org/qora/repository/hsqldb/transaction/HSQLDBTransactionRepository.java +++ b/src/main/java/org/qora/repository/hsqldb/transaction/HSQLDBTransactionRepository.java @@ -9,7 +9,7 @@ import java.sql.SQLException; import java.sql.Timestamp; import java.util.ArrayList; import java.util.Calendar; -import java.util.HashMap; +import java.util.EnumMap; import java.util.List; import java.util.Map; @@ -105,16 +105,13 @@ public class HSQLDBTransactionRepository implements TransactionRepository { for (TransactionType txType : TransactionType.values()) { RepositorySubclassInfo subclassInfo = subclassInfos[txType.value]; - if (subclassInfo == null) - continue; - - if (subclassInfo.constructor == null) + if (subclassInfo == null || subclassInfo.constructor == null) continue; try { this.repositoryByTxType[txType.value] = (HSQLDBTransactionRepository) subclassInfo.constructor.newInstance(repository); } catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException | InstantiationException e) { - continue; + LOGGER.debug(String.format("HSQLDBTransactionRepository subclass constructor failed for transaction type \"%s\"", txType.name())); } } } @@ -152,9 +149,7 @@ public class HSQLDBTransactionRepository implements TransactionRepository { approvalHeight = null; BaseTransactionData baseTransactionData = new BaseTransactionData(timestamp, txGroupId, reference, creatorPublicKey, fee, approvalStatus, blockHeight, approvalHeight, signature); - TransactionData transactionData = this.fromBase(type, baseTransactionData); - - return transactionData; + return this.fromBase(type, baseTransactionData); } catch (SQLException e) { throw new DataException("Unable to fetch transaction from repository", e); } @@ -187,9 +182,7 @@ public class HSQLDBTransactionRepository implements TransactionRepository { approvalHeight = null; BaseTransactionData baseTransactionData = new BaseTransactionData(timestamp, txGroupId, reference, creatorPublicKey, fee, approvalStatus, blockHeight, approvalHeight, signature); - TransactionData transactionData = this.fromBase(type, baseTransactionData); - - return transactionData; + return this.fromBase(type, baseTransactionData); } catch (SQLException e) { throw new DataException("Unable to fetch transaction from repository", e); } @@ -242,7 +235,7 @@ public class HSQLDBTransactionRepository implements TransactionRepository { protected List getPaymentsFromSignature(byte[] signature) throws DataException { String sql = "SELECT recipient, amount, asset_id FROM SharedTransactionPayments WHERE signature = ?"; - List payments = new ArrayList(); + List payments = new ArrayList<>(); try (ResultSet resultSet = this.repository.checkedExecute(sql, signature)) { if (resultSet == null) @@ -314,7 +307,7 @@ public class HSQLDBTransactionRepository implements TransactionRepository { public List getSignaturesInvolvingAddress(String address) throws DataException { String sql = "SELECT signature FROM TransactionRecipients WHERE participant = ?"; - List signatures = new ArrayList(); + List signatures = new ArrayList<>(); try (ResultSet resultSet = this.repository.checkedExecute(sql, address)) { if (resultSet == null) @@ -366,7 +359,7 @@ public class HSQLDBTransactionRepository implements TransactionRepository { + "WHERE block_height BETWEEN ? AND ? " + "GROUP BY type"; - Map transactionCounts = new HashMap<>(); + Map transactionCounts = new EnumMap<>(TransactionType.class); try (ResultSet resultSet = this.repository.checkedExecute(sql, startHeight, endHeight)) { if (resultSet == null) @@ -389,7 +382,7 @@ public class HSQLDBTransactionRepository implements TransactionRepository { public List getSignaturesMatchingCriteria(Integer startBlock, Integer blockLimit, Integer txGroupId, List txTypes, Integer service, String address, ConfirmationStatus confirmationStatus, Integer limit, Integer offset, Boolean reverse) throws DataException { - List signatures = new ArrayList(); + List signatures = new ArrayList<>(); boolean hasAddress = address != null && !address.isEmpty(); boolean hasTxTypes = txTypes != null && !txTypes.isEmpty(); @@ -399,9 +392,9 @@ public class HSQLDBTransactionRepository implements TransactionRepository { startBlock = (reverse == null || !reverse) ? 1 : this.repository.getBlockRepository().getBlockchainHeight() - blockLimit; String signatureColumn = "Transactions.signature"; - List whereClauses = new ArrayList(); + List whereClauses = new ArrayList<>(); String groupBy = null; - List bindParams = new ArrayList(); + List bindParams = new ArrayList<>(); // Tables, starting with Transactions StringBuilder tables = new StringBuilder(256); @@ -579,7 +572,7 @@ public class HSQLDBTransactionRepository implements TransactionRepository { HSQLDBRepository.limitOffsetSql(sql, limit, offset); - List transactions = new ArrayList(); + List transactions = new ArrayList<>(); try (ResultSet resultSet = this.repository.checkedExecute(sql.toString())) { if (resultSet == null) @@ -693,7 +686,7 @@ public class HSQLDBTransactionRepository implements TransactionRepository { HSQLDBRepository.limitOffsetSql(sql, limit, offset); - List transactions = new ArrayList(); + List transactions = new ArrayList<>(); // Find transactions with no corresponding row in BlockTransactions try (ResultSet resultSet = this.repository.checkedExecute(sql.toString(), bindParams)) { @@ -729,7 +722,7 @@ public class HSQLDBTransactionRepository implements TransactionRepository { sql.append(" AND Transactions.block_height < ? - Groups.min_block_delay"); - List transactions = new ArrayList(); + List transactions = new ArrayList<>(); try (ResultSet resultSet = this.repository.checkedExecute(sql.toString(), blockHeight)) { if (resultSet == null) @@ -764,7 +757,7 @@ public class HSQLDBTransactionRepository implements TransactionRepository { sql.append(" AND Transactions.block_height < ? - Groups.max_block_delay"); - List transactions = new ArrayList(); + List transactions = new ArrayList<>(); try (ResultSet resultSet = this.repository.checkedExecute(sql.toString(), blockHeight)) { if (resultSet == null) @@ -925,7 +918,7 @@ public class HSQLDBTransactionRepository implements TransactionRepository { HSQLDBRepository.limitOffsetSql(sql, limit, offset); - List transactions = new ArrayList(); + List transactions = new ArrayList<>(); // Find transactions with no corresponding row in BlockTransactions try (ResultSet resultSet = this.repository.checkedExecute(sql.toString())) { diff --git a/src/main/java/org/qora/settings/Settings.java b/src/main/java/org/qora/settings/Settings.java index 883156fa..f9fb0858 100644 --- a/src/main/java/org/qora/settings/Settings.java +++ b/src/main/java/org/qora/settings/Settings.java @@ -94,8 +94,8 @@ public class Settings { // Auto-update sources private String[] autoUpdateRepos = new String[] { - "https://github.com/catbref/qora-core/raw/%s/qora-core.jar", - "https://raw.githubusercontent.com@151.101.16.133/catbref/qora-core/%s/qora-core.jar" + "https://github.com/QORT/qortal/raw/%s/qora-core.jar", + "https://raw.githubusercontent.com@151.101.16.133/QORT/qortal/%s/qora-core.jar" }; /** Array of NTP server hostnames. */ @@ -171,7 +171,7 @@ public class Settings { String path = ""; do { - LOGGER.info("Using settings file: " + path + filename); + LOGGER.info(String.format("Using settings file: %s%s", path, filename)); // Create the StreamSource by creating Reader to the JSON input try (Reader settingsReader = new FileReader(path + filename)) { diff --git a/src/main/java/org/qora/transaction/ArbitraryTransaction.java b/src/main/java/org/qora/transaction/ArbitraryTransaction.java index 0108e514..0963522a 100644 --- a/src/main/java/org/qora/transaction/ArbitraryTransaction.java +++ b/src/main/java/org/qora/transaction/ArbitraryTransaction.java @@ -35,7 +35,7 @@ public class ArbitraryTransaction extends Transaction { @Override public List getRecipientAccounts() throws DataException { - List recipients = new ArrayList(); + List recipients = new ArrayList<>(); if (arbitraryTransactionData.getVersion() != 1) for (PaymentData paymentData : arbitraryTransactionData.getPayments()) @@ -92,7 +92,7 @@ public class ArbitraryTransaction extends Transaction { @Override public ValidationResult isValid() throws DataException { // Are arbitrary transactions even allowed at this point? - if (arbitraryTransactionData.getVersion() != ArbitraryTransaction.getVersionByTimestamp(arbitraryTransactionData.getTimestamp())) + if (arbitraryTransactionData.getVersion() != Transaction.getVersionByTimestamp(arbitraryTransactionData.getTimestamp())) return ValidationResult.NOT_YET_RELEASED; if (this.arbitraryTransactionData.getTimestamp() < BlockChain.getInstance().getArbitraryReleaseTimestamp()) diff --git a/src/main/java/org/qora/transaction/AtTransaction.java b/src/main/java/org/qora/transaction/AtTransaction.java index f90bd299..2587fd55 100644 --- a/src/main/java/org/qora/transaction/AtTransaction.java +++ b/src/main/java/org/qora/transaction/AtTransaction.java @@ -57,7 +57,7 @@ public class AtTransaction extends Transaction { /** For AT-Transactions, the use the AT address instead of transaction creator (which is genesis account) */ @Override public List getInvolvedAccounts() throws DataException { - List participants = new ArrayList(getRecipientAccounts()); + List participants = new ArrayList<>(getRecipientAccounts()); participants.add(getATAccount()); return participants; } diff --git a/src/main/java/org/qora/transaction/CancelAssetOrderTransaction.java b/src/main/java/org/qora/transaction/CancelAssetOrderTransaction.java index 0b456f95..1aeb0799 100644 --- a/src/main/java/org/qora/transaction/CancelAssetOrderTransaction.java +++ b/src/main/java/org/qora/transaction/CancelAssetOrderTransaction.java @@ -33,7 +33,7 @@ public class CancelAssetOrderTransaction extends Transaction { @Override public List getRecipientAccounts() { - return new ArrayList(); + return new ArrayList<>(); } @Override diff --git a/src/main/java/org/qora/transaction/CancelSellNameTransaction.java b/src/main/java/org/qora/transaction/CancelSellNameTransaction.java index ab18a3b3..e2cb6dc6 100644 --- a/src/main/java/org/qora/transaction/CancelSellNameTransaction.java +++ b/src/main/java/org/qora/transaction/CancelSellNameTransaction.java @@ -33,7 +33,7 @@ public class CancelSellNameTransaction extends Transaction { @Override public List getRecipientAccounts() { - return new ArrayList(); + return new ArrayList<>(); } @Override diff --git a/src/main/java/org/qora/transaction/CreateAssetOrderTransaction.java b/src/main/java/org/qora/transaction/CreateAssetOrderTransaction.java index 308492a6..4c70ac8d 100644 --- a/src/main/java/org/qora/transaction/CreateAssetOrderTransaction.java +++ b/src/main/java/org/qora/transaction/CreateAssetOrderTransaction.java @@ -35,7 +35,7 @@ public class CreateAssetOrderTransaction extends Transaction { @Override public List getRecipientAccounts() { - return new ArrayList(); + return new ArrayList<>(); } @Override diff --git a/src/main/java/org/qora/transaction/DeployAtTransaction.java b/src/main/java/org/qora/transaction/DeployAtTransaction.java index 75aa3947..985290e1 100644 --- a/src/main/java/org/qora/transaction/DeployAtTransaction.java +++ b/src/main/java/org/qora/transaction/DeployAtTransaction.java @@ -1,9 +1,9 @@ package org.qora.transaction; -import java.io.UnsupportedEncodingException; import java.math.BigDecimal; import java.nio.ByteBuffer; import java.nio.ByteOrder; +import java.nio.charset.StandardCharsets; import java.util.ArrayList; import java.util.List; @@ -46,7 +46,7 @@ public class DeployAtTransaction extends Transaction { @Override public List getRecipientAccounts() throws DataException { - return new ArrayList(); + return new ArrayList<>(); } @Override @@ -79,8 +79,7 @@ public class DeployAtTransaction extends Transaction { /** Returns AT version from the header bytes */ private short getVersion() { byte[] creationBytes = deployATTransactionData.getCreationBytes(); - short version = (short) (creationBytes[0] | (creationBytes[1] << 8)); // Little-endian - return version; + return (short) ((creationBytes[0] & 0xff) | (creationBytes[1] << 8)); // Little-endian } /** Make sure deployATTransactionData has an ATAddress */ @@ -92,29 +91,25 @@ public class DeployAtTransaction extends Transaction { if (blockHeight == 0) blockHeight = this.repository.getBlockRepository().getBlockchainHeight() + 1; - try { - byte[] name = this.deployATTransactionData.getName().getBytes("UTF-8"); - byte[] description = this.deployATTransactionData.getDescription().replaceAll("\\s", "").getBytes("UTF-8"); - byte[] creatorPublicKey = this.deployATTransactionData.getCreatorPublicKey(); - byte[] creationBytes = this.deployATTransactionData.getCreationBytes(); + byte[] name = this.deployATTransactionData.getName().getBytes(StandardCharsets.UTF_8); + byte[] description = this.deployATTransactionData.getDescription().replaceAll("\\s", "").getBytes(StandardCharsets.UTF_8); + byte[] creatorPublicKey = this.deployATTransactionData.getCreatorPublicKey(); + byte[] creationBytes = this.deployATTransactionData.getCreationBytes(); - ByteBuffer byteBuffer = ByteBuffer - .allocate(name.length + description.length + creatorPublicKey.length + creationBytes.length + Transformer.INT_LENGTH); + ByteBuffer byteBuffer = ByteBuffer + .allocate(name.length + description.length + creatorPublicKey.length + creationBytes.length + Transformer.INT_LENGTH); - byteBuffer.order(ByteOrder.LITTLE_ENDIAN); + byteBuffer.order(ByteOrder.LITTLE_ENDIAN); - byteBuffer.put(name); - byteBuffer.put(description); - byteBuffer.put(creatorPublicKey); - byteBuffer.put(creationBytes); - byteBuffer.putInt(blockHeight); + byteBuffer.put(name); + byteBuffer.put(description); + byteBuffer.put(creatorPublicKey); + byteBuffer.put(creationBytes); + byteBuffer.putInt(blockHeight); - String atAddress = Crypto.toATAddress(byteBuffer.array()); + String atAddress = Crypto.toATAddress(byteBuffer.array()); - this.deployATTransactionData.setAtAddress(atAddress); - } catch (UnsupportedEncodingException e) { - throw new DataException("Unable to generate AT account from Deploy AT transaction data", e); - } + this.deployATTransactionData.setAtAddress(atAddress); } // Navigation diff --git a/src/main/java/org/qora/transaction/MessageTransaction.java b/src/main/java/org/qora/transaction/MessageTransaction.java index 73639f80..15639524 100644 --- a/src/main/java/org/qora/transaction/MessageTransaction.java +++ b/src/main/java/org/qora/transaction/MessageTransaction.java @@ -90,7 +90,7 @@ public class MessageTransaction extends Transaction { @Override public ValidationResult isValid() throws DataException { // Are message transactions even allowed at this point? - if (messageTransactionData.getVersion() != MessageTransaction.getVersionByTimestamp(messageTransactionData.getTimestamp())) + if (messageTransactionData.getVersion() != Transaction.getVersionByTimestamp(messageTransactionData.getTimestamp())) return ValidationResult.NOT_YET_RELEASED; if (this.repository.getBlockRepository().getBlockchainHeight() < BlockChain.getInstance().getMessageReleaseHeight()) diff --git a/src/main/java/org/qora/transaction/MultiPaymentTransaction.java b/src/main/java/org/qora/transaction/MultiPaymentTransaction.java index c5e5aed6..c87b02ac 100644 --- a/src/main/java/org/qora/transaction/MultiPaymentTransaction.java +++ b/src/main/java/org/qora/transaction/MultiPaymentTransaction.java @@ -35,7 +35,7 @@ public class MultiPaymentTransaction extends Transaction { @Override public List getRecipientAccounts() throws DataException { - List recipients = new ArrayList(); + List recipients = new ArrayList<>(); for (PaymentData paymentData : multiPaymentTransactionData.getPayments()) recipients.add(new Account(this.repository, paymentData.getRecipient())); @@ -95,7 +95,7 @@ public class MultiPaymentTransaction extends Transaction { return ValidationResult.NOT_YET_RELEASED; // Check number of payments - if (payments.size() < 1 || payments.size() > MAX_PAYMENTS_COUNT) + if (payments.isEmpty() || payments.size() > MAX_PAYMENTS_COUNT) return ValidationResult.INVALID_PAYMENTS_COUNT; // Check reference is correct diff --git a/src/main/java/org/qora/transaction/SellNameTransaction.java b/src/main/java/org/qora/transaction/SellNameTransaction.java index de5cca4d..cf891c94 100644 --- a/src/main/java/org/qora/transaction/SellNameTransaction.java +++ b/src/main/java/org/qora/transaction/SellNameTransaction.java @@ -36,7 +36,7 @@ public class SellNameTransaction extends Transaction { @Override public List getRecipientAccounts() { - return new ArrayList(); + return new ArrayList<>(); } @Override diff --git a/src/main/java/org/qora/transaction/Transaction.java b/src/main/java/org/qora/transaction/Transaction.java index 2ed1e146..98f009b8 100644 --- a/src/main/java/org/qora/transaction/Transaction.java +++ b/src/main/java/org/qora/transaction/Transaction.java @@ -7,6 +7,7 @@ import java.math.RoundingMode; import java.util.ArrayList; import java.util.Arrays; import java.util.Comparator; +import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.concurrent.locks.ReentrantLock; @@ -91,7 +92,7 @@ public abstract class Transaction { public final Class clazz; public final Constructor constructor; - private final static Map map = stream(TransactionType.values()).collect(toMap(type -> type.value, type -> type)); + private static final Map map = stream(TransactionType.values()).collect(toMap(type -> type.value, type -> type)); TransactionType(int value, boolean needsApproval) { this.value = value; @@ -105,14 +106,14 @@ public abstract class Transaction { this.className = String.join("", classNameParts); - Class clazz = null; - Constructor constructor = null; + Class subClazz = null; + Constructor subConstructor = null; try { - clazz = Class.forName(String.join("", Transaction.class.getPackage().getName(), ".", this.className, "Transaction")); + subClazz = Class.forName(String.join("", Transaction.class.getPackage().getName(), ".", this.className, "Transaction")); try { - constructor = clazz.getConstructor(Repository.class, TransactionData.class); + subConstructor = subClazz.getConstructor(Repository.class, TransactionData.class); } catch (NoSuchMethodException | SecurityException e) { LOGGER.debug(String.format("Transaction subclass constructor not found for transaction type \"%s\"", this.name())); } @@ -120,8 +121,8 @@ public abstract class Transaction { LOGGER.debug(String.format("Transaction subclass not found for transaction type \"%s\"", this.name())); } - this.clazz = clazz; - this.constructor = constructor; + this.clazz = subClazz; + this.constructor = subConstructor; } public static TransactionType valueOf(int value) { @@ -140,7 +141,7 @@ public abstract class Transaction { public final int value; - private final static Map map = stream(ApprovalStatus.values()).collect(toMap(result -> result.value, result -> result)); + private static final Map map = stream(ApprovalStatus.values()).collect(toMap(result -> result.value, result -> result)); ApprovalStatus(int value) { this.value = value; @@ -244,7 +245,7 @@ public abstract class Transaction { public final int value; - private final static Map map = stream(ValidationResult.values()).collect(toMap(result -> result.value, result -> result)); + private static final Map map = stream(ValidationResult.values()).collect(toMap(result -> result.value, result -> result)); ValidationResult(int value) { this.value = value; @@ -417,7 +418,7 @@ public abstract class Transaction { */ public List getInvolvedAccounts() throws DataException { // Typically this is all the recipients plus the transaction creator/sender - List participants = new ArrayList(getRecipientAccounts()); + List participants = new ArrayList<>(getRecipientAccounts()); participants.add(getCreator()); return participants; } @@ -622,8 +623,8 @@ public abstract class Transaction { List unconfirmedTransactions = repository.getTransactionRepository().getUnconfirmedTransactions(); int count = 0; - for (TransactionData transactionData : unconfirmedTransactions) { - Transaction transaction = Transaction.fromData(repository, transactionData); + for (TransactionData unconfirmedTransactionData : unconfirmedTransactions) { + Transaction transaction = Transaction.fromData(repository, unconfirmedTransactionData); PublicKeyAccount otherCreator = transaction.getCreator(); if (Arrays.equals(creator.getPublicKey(), otherCreator.getPublicKey())) @@ -662,14 +663,14 @@ public abstract class Transaction { repository.discardChanges(); try { - for (int i = 0; i < unconfirmedTransactions.size(); ++i) { - TransactionData transactionData = unconfirmedTransactions.get(i); + Iterator unconfirmedTransactionsIterator = unconfirmedTransactions.iterator(); + while (unconfirmedTransactionsIterator.hasNext()) { + TransactionData transactionData = unconfirmedTransactionsIterator.next(); - if (!isStillValidUnconfirmed(repository, transactionData, latestBlockData.getTimestamp())) { - unconfirmedTransactions.remove(i); - --i; + if (isStillValidUnconfirmed(repository, transactionData, latestBlockData.getTimestamp())) continue; - } + + unconfirmedTransactionsIterator.remove(); } } finally { // Throw away temporary updates to account lastReference @@ -713,16 +714,15 @@ public abstract class Transaction { repository.discardChanges(); try { - for (int i = 0; i < unconfirmedTransactions.size(); ++i) { - TransactionData transactionData = unconfirmedTransactions.get(i); + Iterator unconfirmedTransactionsIterator = unconfirmedTransactions.iterator(); + while (unconfirmedTransactionsIterator.hasNext()) { + TransactionData transactionData = unconfirmedTransactionsIterator.next(); - if (!isStillValidUnconfirmed(repository, transactionData, latestBlockData.getTimestamp())) { - invalidTransactions.add(transactionData); - - unconfirmedTransactions.remove(i); - --i; + if (isStillValidUnconfirmed(repository, transactionData, latestBlockData.getTimestamp())) continue; - } + + invalidTransactions.add(transactionData); + unconfirmedTransactionsIterator.remove(); } } finally { // Throw away temporary updates to account lastReference @@ -927,7 +927,7 @@ public abstract class Transaction { */ public ValidationResult isProcessable() throws DataException { return ValidationResult.OK; - }; + } /** * Actually process a transaction, updating the blockchain. diff --git a/src/main/java/org/qora/transaction/VoteOnPollTransaction.java b/src/main/java/org/qora/transaction/VoteOnPollTransaction.java index 0b38bd61..3bb63d02 100644 --- a/src/main/java/org/qora/transaction/VoteOnPollTransaction.java +++ b/src/main/java/org/qora/transaction/VoteOnPollTransaction.java @@ -41,7 +41,7 @@ public class VoteOnPollTransaction extends Transaction { @Override public List getRecipientAccounts() { - return new ArrayList(); + return new ArrayList<>(); } @Override @@ -151,15 +151,13 @@ public class VoteOnPollTransaction extends Transaction { Integer previousOptionIndex = voteOnPollTransactionData.getPreviousOptionIndex(); if (previousOptionIndex != null) { // Reinstate previous vote - LOGGER.trace("Reinstating previous vote by " + voter.getAddress() + " on poll \"" + voteOnPollTransactionData.getPollName() - + "\" with option index " + previousOptionIndex); + LOGGER.trace(() -> String.format("Reinstating previous vote by %s on poll \"%s\" with option index %d", voter.getAddress(), voteOnPollTransactionData.getPollName(), previousOptionIndex)); VoteOnPollData previousVoteOnPollData = new VoteOnPollData(voteOnPollTransactionData.getPollName(), voteOnPollTransactionData.getVoterPublicKey(), previousOptionIndex); votingRepository.save(previousVoteOnPollData); } else { // Delete vote - LOGGER.trace("Deleting vote by " + voter.getAddress() + " on poll \"" + voteOnPollTransactionData.getPollName() + "\" with option index " - + voteOnPollTransactionData.getOptionIndex()); + LOGGER.trace(() -> String.format("Deleting vote by %s on poll \"%s\" with option index %d", voter.getAddress(), voteOnPollTransactionData.getPollName(), voteOnPollTransactionData.getOptionIndex())); votingRepository.delete(voteOnPollTransactionData.getPollName(), voteOnPollTransactionData.getVoterPublicKey()); } diff --git a/src/main/java/org/qora/transform/PaymentTransformer.java b/src/main/java/org/qora/transform/PaymentTransformer.java index d49541cd..4c6cf241 100644 --- a/src/main/java/org/qora/transform/PaymentTransformer.java +++ b/src/main/java/org/qora/transform/PaymentTransformer.java @@ -7,7 +7,6 @@ import java.nio.ByteBuffer; import org.json.simple.JSONObject; import org.qora.data.PaymentData; -import org.qora.transform.TransformationException; import org.qora.utils.Serialization; import com.google.common.primitives.Longs; diff --git a/src/main/java/org/qora/transform/block/BlockTransformer.java b/src/main/java/org/qora/transform/block/BlockTransformer.java index a569cba2..32ab8d13 100644 --- a/src/main/java/org/qora/transform/block/BlockTransformer.java +++ b/src/main/java/org/qora/transform/block/BlockTransformer.java @@ -109,7 +109,7 @@ public class BlockTransformer extends Transformer { int atCount = 0; BigDecimal atFees = BigDecimal.ZERO.setScale(8); - List atStates = new ArrayList(); + List atStates = new ArrayList<>(); if (version >= 2) { int atBytesLength = byteBuffer.getInt(); @@ -172,7 +172,7 @@ public class BlockTransformer extends Transformer { int transactionCount = byteBuffer.getInt(); // Parse transactions now, compared to deferred parsing in Gen1, so we can throw ParseException if need be. - List transactions = new ArrayList(); + List transactions = new ArrayList<>(); for (int t = 0; t < transactionCount; ++t) { if (byteBuffer.remaining() < TRANSACTION_SIZE_LENGTH) @@ -244,7 +244,7 @@ public class BlockTransformer extends Transformer { BlockData blockData = new BlockData(version, reference, transactionCount, totalFees, transactionsSignature, height, timestamp, generatorPublicKey, generatorSignature, atCount, atFees, encodedOnlineAccounts, onlineAccountsCount, onlineAccountsTimestamp, onlineAccountsSignatures); - return new Triple, List>(blockData, transactions, atStates); + return new Triple<>(blockData, transactions, atStates); } public static int getDataLength(Block block) throws TransformationException { diff --git a/src/main/java/org/qora/transform/transaction/ArbitraryTransactionTransformer.java b/src/main/java/org/qora/transform/transaction/ArbitraryTransactionTransformer.java index 513a4fee..86957995 100644 --- a/src/main/java/org/qora/transform/transaction/ArbitraryTransactionTransformer.java +++ b/src/main/java/org/qora/transform/transaction/ArbitraryTransactionTransformer.java @@ -16,6 +16,7 @@ import org.qora.data.transaction.BaseTransactionData; import org.qora.data.transaction.TransactionData; import org.qora.data.transaction.ArbitraryTransactionData.DataType; import org.qora.transaction.ArbitraryTransaction; +import org.qora.transaction.Transaction; import org.qora.transaction.Transaction.TransactionType; import org.qora.transform.PaymentTransformer; import org.qora.transform.TransformationException; @@ -59,7 +60,7 @@ public class ArbitraryTransactionTransformer extends TransactionTransformer { public static TransactionData fromByteBuffer(ByteBuffer byteBuffer) throws TransformationException { long timestamp = byteBuffer.getLong(); - int version = ArbitraryTransaction.getVersionByTimestamp(timestamp); + int version = Transaction.getVersionByTimestamp(timestamp); int txGroupId = 0; if (timestamp >= BlockChain.getInstance().getQoraV2Timestamp()) @@ -71,7 +72,7 @@ public class ArbitraryTransactionTransformer extends TransactionTransformer { byte[] senderPublicKey = Serialization.deserializePublicKey(byteBuffer); // V3+ allows payments but always return a list of payments, even if empty - List payments = new ArrayList(); + List payments = new ArrayList<>(); if (version != 1) { int paymentsCount = byteBuffer.getInt(); @@ -182,7 +183,7 @@ public class ArbitraryTransactionTransformer extends TransactionTransformer { // In v1, a coding error means that all bytes prior to final payment entry are lost! // If there are no payments then we can skip mangling - if (arbitraryTransactionData.getPayments().size() == 0) + if (arbitraryTransactionData.getPayments().isEmpty()) return bytes; // So we're left with: final payment entry, service, data size, data, fee diff --git a/src/main/java/org/qora/transform/transaction/CreatePollTransactionTransformer.java b/src/main/java/org/qora/transform/transaction/CreatePollTransactionTransformer.java index f727bf95..b37063ae 100644 --- a/src/main/java/org/qora/transform/transaction/CreatePollTransactionTransformer.java +++ b/src/main/java/org/qora/transform/transaction/CreatePollTransactionTransformer.java @@ -72,7 +72,7 @@ public class CreatePollTransactionTransformer extends TransactionTransformer { if (optionsCount < 1 || optionsCount > Poll.MAX_OPTIONS) throw new TransformationException("Invalid number of options for CreatePollTransaction"); - List pollOptions = new ArrayList(); + List pollOptions = new ArrayList<>(); for (int optionIndex = 0; optionIndex < optionsCount; ++optionIndex) { String optionName = Serialization.deserializeSizedString(byteBuffer, Poll.MAX_NAME_SIZE); diff --git a/src/main/java/org/qora/transform/transaction/DeployAtTransactionTransformer.java b/src/main/java/org/qora/transform/transaction/DeployAtTransactionTransformer.java index 8f1a79d4..64972978 100644 --- a/src/main/java/org/qora/transform/transaction/DeployAtTransactionTransformer.java +++ b/src/main/java/org/qora/transform/transaction/DeployAtTransactionTransformer.java @@ -11,6 +11,7 @@ import org.qora.data.transaction.BaseTransactionData; import org.qora.data.transaction.DeployAtTransactionData; import org.qora.data.transaction.TransactionData; import org.qora.transaction.DeployAtTransaction; +import org.qora.transaction.Transaction; import org.qora.transaction.Transaction.TransactionType; import org.qora.transform.TransformationException; import org.qora.utils.Serialization; @@ -59,7 +60,7 @@ public class DeployAtTransactionTransformer extends TransactionTransformer { public static TransactionData fromByteBuffer(ByteBuffer byteBuffer) throws TransformationException { long timestamp = byteBuffer.getLong(); - int version = DeployAtTransaction.getVersionByTimestamp(timestamp); + int version = Transaction.getVersionByTimestamp(timestamp); int txGroupId = 0; if (timestamp >= BlockChain.getInstance().getQoraV2Timestamp()) @@ -106,7 +107,7 @@ public class DeployAtTransactionTransformer extends TransactionTransformer { int dataLength = getBaseLength(transactionData) + EXTRAS_LENGTH; - int version = DeployAtTransaction.getVersionByTimestamp(transactionData.getTimestamp()); + int version = Transaction.getVersionByTimestamp(transactionData.getTimestamp()); // V4+ have assetId too if (version >= 4) @@ -123,7 +124,7 @@ public class DeployAtTransactionTransformer extends TransactionTransformer { try { DeployAtTransactionData deployATTransactionData = (DeployAtTransactionData) transactionData; - int version = DeployAtTransaction.getVersionByTimestamp(transactionData.getTimestamp()); + int version = Transaction.getVersionByTimestamp(transactionData.getTimestamp()); ByteArrayOutputStream bytes = new ByteArrayOutputStream(); diff --git a/src/main/java/org/qora/transform/transaction/MessageTransactionTransformer.java b/src/main/java/org/qora/transform/transaction/MessageTransactionTransformer.java index cd3a0694..f83daf42 100644 --- a/src/main/java/org/qora/transform/transaction/MessageTransactionTransformer.java +++ b/src/main/java/org/qora/transform/transaction/MessageTransactionTransformer.java @@ -11,6 +11,7 @@ import org.qora.data.transaction.BaseTransactionData; import org.qora.data.transaction.MessageTransactionData; import org.qora.data.transaction.TransactionData; import org.qora.transaction.MessageTransaction; +import org.qora.transaction.Transaction; import org.qora.transaction.Transaction.TransactionType; import org.qora.transform.TransformationException; import org.qora.utils.Serialization; @@ -53,7 +54,7 @@ public class MessageTransactionTransformer extends TransactionTransformer { public static TransactionData fromByteBuffer(ByteBuffer byteBuffer) throws TransformationException { long timestamp = byteBuffer.getLong(); - int version = MessageTransaction.getVersionByTimestamp(timestamp); + int version = Transaction.getVersionByTimestamp(timestamp); int txGroupId = 0; if (timestamp >= BlockChain.getInstance().getQoraV2Timestamp()) diff --git a/src/main/java/org/qora/transform/transaction/MultiPaymentTransactionTransformer.java b/src/main/java/org/qora/transform/transaction/MultiPaymentTransactionTransformer.java index 8bfb00c7..86bf768c 100644 --- a/src/main/java/org/qora/transform/transaction/MultiPaymentTransactionTransformer.java +++ b/src/main/java/org/qora/transform/transaction/MultiPaymentTransactionTransformer.java @@ -58,7 +58,7 @@ public class MultiPaymentTransactionTransformer extends TransactionTransformer { int paymentsCount = byteBuffer.getInt(); - List payments = new ArrayList(); + List payments = new ArrayList<>(); for (int i = 0; i < paymentsCount; ++i) payments.add(PaymentTransformer.fromByteBuffer(byteBuffer)); diff --git a/src/main/java/org/qora/transform/transaction/UpdateAssetTransactionTransformer.java b/src/main/java/org/qora/transform/transaction/UpdateAssetTransactionTransformer.java index 11b15f89..31bcffe4 100644 --- a/src/main/java/org/qora/transform/transaction/UpdateAssetTransactionTransformer.java +++ b/src/main/java/org/qora/transform/transaction/UpdateAssetTransactionTransformer.java @@ -80,11 +80,9 @@ public class UpdateAssetTransactionTransformer extends TransactionTransformer { public static int getDataLength(TransactionData transactionData) throws TransformationException { UpdateAssetTransactionData updateAssetTransactionData = (UpdateAssetTransactionData) transactionData; - int dataLength = getBaseLength(transactionData) + EXTRAS_LENGTH + return getBaseLength(transactionData) + EXTRAS_LENGTH + Utf8.encodedLength(updateAssetTransactionData.getNewDescription()) + Utf8.encodedLength(updateAssetTransactionData.getNewData()); - - return dataLength; } public static byte[] toBytes(TransactionData transactionData) throws TransformationException { diff --git a/src/main/java/org/qora/utils/BIP39.java b/src/main/java/org/qora/utils/BIP39.java index c5ef351e..99043726 100644 --- a/src/main/java/org/qora/utils/BIP39.java +++ b/src/main/java/org/qora/utils/BIP39.java @@ -40,7 +40,7 @@ public class BIP39 { bitShift = 0 - bitShift; entropy[byteIndex++] |= (byte) (wordListIndex >> bitShift); - entropy[byteIndex] |= (byte) ((wordListIndex << (8 - bitShift))); + entropy[byteIndex] |= (byte) (wordListIndex << (8 - bitShift)); bitShift = bitShift + BITS_PER_WORD - 8; } } diff --git a/src/main/java/org/qora/utils/ByteArray.java b/src/main/java/org/qora/utils/ByteArray.java index 2ca0182d..604e586b 100644 --- a/src/main/java/org/qora/utils/ByteArray.java +++ b/src/main/java/org/qora/utils/ByteArray.java @@ -27,7 +27,7 @@ public class ByteArray implements Comparable { public int hashCode() { int h = hash; if (h == 0 && value.length > 0) { - byte val[] = value; + byte[] val = value; for (int i = 0; i < val.length; ++i) h = 31 * h + val[i]; @@ -56,7 +56,7 @@ public class ByteArray implements Comparable { int b = otherValue[i] & 0xFF; if (a < b) return -1; - if (b > a) + if (a > b) return 1; } diff --git a/src/main/java/org/qora/utils/NTP.java b/src/main/java/org/qora/utils/NTP.java index 53851e79..6bae7564 100644 --- a/src/main/java/org/qora/utils/NTP.java +++ b/src/main/java/org/qora/utils/NTP.java @@ -53,7 +53,7 @@ public class NTP implements Runnable { this.remote = remote; } - public boolean poll(NTPUDPClient client) { + public boolean doPoll(NTPUDPClient client) { Thread.currentThread().setName(String.format("NTP: %s", this.remote)); try { @@ -161,9 +161,9 @@ public class NTP implements Runnable { while (!isStopping) { Thread.sleep(1000); - CompletionService ecs = new ExecutorCompletionService(serverExecutor); + CompletionService ecs = new ExecutorCompletionService<>(serverExecutor); for (NTPServer server : ntpServers) - ecs.submit(() -> server.poll(client)); + ecs.submit(() -> server.doPoll(client)); boolean hasUpdate = false; for (int i = 0; i < ntpServers.size(); ++i) { diff --git a/src/main/java/org/qora/utils/Serialization.java b/src/main/java/org/qora/utils/Serialization.java index 2587e84d..94bacfa7 100644 --- a/src/main/java/org/qora/utils/Serialization.java +++ b/src/main/java/org/qora/utils/Serialization.java @@ -6,6 +6,7 @@ import java.io.UnsupportedEncodingException; import java.math.BigDecimal; import java.math.BigInteger; import java.nio.ByteBuffer; +import java.nio.charset.StandardCharsets; import org.qora.transform.TransformationException; import org.qora.transform.Transformer; @@ -92,7 +93,7 @@ public class Serialization { } public static void serializeSizedString(ByteArrayOutputStream bytes, String string) throws UnsupportedEncodingException, IOException { - byte[] stringBytes = string.getBytes("UTF-8"); + byte[] stringBytes = string.getBytes(StandardCharsets.UTF_8); bytes.write(Ints.toByteArray(stringBytes.length)); bytes.write(stringBytes); } @@ -108,11 +109,7 @@ public class Serialization { byte[] bytes = new byte[size]; byteBuffer.get(bytes); - try { - return new String(bytes, "UTF-8"); - } catch (UnsupportedEncodingException e) { - throw new TransformationException("UTF-8 charset unsupported during string deserialization"); - } + return new String(bytes, StandardCharsets.UTF_8); } } diff --git a/src/main/java/org/qora/utils/StringLongMapXmlAdapter.java b/src/main/java/org/qora/utils/StringLongMapXmlAdapter.java index e5757f2d..eae5d8f0 100644 --- a/src/main/java/org/qora/utils/StringLongMapXmlAdapter.java +++ b/src/main/java/org/qora/utils/StringLongMapXmlAdapter.java @@ -16,7 +16,7 @@ public class StringLongMapXmlAdapter extends XmlAdapter entries = new ArrayList(); + List entries = new ArrayList<>(); } public static class MapEntry { diff --git a/src/test/java/org/qora/test/ByteArrayTests.java b/src/test/java/org/qora/test/ByteArrayTests.java index eb40eba1..8b59d77c 100644 --- a/src/test/java/org/qora/test/ByteArrayTests.java +++ b/src/test/java/org/qora/test/ByteArrayTests.java @@ -120,4 +120,14 @@ public class ByteArrayTests { System.out.println(String.format("Primitive hashCode: 0x%08x", copiedValue.hashCode())); } + @Test + public void testCompareTo() { + ByteArray testValue0 = new ByteArray(new byte[] { 0x00 }); + ByteArray testValue1 = new ByteArray(new byte[] { 0x01 }); + + assertEquals("0 should be the same as 0", 0, testValue0.compareTo(testValue0)); + assertEquals("0 should be before 1", -1, testValue0.compareTo(testValue1)); + assertEquals("1 should be after 0", 1, testValue1.compareTo(testValue0)); + } + }