target
stringlengths 20
113k
| src_fm
stringlengths 11
86.3k
| src_fm_fc
stringlengths 21
86.4k
| src_fm_fc_co
stringlengths 30
86.4k
| src_fm_fc_ms
stringlengths 42
86.8k
| src_fm_fc_ms_ff
stringlengths 43
86.8k
|
---|---|---|---|---|---|
@Test public void rememberLastBlockSeenHash() throws Exception { BigInteger v1 = toNanoCoins(5, 0); BigInteger v2 = toNanoCoins(0, 50); BigInteger v3 = toNanoCoins(0, 25); Transaction t1 = createFakeTx(params, v1, myAddress); Transaction t2 = createFakeTx(params, v2, myAddress); Transaction t3 = createFakeTx(params, v3, myAddress); Block genesis = blockStore.getChainHead().getHeader(); Block b10 = makeSolvedTestBlock(genesis, t1); Block b11 = makeSolvedTestBlock(genesis, t2); Block b2 = makeSolvedTestBlock(b10, t3); Block b3 = makeSolvedTestBlock(b2); chain.add(b10); assertEquals(b10.getHash(), wallet.getLastBlockSeenHash()); chain.add(b11); assertEquals(b10.getHash(), wallet.getLastBlockSeenHash()); chain.add(b2); assertEquals(b2.getHash(), wallet.getLastBlockSeenHash()); chain.add(b3); assertEquals(b3.getHash(), wallet.getLastBlockSeenHash()); } | public Sha256Hash getLastBlockSeenHash() { lock.lock(); try { return lastBlockSeenHash; } finally { lock.unlock(); } } | Wallet implements Serializable, BlockChainListener { public Sha256Hash getLastBlockSeenHash() { lock.lock(); try { return lastBlockSeenHash; } finally { lock.unlock(); } } } | Wallet implements Serializable, BlockChainListener { public Sha256Hash getLastBlockSeenHash() { lock.lock(); try { return lastBlockSeenHash; } finally { lock.unlock(); } } Wallet(NetworkParameters params); Wallet(NetworkParameters params, KeyCrypter keyCrypter); } | Wallet implements Serializable, BlockChainListener { public Sha256Hash getLastBlockSeenHash() { lock.lock(); try { return lastBlockSeenHash; } finally { lock.unlock(); } } Wallet(NetworkParameters params); Wallet(NetworkParameters params, KeyCrypter keyCrypter); NetworkParameters getNetworkParameters(); Iterable<ECKey> getKeys(); int getKeychainSize(); void saveToFile(File f); void setAcceptTimeLockedTransactions(boolean acceptTimeLockedTransactions); boolean doesAcceptTimeLockedTransactions(); void autosaveToFile(File f, long delayTime, TimeUnit timeUnit,
AutosaveEventListener eventListener); void saveToFileStream(OutputStream f); NetworkParameters getParams(); static Wallet loadFromFile(File f); boolean isConsistent(); static Wallet loadFromFileStream(InputStream stream); void notifyTransactionIsInBlock(Sha256Hash txHash, StoredBlock block,
BlockChain.NewBlockType blockType); void receivePending(Transaction tx, List<Transaction> dependencies); boolean isTransactionRelevant(Transaction tx); void receiveFromBlock(Transaction tx, StoredBlock block,
BlockChain.NewBlockType blockType); void notifyNewBestBlock(StoredBlock block); void addEventListener(WalletEventListener listener); boolean removeEventListener(WalletEventListener listener); void commitTx(Transaction tx); Set<Transaction> getTransactions(boolean includeDead, boolean includeInactive); Iterable<WalletTransaction> getWalletTransactions(); void addWalletTransaction(WalletTransaction wtx); List<Transaction> getTransactionsByTime(); List<Transaction> getRecentTransactions(int numTransactions, boolean includeDead); Transaction getTransaction(Sha256Hash hash); void clearTransactions(int fromHeight); Transaction createSend(Address address, BigInteger nanocoins); Transaction createSend(SendRequest req); Transaction sendCoinsOffline(SendRequest request); SendResult sendCoins(PeerGroup peerGroup, Address to, BigInteger value); SendResult sendCoins(PeerGroup peerGroup, SendRequest request); Transaction sendCoins(Peer peer, SendRequest request); boolean completeTx(SendRequest req); boolean addKey(final ECKey key); int addKeys(final List<ECKey> keys); ECKey findKeyFromPubHash(byte[] pubkeyHash); boolean hasKey(ECKey key); boolean isPubKeyHashMine(byte[] pubkeyHash); ECKey findKeyFromPubKey(byte[] pubkey); boolean isPubKeyMine(byte[] pubkey); BigInteger getBalance(); BigInteger getBalance(BalanceType balanceType); BigInteger getBalance(CoinSelector selector); @Override String toString(); String toString(boolean includePrivateKeys, AbstractBlockChain chain); void reorganize(StoredBlock splitPoint, List<StoredBlock> oldBlocks, List<StoredBlock> newBlocks); Collection<Transaction> getPendingTransactions(); long getEarliestKeyCreationTime(); Sha256Hash getLastBlockSeenHash(); void setLastBlockSeenHash(Sha256Hash lastBlockSeenHash); void setLastBlockSeenHeight(int lastBlockSeenHeight); int getLastBlockSeenHeight(); KeyParameter encrypt(CharSequence password); void encrypt(KeyCrypter keyCrypter, KeyParameter aesKey); void decrypt(KeyParameter aesKey); ECKey addNewEncryptedKey(KeyCrypter keyCrypter, KeyParameter aesKey); ECKey addNewEncryptedKey(CharSequence password); boolean checkPassword(CharSequence password); boolean checkAESKey(KeyParameter aesKey); KeyCrypter getKeyCrypter(); EncryptionType getEncryptionType(); boolean isEncrypted(); int getVersion(); void setVersion(int version); void setDescription(String description); String getDescription(); int getBloomFilterElementCount(); BloomFilter getBloomFilter(double falsePositiveRate); BloomFilter getBloomFilter(int size, double falsePositiveRate, long nTweak); CoinSelector getCoinSelector(); void setCoinSelector(CoinSelector coinSelector); void trim(final int minTransactionsToKeep); } | Wallet implements Serializable, BlockChainListener { public Sha256Hash getLastBlockSeenHash() { lock.lock(); try { return lastBlockSeenHash; } finally { lock.unlock(); } } Wallet(NetworkParameters params); Wallet(NetworkParameters params, KeyCrypter keyCrypter); NetworkParameters getNetworkParameters(); Iterable<ECKey> getKeys(); int getKeychainSize(); void saveToFile(File f); void setAcceptTimeLockedTransactions(boolean acceptTimeLockedTransactions); boolean doesAcceptTimeLockedTransactions(); void autosaveToFile(File f, long delayTime, TimeUnit timeUnit,
AutosaveEventListener eventListener); void saveToFileStream(OutputStream f); NetworkParameters getParams(); static Wallet loadFromFile(File f); boolean isConsistent(); static Wallet loadFromFileStream(InputStream stream); void notifyTransactionIsInBlock(Sha256Hash txHash, StoredBlock block,
BlockChain.NewBlockType blockType); void receivePending(Transaction tx, List<Transaction> dependencies); boolean isTransactionRelevant(Transaction tx); void receiveFromBlock(Transaction tx, StoredBlock block,
BlockChain.NewBlockType blockType); void notifyNewBestBlock(StoredBlock block); void addEventListener(WalletEventListener listener); boolean removeEventListener(WalletEventListener listener); void commitTx(Transaction tx); Set<Transaction> getTransactions(boolean includeDead, boolean includeInactive); Iterable<WalletTransaction> getWalletTransactions(); void addWalletTransaction(WalletTransaction wtx); List<Transaction> getTransactionsByTime(); List<Transaction> getRecentTransactions(int numTransactions, boolean includeDead); Transaction getTransaction(Sha256Hash hash); void clearTransactions(int fromHeight); Transaction createSend(Address address, BigInteger nanocoins); Transaction createSend(SendRequest req); Transaction sendCoinsOffline(SendRequest request); SendResult sendCoins(PeerGroup peerGroup, Address to, BigInteger value); SendResult sendCoins(PeerGroup peerGroup, SendRequest request); Transaction sendCoins(Peer peer, SendRequest request); boolean completeTx(SendRequest req); boolean addKey(final ECKey key); int addKeys(final List<ECKey> keys); ECKey findKeyFromPubHash(byte[] pubkeyHash); boolean hasKey(ECKey key); boolean isPubKeyHashMine(byte[] pubkeyHash); ECKey findKeyFromPubKey(byte[] pubkey); boolean isPubKeyMine(byte[] pubkey); BigInteger getBalance(); BigInteger getBalance(BalanceType balanceType); BigInteger getBalance(CoinSelector selector); @Override String toString(); String toString(boolean includePrivateKeys, AbstractBlockChain chain); void reorganize(StoredBlock splitPoint, List<StoredBlock> oldBlocks, List<StoredBlock> newBlocks); Collection<Transaction> getPendingTransactions(); long getEarliestKeyCreationTime(); Sha256Hash getLastBlockSeenHash(); void setLastBlockSeenHash(Sha256Hash lastBlockSeenHash); void setLastBlockSeenHeight(int lastBlockSeenHeight); int getLastBlockSeenHeight(); KeyParameter encrypt(CharSequence password); void encrypt(KeyCrypter keyCrypter, KeyParameter aesKey); void decrypt(KeyParameter aesKey); ECKey addNewEncryptedKey(KeyCrypter keyCrypter, KeyParameter aesKey); ECKey addNewEncryptedKey(CharSequence password); boolean checkPassword(CharSequence password); boolean checkAESKey(KeyParameter aesKey); KeyCrypter getKeyCrypter(); EncryptionType getEncryptionType(); boolean isEncrypted(); int getVersion(); void setVersion(int version); void setDescription(String description); String getDescription(); int getBloomFilterElementCount(); BloomFilter getBloomFilter(double falsePositiveRate); BloomFilter getBloomFilter(int size, double falsePositiveRate, long nTweak); CoinSelector getCoinSelector(); void setCoinSelector(CoinSelector coinSelector); void trim(final int minTransactionsToKeep); public ArrayList<ECKey> keychain; } |
@Test public void getPeer_all() throws Exception{ SeedPeers seedPeers = new SeedPeers(NetworkParameters.prodNet()); for(int i = 0; i < SeedPeers.seedAddrs.length; ++i){ assertThat("Failed on index: "+i, seedPeers.getPeer(), notNullValue()); } assertThat(seedPeers.getPeer(), equalTo(null)); } | public InetSocketAddress getPeer() throws PeerDiscoveryException { try { return nextPeer(); } catch (UnknownHostException e) { throw new PeerDiscoveryException(e); } } | SeedPeers implements PeerDiscovery { public InetSocketAddress getPeer() throws PeerDiscoveryException { try { return nextPeer(); } catch (UnknownHostException e) { throw new PeerDiscoveryException(e); } } } | SeedPeers implements PeerDiscovery { public InetSocketAddress getPeer() throws PeerDiscoveryException { try { return nextPeer(); } catch (UnknownHostException e) { throw new PeerDiscoveryException(e); } } SeedPeers(NetworkParameters params); } | SeedPeers implements PeerDiscovery { public InetSocketAddress getPeer() throws PeerDiscoveryException { try { return nextPeer(); } catch (UnknownHostException e) { throw new PeerDiscoveryException(e); } } SeedPeers(NetworkParameters params); InetSocketAddress getPeer(); InetSocketAddress[] getPeers(long timeoutValue, TimeUnit timeoutUnit); void shutdown(); } | SeedPeers implements PeerDiscovery { public InetSocketAddress getPeer() throws PeerDiscoveryException { try { return nextPeer(); } catch (UnknownHostException e) { throw new PeerDiscoveryException(e); } } SeedPeers(NetworkParameters params); InetSocketAddress getPeer(); InetSocketAddress[] getPeers(long timeoutValue, TimeUnit timeoutUnit); void shutdown(); static int[] seedAddrs; } |
@Test public void respectMaxStandardSize() throws Exception { sendMoneyToWallet(Utils.toNanoCoins(100, 0), AbstractBlockChain.NewBlockType.BEST_CHAIN); Transaction tx = new Transaction(params); byte[] bits = new byte[20]; new Random().nextBytes(bits); BigInteger v = Utils.toNanoCoins(0, 1); for (int i = 0; i < 3100; i++) { tx.addOutput(v, new Address(params, bits)); } Wallet.SendRequest req = Wallet.SendRequest.forTx(tx); assertFalse(wallet.completeTx(req)); } | public boolean completeTx(SendRequest req) { lock.lock(); try { Preconditions.checkArgument(!req.completed, "Given SendRequest has already been completed."); BigInteger value = BigInteger.ZERO; for (TransactionOutput output : req.tx.getOutputs()) { value = value.add(output.getValue()); } value = value.add(req.fee); log.info("Completing send tx with {} outputs totalling {}", req.tx.getOutputs().size(), litecoinValueToFriendlyString(value)); LinkedList<TransactionOutput> candidates = calculateSpendCandidates(true); CoinSelection selection = coinSelector.select(value, candidates); if (selection.valueGathered.compareTo(value) < 0) { log.warn("Insufficient value in wallet for send, missing " + litecoinValueToFriendlyString(value.subtract(selection.valueGathered))); return false; } checkState(selection.gathered.size() > 0); req.tx.getConfidence().setConfidenceType(ConfidenceType.NOT_SEEN_IN_CHAIN); BigInteger change = selection.valueGathered.subtract(value); if (change.compareTo(BigInteger.ZERO) > 0) { Address changeAddress = req.changeAddress != null ? req.changeAddress : getChangeAddress(); log.info(" with {} coins change", litecoinValueToFriendlyString(change)); req.tx.addOutput(new TransactionOutput(params, req.tx, change, changeAddress)); } for (TransactionOutput output : selection.gathered) { req.tx.addInput(output); } try { req.tx.signInputs(Transaction.SigHash.ALL, this, req.aesKey); } catch (ScriptException e) { throw new RuntimeException(e); } int size = req.tx.litecoinSerialize().length; if (size > Transaction.MAX_STANDARD_TX_SIZE) { log.error("Transaction could not be created without exceeding max size: {} vs {}", size, Transaction.MAX_STANDARD_TX_SIZE); return false; } req.tx.getConfidence().setSource(TransactionConfidence.Source.SELF); req.completed = true; log.info(" completed {} with {} inputs", req.tx.getHashAsString(), req.tx.getInputs().size()); return true; } finally { lock.unlock(); } } | Wallet implements Serializable, BlockChainListener { public boolean completeTx(SendRequest req) { lock.lock(); try { Preconditions.checkArgument(!req.completed, "Given SendRequest has already been completed."); BigInteger value = BigInteger.ZERO; for (TransactionOutput output : req.tx.getOutputs()) { value = value.add(output.getValue()); } value = value.add(req.fee); log.info("Completing send tx with {} outputs totalling {}", req.tx.getOutputs().size(), litecoinValueToFriendlyString(value)); LinkedList<TransactionOutput> candidates = calculateSpendCandidates(true); CoinSelection selection = coinSelector.select(value, candidates); if (selection.valueGathered.compareTo(value) < 0) { log.warn("Insufficient value in wallet for send, missing " + litecoinValueToFriendlyString(value.subtract(selection.valueGathered))); return false; } checkState(selection.gathered.size() > 0); req.tx.getConfidence().setConfidenceType(ConfidenceType.NOT_SEEN_IN_CHAIN); BigInteger change = selection.valueGathered.subtract(value); if (change.compareTo(BigInteger.ZERO) > 0) { Address changeAddress = req.changeAddress != null ? req.changeAddress : getChangeAddress(); log.info(" with {} coins change", litecoinValueToFriendlyString(change)); req.tx.addOutput(new TransactionOutput(params, req.tx, change, changeAddress)); } for (TransactionOutput output : selection.gathered) { req.tx.addInput(output); } try { req.tx.signInputs(Transaction.SigHash.ALL, this, req.aesKey); } catch (ScriptException e) { throw new RuntimeException(e); } int size = req.tx.litecoinSerialize().length; if (size > Transaction.MAX_STANDARD_TX_SIZE) { log.error("Transaction could not be created without exceeding max size: {} vs {}", size, Transaction.MAX_STANDARD_TX_SIZE); return false; } req.tx.getConfidence().setSource(TransactionConfidence.Source.SELF); req.completed = true; log.info(" completed {} with {} inputs", req.tx.getHashAsString(), req.tx.getInputs().size()); return true; } finally { lock.unlock(); } } } | Wallet implements Serializable, BlockChainListener { public boolean completeTx(SendRequest req) { lock.lock(); try { Preconditions.checkArgument(!req.completed, "Given SendRequest has already been completed."); BigInteger value = BigInteger.ZERO; for (TransactionOutput output : req.tx.getOutputs()) { value = value.add(output.getValue()); } value = value.add(req.fee); log.info("Completing send tx with {} outputs totalling {}", req.tx.getOutputs().size(), litecoinValueToFriendlyString(value)); LinkedList<TransactionOutput> candidates = calculateSpendCandidates(true); CoinSelection selection = coinSelector.select(value, candidates); if (selection.valueGathered.compareTo(value) < 0) { log.warn("Insufficient value in wallet for send, missing " + litecoinValueToFriendlyString(value.subtract(selection.valueGathered))); return false; } checkState(selection.gathered.size() > 0); req.tx.getConfidence().setConfidenceType(ConfidenceType.NOT_SEEN_IN_CHAIN); BigInteger change = selection.valueGathered.subtract(value); if (change.compareTo(BigInteger.ZERO) > 0) { Address changeAddress = req.changeAddress != null ? req.changeAddress : getChangeAddress(); log.info(" with {} coins change", litecoinValueToFriendlyString(change)); req.tx.addOutput(new TransactionOutput(params, req.tx, change, changeAddress)); } for (TransactionOutput output : selection.gathered) { req.tx.addInput(output); } try { req.tx.signInputs(Transaction.SigHash.ALL, this, req.aesKey); } catch (ScriptException e) { throw new RuntimeException(e); } int size = req.tx.litecoinSerialize().length; if (size > Transaction.MAX_STANDARD_TX_SIZE) { log.error("Transaction could not be created without exceeding max size: {} vs {}", size, Transaction.MAX_STANDARD_TX_SIZE); return false; } req.tx.getConfidence().setSource(TransactionConfidence.Source.SELF); req.completed = true; log.info(" completed {} with {} inputs", req.tx.getHashAsString(), req.tx.getInputs().size()); return true; } finally { lock.unlock(); } } Wallet(NetworkParameters params); Wallet(NetworkParameters params, KeyCrypter keyCrypter); } | Wallet implements Serializable, BlockChainListener { public boolean completeTx(SendRequest req) { lock.lock(); try { Preconditions.checkArgument(!req.completed, "Given SendRequest has already been completed."); BigInteger value = BigInteger.ZERO; for (TransactionOutput output : req.tx.getOutputs()) { value = value.add(output.getValue()); } value = value.add(req.fee); log.info("Completing send tx with {} outputs totalling {}", req.tx.getOutputs().size(), litecoinValueToFriendlyString(value)); LinkedList<TransactionOutput> candidates = calculateSpendCandidates(true); CoinSelection selection = coinSelector.select(value, candidates); if (selection.valueGathered.compareTo(value) < 0) { log.warn("Insufficient value in wallet for send, missing " + litecoinValueToFriendlyString(value.subtract(selection.valueGathered))); return false; } checkState(selection.gathered.size() > 0); req.tx.getConfidence().setConfidenceType(ConfidenceType.NOT_SEEN_IN_CHAIN); BigInteger change = selection.valueGathered.subtract(value); if (change.compareTo(BigInteger.ZERO) > 0) { Address changeAddress = req.changeAddress != null ? req.changeAddress : getChangeAddress(); log.info(" with {} coins change", litecoinValueToFriendlyString(change)); req.tx.addOutput(new TransactionOutput(params, req.tx, change, changeAddress)); } for (TransactionOutput output : selection.gathered) { req.tx.addInput(output); } try { req.tx.signInputs(Transaction.SigHash.ALL, this, req.aesKey); } catch (ScriptException e) { throw new RuntimeException(e); } int size = req.tx.litecoinSerialize().length; if (size > Transaction.MAX_STANDARD_TX_SIZE) { log.error("Transaction could not be created without exceeding max size: {} vs {}", size, Transaction.MAX_STANDARD_TX_SIZE); return false; } req.tx.getConfidence().setSource(TransactionConfidence.Source.SELF); req.completed = true; log.info(" completed {} with {} inputs", req.tx.getHashAsString(), req.tx.getInputs().size()); return true; } finally { lock.unlock(); } } Wallet(NetworkParameters params); Wallet(NetworkParameters params, KeyCrypter keyCrypter); NetworkParameters getNetworkParameters(); Iterable<ECKey> getKeys(); int getKeychainSize(); void saveToFile(File f); void setAcceptTimeLockedTransactions(boolean acceptTimeLockedTransactions); boolean doesAcceptTimeLockedTransactions(); void autosaveToFile(File f, long delayTime, TimeUnit timeUnit,
AutosaveEventListener eventListener); void saveToFileStream(OutputStream f); NetworkParameters getParams(); static Wallet loadFromFile(File f); boolean isConsistent(); static Wallet loadFromFileStream(InputStream stream); void notifyTransactionIsInBlock(Sha256Hash txHash, StoredBlock block,
BlockChain.NewBlockType blockType); void receivePending(Transaction tx, List<Transaction> dependencies); boolean isTransactionRelevant(Transaction tx); void receiveFromBlock(Transaction tx, StoredBlock block,
BlockChain.NewBlockType blockType); void notifyNewBestBlock(StoredBlock block); void addEventListener(WalletEventListener listener); boolean removeEventListener(WalletEventListener listener); void commitTx(Transaction tx); Set<Transaction> getTransactions(boolean includeDead, boolean includeInactive); Iterable<WalletTransaction> getWalletTransactions(); void addWalletTransaction(WalletTransaction wtx); List<Transaction> getTransactionsByTime(); List<Transaction> getRecentTransactions(int numTransactions, boolean includeDead); Transaction getTransaction(Sha256Hash hash); void clearTransactions(int fromHeight); Transaction createSend(Address address, BigInteger nanocoins); Transaction createSend(SendRequest req); Transaction sendCoinsOffline(SendRequest request); SendResult sendCoins(PeerGroup peerGroup, Address to, BigInteger value); SendResult sendCoins(PeerGroup peerGroup, SendRequest request); Transaction sendCoins(Peer peer, SendRequest request); boolean completeTx(SendRequest req); boolean addKey(final ECKey key); int addKeys(final List<ECKey> keys); ECKey findKeyFromPubHash(byte[] pubkeyHash); boolean hasKey(ECKey key); boolean isPubKeyHashMine(byte[] pubkeyHash); ECKey findKeyFromPubKey(byte[] pubkey); boolean isPubKeyMine(byte[] pubkey); BigInteger getBalance(); BigInteger getBalance(BalanceType balanceType); BigInteger getBalance(CoinSelector selector); @Override String toString(); String toString(boolean includePrivateKeys, AbstractBlockChain chain); void reorganize(StoredBlock splitPoint, List<StoredBlock> oldBlocks, List<StoredBlock> newBlocks); Collection<Transaction> getPendingTransactions(); long getEarliestKeyCreationTime(); Sha256Hash getLastBlockSeenHash(); void setLastBlockSeenHash(Sha256Hash lastBlockSeenHash); void setLastBlockSeenHeight(int lastBlockSeenHeight); int getLastBlockSeenHeight(); KeyParameter encrypt(CharSequence password); void encrypt(KeyCrypter keyCrypter, KeyParameter aesKey); void decrypt(KeyParameter aesKey); ECKey addNewEncryptedKey(KeyCrypter keyCrypter, KeyParameter aesKey); ECKey addNewEncryptedKey(CharSequence password); boolean checkPassword(CharSequence password); boolean checkAESKey(KeyParameter aesKey); KeyCrypter getKeyCrypter(); EncryptionType getEncryptionType(); boolean isEncrypted(); int getVersion(); void setVersion(int version); void setDescription(String description); String getDescription(); int getBloomFilterElementCount(); BloomFilter getBloomFilter(double falsePositiveRate); BloomFilter getBloomFilter(int size, double falsePositiveRate, long nTweak); CoinSelector getCoinSelector(); void setCoinSelector(CoinSelector coinSelector); void trim(final int minTransactionsToKeep); } | Wallet implements Serializable, BlockChainListener { public boolean completeTx(SendRequest req) { lock.lock(); try { Preconditions.checkArgument(!req.completed, "Given SendRequest has already been completed."); BigInteger value = BigInteger.ZERO; for (TransactionOutput output : req.tx.getOutputs()) { value = value.add(output.getValue()); } value = value.add(req.fee); log.info("Completing send tx with {} outputs totalling {}", req.tx.getOutputs().size(), litecoinValueToFriendlyString(value)); LinkedList<TransactionOutput> candidates = calculateSpendCandidates(true); CoinSelection selection = coinSelector.select(value, candidates); if (selection.valueGathered.compareTo(value) < 0) { log.warn("Insufficient value in wallet for send, missing " + litecoinValueToFriendlyString(value.subtract(selection.valueGathered))); return false; } checkState(selection.gathered.size() > 0); req.tx.getConfidence().setConfidenceType(ConfidenceType.NOT_SEEN_IN_CHAIN); BigInteger change = selection.valueGathered.subtract(value); if (change.compareTo(BigInteger.ZERO) > 0) { Address changeAddress = req.changeAddress != null ? req.changeAddress : getChangeAddress(); log.info(" with {} coins change", litecoinValueToFriendlyString(change)); req.tx.addOutput(new TransactionOutput(params, req.tx, change, changeAddress)); } for (TransactionOutput output : selection.gathered) { req.tx.addInput(output); } try { req.tx.signInputs(Transaction.SigHash.ALL, this, req.aesKey); } catch (ScriptException e) { throw new RuntimeException(e); } int size = req.tx.litecoinSerialize().length; if (size > Transaction.MAX_STANDARD_TX_SIZE) { log.error("Transaction could not be created without exceeding max size: {} vs {}", size, Transaction.MAX_STANDARD_TX_SIZE); return false; } req.tx.getConfidence().setSource(TransactionConfidence.Source.SELF); req.completed = true; log.info(" completed {} with {} inputs", req.tx.getHashAsString(), req.tx.getInputs().size()); return true; } finally { lock.unlock(); } } Wallet(NetworkParameters params); Wallet(NetworkParameters params, KeyCrypter keyCrypter); NetworkParameters getNetworkParameters(); Iterable<ECKey> getKeys(); int getKeychainSize(); void saveToFile(File f); void setAcceptTimeLockedTransactions(boolean acceptTimeLockedTransactions); boolean doesAcceptTimeLockedTransactions(); void autosaveToFile(File f, long delayTime, TimeUnit timeUnit,
AutosaveEventListener eventListener); void saveToFileStream(OutputStream f); NetworkParameters getParams(); static Wallet loadFromFile(File f); boolean isConsistent(); static Wallet loadFromFileStream(InputStream stream); void notifyTransactionIsInBlock(Sha256Hash txHash, StoredBlock block,
BlockChain.NewBlockType blockType); void receivePending(Transaction tx, List<Transaction> dependencies); boolean isTransactionRelevant(Transaction tx); void receiveFromBlock(Transaction tx, StoredBlock block,
BlockChain.NewBlockType blockType); void notifyNewBestBlock(StoredBlock block); void addEventListener(WalletEventListener listener); boolean removeEventListener(WalletEventListener listener); void commitTx(Transaction tx); Set<Transaction> getTransactions(boolean includeDead, boolean includeInactive); Iterable<WalletTransaction> getWalletTransactions(); void addWalletTransaction(WalletTransaction wtx); List<Transaction> getTransactionsByTime(); List<Transaction> getRecentTransactions(int numTransactions, boolean includeDead); Transaction getTransaction(Sha256Hash hash); void clearTransactions(int fromHeight); Transaction createSend(Address address, BigInteger nanocoins); Transaction createSend(SendRequest req); Transaction sendCoinsOffline(SendRequest request); SendResult sendCoins(PeerGroup peerGroup, Address to, BigInteger value); SendResult sendCoins(PeerGroup peerGroup, SendRequest request); Transaction sendCoins(Peer peer, SendRequest request); boolean completeTx(SendRequest req); boolean addKey(final ECKey key); int addKeys(final List<ECKey> keys); ECKey findKeyFromPubHash(byte[] pubkeyHash); boolean hasKey(ECKey key); boolean isPubKeyHashMine(byte[] pubkeyHash); ECKey findKeyFromPubKey(byte[] pubkey); boolean isPubKeyMine(byte[] pubkey); BigInteger getBalance(); BigInteger getBalance(BalanceType balanceType); BigInteger getBalance(CoinSelector selector); @Override String toString(); String toString(boolean includePrivateKeys, AbstractBlockChain chain); void reorganize(StoredBlock splitPoint, List<StoredBlock> oldBlocks, List<StoredBlock> newBlocks); Collection<Transaction> getPendingTransactions(); long getEarliestKeyCreationTime(); Sha256Hash getLastBlockSeenHash(); void setLastBlockSeenHash(Sha256Hash lastBlockSeenHash); void setLastBlockSeenHeight(int lastBlockSeenHeight); int getLastBlockSeenHeight(); KeyParameter encrypt(CharSequence password); void encrypt(KeyCrypter keyCrypter, KeyParameter aesKey); void decrypt(KeyParameter aesKey); ECKey addNewEncryptedKey(KeyCrypter keyCrypter, KeyParameter aesKey); ECKey addNewEncryptedKey(CharSequence password); boolean checkPassword(CharSequence password); boolean checkAESKey(KeyParameter aesKey); KeyCrypter getKeyCrypter(); EncryptionType getEncryptionType(); boolean isEncrypted(); int getVersion(); void setVersion(int version); void setDescription(String description); String getDescription(); int getBloomFilterElementCount(); BloomFilter getBloomFilter(double falsePositiveRate); BloomFilter getBloomFilter(int size, double falsePositiveRate, long nTweak); CoinSelector getCoinSelector(); void setCoinSelector(CoinSelector coinSelector); void trim(final int minTransactionsToKeep); public ArrayList<ECKey> keychain; } |
@Test public void testIp() throws Exception { byte[] bytes = Hex.decode("41043e96222332ea7848323c08116dddafbfa917b8e37f0bdf63841628267148588a09a43540942d58d49717ad3fabfe14978cf4f0a8b84d2435dad16e9aa4d7f935ac"); Script s = new Script(params, bytes, 0, bytes.length); assertTrue(s.isSentToRawPubKey()); } | public boolean isSentToRawPubKey() { if (chunks.size() != 2) return false; return chunks.get(1).equalsOpCode(OP_CHECKSIG) && !chunks.get(0).isOpCode && chunks.get(0).data.length > 1; } | Script { public boolean isSentToRawPubKey() { if (chunks.size() != 2) return false; return chunks.get(1).equalsOpCode(OP_CHECKSIG) && !chunks.get(0).isOpCode && chunks.get(0).data.length > 1; } } | Script { public boolean isSentToRawPubKey() { if (chunks.size() != 2) return false; return chunks.get(1).equalsOpCode(OP_CHECKSIG) && !chunks.get(0).isOpCode && chunks.get(0).data.length > 1; } private Script(); Script(NetworkParameters params, byte[] programBytes, int offset, int length); } | Script { public boolean isSentToRawPubKey() { if (chunks.size() != 2) return false; return chunks.get(1).equalsOpCode(OP_CHECKSIG) && !chunks.get(0).isOpCode && chunks.get(0).data.length > 1; } private Script(); Script(NetworkParameters params, byte[] programBytes, int offset, int length); String toString(); static String getOpCodeName(byte opCode); boolean isSentToRawPubKey(); boolean isSentToAddress(); byte[] getPubKeyHash(); byte[] getPubKey(); Address getFromAddress(); Address getToAddress(); static byte[] createOutputScript(Address to); static byte[] createOutputScript(byte[] pubkey); static byte[] createOutputScript(ECKey pubkey); static byte[] createInputScript(byte[] signature, byte[] pubkey); static byte[] createInputScript(byte[] signature); static int getSigOpCount(byte[] program); static long getP2SHSigOpCount(byte[] scriptSig); boolean isPayToScriptHash(); static byte[] removeAllInstancesOf(byte[] inputScript, byte[] chunkToRemove); static byte[] removeAllInstancesOfOp(byte[] inputScript, int opCode); void correctlySpends(Transaction txContainingThis, long scriptSigIndex, Script scriptPubKey,
boolean enforceP2SH); } | Script { public boolean isSentToRawPubKey() { if (chunks.size() != 2) return false; return chunks.get(1).equalsOpCode(OP_CHECKSIG) && !chunks.get(0).isOpCode && chunks.get(0).data.length > 1; } private Script(); Script(NetworkParameters params, byte[] programBytes, int offset, int length); String toString(); static String getOpCodeName(byte opCode); boolean isSentToRawPubKey(); boolean isSentToAddress(); byte[] getPubKeyHash(); byte[] getPubKey(); Address getFromAddress(); Address getToAddress(); static byte[] createOutputScript(Address to); static byte[] createOutputScript(byte[] pubkey); static byte[] createOutputScript(ECKey pubkey); static byte[] createInputScript(byte[] signature, byte[] pubkey); static byte[] createInputScript(byte[] signature); static int getSigOpCount(byte[] program); static long getP2SHSigOpCount(byte[] scriptSig); boolean isPayToScriptHash(); static byte[] removeAllInstancesOf(byte[] inputScript, byte[] chunkToRemove); static byte[] removeAllInstancesOfOp(byte[] inputScript, int opCode); void correctlySpends(Transaction txContainingThis, long scriptSigIndex, Script scriptPubKey,
boolean enforceP2SH); static final int OP_0; static final int OP_FALSE; static final int OP_PUSHDATA1; static final int OP_PUSHDATA2; static final int OP_PUSHDATA4; static final int OP_1NEGATE; static final int OP_RESERVED; static final int OP_1; static final int OP_TRUE; static final int OP_2; static final int OP_3; static final int OP_4; static final int OP_5; static final int OP_6; static final int OP_7; static final int OP_8; static final int OP_9; static final int OP_10; static final int OP_11; static final int OP_12; static final int OP_13; static final int OP_14; static final int OP_15; static final int OP_16; static final int OP_NOP; static final int OP_VER; static final int OP_IF; static final int OP_NOTIF; static final int OP_VERIF; static final int OP_VERNOTIF; static final int OP_ELSE; static final int OP_ENDIF; static final int OP_VERIFY; static final int OP_RETURN; static final int OP_TOALTSTACK; static final int OP_FROMALTSTACK; static final int OP_2DROP; static final int OP_2DUP; static final int OP_3DUP; static final int OP_2OVER; static final int OP_2ROT; static final int OP_2SWAP; static final int OP_IFDUP; static final int OP_DEPTH; static final int OP_DROP; static final int OP_DUP; static final int OP_NIP; static final int OP_OVER; static final int OP_PICK; static final int OP_ROLL; static final int OP_ROT; static final int OP_SWAP; static final int OP_TUCK; static final int OP_CAT; static final int OP_SUBSTR; static final int OP_LEFT; static final int OP_RIGHT; static final int OP_SIZE; static final int OP_INVERT; static final int OP_AND; static final int OP_OR; static final int OP_XOR; static final int OP_EQUAL; static final int OP_EQUALVERIFY; static final int OP_RESERVED1; static final int OP_RESERVED2; static final int OP_1ADD; static final int OP_1SUB; static final int OP_2MUL; static final int OP_2DIV; static final int OP_NEGATE; static final int OP_ABS; static final int OP_NOT; static final int OP_0NOTEQUAL; static final int OP_ADD; static final int OP_SUB; static final int OP_MUL; static final int OP_DIV; static final int OP_MOD; static final int OP_LSHIFT; static final int OP_RSHIFT; static final int OP_BOOLAND; static final int OP_BOOLOR; static final int OP_NUMEQUAL; static final int OP_NUMEQUALVERIFY; static final int OP_NUMNOTEQUAL; static final int OP_LESSTHAN; static final int OP_GREATERTHAN; static final int OP_LESSTHANOREQUAL; static final int OP_GREATERTHANOREQUAL; static final int OP_MIN; static final int OP_MAX; static final int OP_WITHIN; static final int OP_RIPEMD160; static final int OP_SHA1; static final int OP_SHA256; static final int OP_HASH160; static final int OP_HASH256; static final int OP_CODESEPARATOR; static final int OP_CHECKSIG; static final int OP_CHECKSIGVERIFY; static final int OP_CHECKMULTISIG; static final int OP_CHECKMULTISIGVERIFY; static final int OP_NOP1; static final int OP_NOP2; static final int OP_NOP3; static final int OP_NOP4; static final int OP_NOP5; static final int OP_NOP6; static final int OP_NOP7; static final int OP_NOP8; static final int OP_NOP9; static final int OP_NOP10; static final int OP_INVALIDOPCODE; } |
@Test public void dataDrivenValidScripts() throws Exception { BufferedReader in = new BufferedReader(new InputStreamReader( getClass().getResourceAsStream("script_valid.json"), Charset.forName("UTF-8"))); NetworkParameters params = NetworkParameters.testNet(); String script = ""; while (in.ready()) { String line = in.readLine(); if (line == null || line.equals("")) continue; script += line; if (line.equals("]") && script.equals("]") && !in.ready()) break; if (line.trim().endsWith("],") || line.trim().endsWith("]")) { String[] scripts = script.split(","); Script scriptSig = parseScriptString(params, scripts[0].replaceAll("[\"\\[\\]]", "").trim()); Script scriptPubKey = parseScriptString(params, scripts[1].replaceAll("[\"\\[\\]]", "").trim()); scriptSig.correctlySpends(new Transaction(params), 0, scriptPubKey, true); script = ""; } } in.close(); } | public void correctlySpends(Transaction txContainingThis, long scriptSigIndex, Script scriptPubKey, boolean enforceP2SH) throws ScriptException { if (program.length > 10000 || scriptPubKey.program.length > 10000) throw new ScriptException("Script larger than 10,000 bytes"); LinkedList<byte[]> stack = new LinkedList<byte[]>(); LinkedList<byte[]> p2shStack = null; executeScript(txContainingThis, scriptSigIndex, this, stack); if (enforceP2SH) p2shStack = new LinkedList<byte[]>(stack); executeScript(txContainingThis, scriptSigIndex, scriptPubKey, stack); if (stack.size() == 0) throw new ScriptException("Stack empty at end of script execution."); if (!castToBool(stack.pollLast())) throw new ScriptException("Script resulted in a non-true stack"); if (enforceP2SH && scriptPubKey.isPayToScriptHash()) { for (ScriptChunk chunk : chunks) if (chunk.isOpCode && (chunk.data[0] & 0xff) > OP_16) throw new ScriptException("Attempted to spend a P2SH scriptPubKey with a script that contained script ops"); byte[] scriptPubKeyBytes = p2shStack.pollLast(); Script scriptPubKeyP2SH = new Script(params, scriptPubKeyBytes, 0, scriptPubKeyBytes.length); executeScript(txContainingThis, scriptSigIndex, scriptPubKeyP2SH, p2shStack); if (p2shStack.size() == 0) throw new ScriptException("P2SH stack empty at end of script execution."); if (!castToBool(p2shStack.pollLast())) throw new ScriptException("P2SH script execution resulted in a non-true stack"); } } | Script { public void correctlySpends(Transaction txContainingThis, long scriptSigIndex, Script scriptPubKey, boolean enforceP2SH) throws ScriptException { if (program.length > 10000 || scriptPubKey.program.length > 10000) throw new ScriptException("Script larger than 10,000 bytes"); LinkedList<byte[]> stack = new LinkedList<byte[]>(); LinkedList<byte[]> p2shStack = null; executeScript(txContainingThis, scriptSigIndex, this, stack); if (enforceP2SH) p2shStack = new LinkedList<byte[]>(stack); executeScript(txContainingThis, scriptSigIndex, scriptPubKey, stack); if (stack.size() == 0) throw new ScriptException("Stack empty at end of script execution."); if (!castToBool(stack.pollLast())) throw new ScriptException("Script resulted in a non-true stack"); if (enforceP2SH && scriptPubKey.isPayToScriptHash()) { for (ScriptChunk chunk : chunks) if (chunk.isOpCode && (chunk.data[0] & 0xff) > OP_16) throw new ScriptException("Attempted to spend a P2SH scriptPubKey with a script that contained script ops"); byte[] scriptPubKeyBytes = p2shStack.pollLast(); Script scriptPubKeyP2SH = new Script(params, scriptPubKeyBytes, 0, scriptPubKeyBytes.length); executeScript(txContainingThis, scriptSigIndex, scriptPubKeyP2SH, p2shStack); if (p2shStack.size() == 0) throw new ScriptException("P2SH stack empty at end of script execution."); if (!castToBool(p2shStack.pollLast())) throw new ScriptException("P2SH script execution resulted in a non-true stack"); } } } | Script { public void correctlySpends(Transaction txContainingThis, long scriptSigIndex, Script scriptPubKey, boolean enforceP2SH) throws ScriptException { if (program.length > 10000 || scriptPubKey.program.length > 10000) throw new ScriptException("Script larger than 10,000 bytes"); LinkedList<byte[]> stack = new LinkedList<byte[]>(); LinkedList<byte[]> p2shStack = null; executeScript(txContainingThis, scriptSigIndex, this, stack); if (enforceP2SH) p2shStack = new LinkedList<byte[]>(stack); executeScript(txContainingThis, scriptSigIndex, scriptPubKey, stack); if (stack.size() == 0) throw new ScriptException("Stack empty at end of script execution."); if (!castToBool(stack.pollLast())) throw new ScriptException("Script resulted in a non-true stack"); if (enforceP2SH && scriptPubKey.isPayToScriptHash()) { for (ScriptChunk chunk : chunks) if (chunk.isOpCode && (chunk.data[0] & 0xff) > OP_16) throw new ScriptException("Attempted to spend a P2SH scriptPubKey with a script that contained script ops"); byte[] scriptPubKeyBytes = p2shStack.pollLast(); Script scriptPubKeyP2SH = new Script(params, scriptPubKeyBytes, 0, scriptPubKeyBytes.length); executeScript(txContainingThis, scriptSigIndex, scriptPubKeyP2SH, p2shStack); if (p2shStack.size() == 0) throw new ScriptException("P2SH stack empty at end of script execution."); if (!castToBool(p2shStack.pollLast())) throw new ScriptException("P2SH script execution resulted in a non-true stack"); } } private Script(); Script(NetworkParameters params, byte[] programBytes, int offset, int length); } | Script { public void correctlySpends(Transaction txContainingThis, long scriptSigIndex, Script scriptPubKey, boolean enforceP2SH) throws ScriptException { if (program.length > 10000 || scriptPubKey.program.length > 10000) throw new ScriptException("Script larger than 10,000 bytes"); LinkedList<byte[]> stack = new LinkedList<byte[]>(); LinkedList<byte[]> p2shStack = null; executeScript(txContainingThis, scriptSigIndex, this, stack); if (enforceP2SH) p2shStack = new LinkedList<byte[]>(stack); executeScript(txContainingThis, scriptSigIndex, scriptPubKey, stack); if (stack.size() == 0) throw new ScriptException("Stack empty at end of script execution."); if (!castToBool(stack.pollLast())) throw new ScriptException("Script resulted in a non-true stack"); if (enforceP2SH && scriptPubKey.isPayToScriptHash()) { for (ScriptChunk chunk : chunks) if (chunk.isOpCode && (chunk.data[0] & 0xff) > OP_16) throw new ScriptException("Attempted to spend a P2SH scriptPubKey with a script that contained script ops"); byte[] scriptPubKeyBytes = p2shStack.pollLast(); Script scriptPubKeyP2SH = new Script(params, scriptPubKeyBytes, 0, scriptPubKeyBytes.length); executeScript(txContainingThis, scriptSigIndex, scriptPubKeyP2SH, p2shStack); if (p2shStack.size() == 0) throw new ScriptException("P2SH stack empty at end of script execution."); if (!castToBool(p2shStack.pollLast())) throw new ScriptException("P2SH script execution resulted in a non-true stack"); } } private Script(); Script(NetworkParameters params, byte[] programBytes, int offset, int length); String toString(); static String getOpCodeName(byte opCode); boolean isSentToRawPubKey(); boolean isSentToAddress(); byte[] getPubKeyHash(); byte[] getPubKey(); Address getFromAddress(); Address getToAddress(); static byte[] createOutputScript(Address to); static byte[] createOutputScript(byte[] pubkey); static byte[] createOutputScript(ECKey pubkey); static byte[] createInputScript(byte[] signature, byte[] pubkey); static byte[] createInputScript(byte[] signature); static int getSigOpCount(byte[] program); static long getP2SHSigOpCount(byte[] scriptSig); boolean isPayToScriptHash(); static byte[] removeAllInstancesOf(byte[] inputScript, byte[] chunkToRemove); static byte[] removeAllInstancesOfOp(byte[] inputScript, int opCode); void correctlySpends(Transaction txContainingThis, long scriptSigIndex, Script scriptPubKey,
boolean enforceP2SH); } | Script { public void correctlySpends(Transaction txContainingThis, long scriptSigIndex, Script scriptPubKey, boolean enforceP2SH) throws ScriptException { if (program.length > 10000 || scriptPubKey.program.length > 10000) throw new ScriptException("Script larger than 10,000 bytes"); LinkedList<byte[]> stack = new LinkedList<byte[]>(); LinkedList<byte[]> p2shStack = null; executeScript(txContainingThis, scriptSigIndex, this, stack); if (enforceP2SH) p2shStack = new LinkedList<byte[]>(stack); executeScript(txContainingThis, scriptSigIndex, scriptPubKey, stack); if (stack.size() == 0) throw new ScriptException("Stack empty at end of script execution."); if (!castToBool(stack.pollLast())) throw new ScriptException("Script resulted in a non-true stack"); if (enforceP2SH && scriptPubKey.isPayToScriptHash()) { for (ScriptChunk chunk : chunks) if (chunk.isOpCode && (chunk.data[0] & 0xff) > OP_16) throw new ScriptException("Attempted to spend a P2SH scriptPubKey with a script that contained script ops"); byte[] scriptPubKeyBytes = p2shStack.pollLast(); Script scriptPubKeyP2SH = new Script(params, scriptPubKeyBytes, 0, scriptPubKeyBytes.length); executeScript(txContainingThis, scriptSigIndex, scriptPubKeyP2SH, p2shStack); if (p2shStack.size() == 0) throw new ScriptException("P2SH stack empty at end of script execution."); if (!castToBool(p2shStack.pollLast())) throw new ScriptException("P2SH script execution resulted in a non-true stack"); } } private Script(); Script(NetworkParameters params, byte[] programBytes, int offset, int length); String toString(); static String getOpCodeName(byte opCode); boolean isSentToRawPubKey(); boolean isSentToAddress(); byte[] getPubKeyHash(); byte[] getPubKey(); Address getFromAddress(); Address getToAddress(); static byte[] createOutputScript(Address to); static byte[] createOutputScript(byte[] pubkey); static byte[] createOutputScript(ECKey pubkey); static byte[] createInputScript(byte[] signature, byte[] pubkey); static byte[] createInputScript(byte[] signature); static int getSigOpCount(byte[] program); static long getP2SHSigOpCount(byte[] scriptSig); boolean isPayToScriptHash(); static byte[] removeAllInstancesOf(byte[] inputScript, byte[] chunkToRemove); static byte[] removeAllInstancesOfOp(byte[] inputScript, int opCode); void correctlySpends(Transaction txContainingThis, long scriptSigIndex, Script scriptPubKey,
boolean enforceP2SH); static final int OP_0; static final int OP_FALSE; static final int OP_PUSHDATA1; static final int OP_PUSHDATA2; static final int OP_PUSHDATA4; static final int OP_1NEGATE; static final int OP_RESERVED; static final int OP_1; static final int OP_TRUE; static final int OP_2; static final int OP_3; static final int OP_4; static final int OP_5; static final int OP_6; static final int OP_7; static final int OP_8; static final int OP_9; static final int OP_10; static final int OP_11; static final int OP_12; static final int OP_13; static final int OP_14; static final int OP_15; static final int OP_16; static final int OP_NOP; static final int OP_VER; static final int OP_IF; static final int OP_NOTIF; static final int OP_VERIF; static final int OP_VERNOTIF; static final int OP_ELSE; static final int OP_ENDIF; static final int OP_VERIFY; static final int OP_RETURN; static final int OP_TOALTSTACK; static final int OP_FROMALTSTACK; static final int OP_2DROP; static final int OP_2DUP; static final int OP_3DUP; static final int OP_2OVER; static final int OP_2ROT; static final int OP_2SWAP; static final int OP_IFDUP; static final int OP_DEPTH; static final int OP_DROP; static final int OP_DUP; static final int OP_NIP; static final int OP_OVER; static final int OP_PICK; static final int OP_ROLL; static final int OP_ROT; static final int OP_SWAP; static final int OP_TUCK; static final int OP_CAT; static final int OP_SUBSTR; static final int OP_LEFT; static final int OP_RIGHT; static final int OP_SIZE; static final int OP_INVERT; static final int OP_AND; static final int OP_OR; static final int OP_XOR; static final int OP_EQUAL; static final int OP_EQUALVERIFY; static final int OP_RESERVED1; static final int OP_RESERVED2; static final int OP_1ADD; static final int OP_1SUB; static final int OP_2MUL; static final int OP_2DIV; static final int OP_NEGATE; static final int OP_ABS; static final int OP_NOT; static final int OP_0NOTEQUAL; static final int OP_ADD; static final int OP_SUB; static final int OP_MUL; static final int OP_DIV; static final int OP_MOD; static final int OP_LSHIFT; static final int OP_RSHIFT; static final int OP_BOOLAND; static final int OP_BOOLOR; static final int OP_NUMEQUAL; static final int OP_NUMEQUALVERIFY; static final int OP_NUMNOTEQUAL; static final int OP_LESSTHAN; static final int OP_GREATERTHAN; static final int OP_LESSTHANOREQUAL; static final int OP_GREATERTHANOREQUAL; static final int OP_MIN; static final int OP_MAX; static final int OP_WITHIN; static final int OP_RIPEMD160; static final int OP_SHA1; static final int OP_SHA256; static final int OP_HASH160; static final int OP_HASH256; static final int OP_CODESEPARATOR; static final int OP_CHECKSIG; static final int OP_CHECKSIGVERIFY; static final int OP_CHECKMULTISIG; static final int OP_CHECKMULTISIGVERIFY; static final int OP_NOP1; static final int OP_NOP2; static final int OP_NOP3; static final int OP_NOP4; static final int OP_NOP5; static final int OP_NOP6; static final int OP_NOP7; static final int OP_NOP8; static final int OP_NOP9; static final int OP_NOP10; static final int OP_INVALIDOPCODE; } |
@Test public void dataDrivenInvalidScripts() throws Exception { BufferedReader in = new BufferedReader(new InputStreamReader( getClass().getResourceAsStream("script_invalid.json"), Charset.forName("UTF-8"))); NetworkParameters params = NetworkParameters.testNet(); String script = ""; while (in.ready()) { String line = in.readLine(); if (line == null || line.equals("")) continue; script += line; if (line.equals("]") && script.equals("]") && !in.ready()) break; if (line.trim().endsWith("],") || line.trim().equals("]")) { String[] scripts = script.split(","); try { Script scriptSig = parseScriptString(params, scripts[0].replaceAll("[\"\\[\\]]", "").trim()); Script scriptPubKey = parseScriptString(params, scripts[1].replaceAll("[\"\\[\\]]", "").trim()); scriptSig.correctlySpends(new Transaction(params), 0, scriptPubKey, true); fail(); } catch (VerificationException e) { } script = ""; } } in.close(); } | public void correctlySpends(Transaction txContainingThis, long scriptSigIndex, Script scriptPubKey, boolean enforceP2SH) throws ScriptException { if (program.length > 10000 || scriptPubKey.program.length > 10000) throw new ScriptException("Script larger than 10,000 bytes"); LinkedList<byte[]> stack = new LinkedList<byte[]>(); LinkedList<byte[]> p2shStack = null; executeScript(txContainingThis, scriptSigIndex, this, stack); if (enforceP2SH) p2shStack = new LinkedList<byte[]>(stack); executeScript(txContainingThis, scriptSigIndex, scriptPubKey, stack); if (stack.size() == 0) throw new ScriptException("Stack empty at end of script execution."); if (!castToBool(stack.pollLast())) throw new ScriptException("Script resulted in a non-true stack"); if (enforceP2SH && scriptPubKey.isPayToScriptHash()) { for (ScriptChunk chunk : chunks) if (chunk.isOpCode && (chunk.data[0] & 0xff) > OP_16) throw new ScriptException("Attempted to spend a P2SH scriptPubKey with a script that contained script ops"); byte[] scriptPubKeyBytes = p2shStack.pollLast(); Script scriptPubKeyP2SH = new Script(params, scriptPubKeyBytes, 0, scriptPubKeyBytes.length); executeScript(txContainingThis, scriptSigIndex, scriptPubKeyP2SH, p2shStack); if (p2shStack.size() == 0) throw new ScriptException("P2SH stack empty at end of script execution."); if (!castToBool(p2shStack.pollLast())) throw new ScriptException("P2SH script execution resulted in a non-true stack"); } } | Script { public void correctlySpends(Transaction txContainingThis, long scriptSigIndex, Script scriptPubKey, boolean enforceP2SH) throws ScriptException { if (program.length > 10000 || scriptPubKey.program.length > 10000) throw new ScriptException("Script larger than 10,000 bytes"); LinkedList<byte[]> stack = new LinkedList<byte[]>(); LinkedList<byte[]> p2shStack = null; executeScript(txContainingThis, scriptSigIndex, this, stack); if (enforceP2SH) p2shStack = new LinkedList<byte[]>(stack); executeScript(txContainingThis, scriptSigIndex, scriptPubKey, stack); if (stack.size() == 0) throw new ScriptException("Stack empty at end of script execution."); if (!castToBool(stack.pollLast())) throw new ScriptException("Script resulted in a non-true stack"); if (enforceP2SH && scriptPubKey.isPayToScriptHash()) { for (ScriptChunk chunk : chunks) if (chunk.isOpCode && (chunk.data[0] & 0xff) > OP_16) throw new ScriptException("Attempted to spend a P2SH scriptPubKey with a script that contained script ops"); byte[] scriptPubKeyBytes = p2shStack.pollLast(); Script scriptPubKeyP2SH = new Script(params, scriptPubKeyBytes, 0, scriptPubKeyBytes.length); executeScript(txContainingThis, scriptSigIndex, scriptPubKeyP2SH, p2shStack); if (p2shStack.size() == 0) throw new ScriptException("P2SH stack empty at end of script execution."); if (!castToBool(p2shStack.pollLast())) throw new ScriptException("P2SH script execution resulted in a non-true stack"); } } } | Script { public void correctlySpends(Transaction txContainingThis, long scriptSigIndex, Script scriptPubKey, boolean enforceP2SH) throws ScriptException { if (program.length > 10000 || scriptPubKey.program.length > 10000) throw new ScriptException("Script larger than 10,000 bytes"); LinkedList<byte[]> stack = new LinkedList<byte[]>(); LinkedList<byte[]> p2shStack = null; executeScript(txContainingThis, scriptSigIndex, this, stack); if (enforceP2SH) p2shStack = new LinkedList<byte[]>(stack); executeScript(txContainingThis, scriptSigIndex, scriptPubKey, stack); if (stack.size() == 0) throw new ScriptException("Stack empty at end of script execution."); if (!castToBool(stack.pollLast())) throw new ScriptException("Script resulted in a non-true stack"); if (enforceP2SH && scriptPubKey.isPayToScriptHash()) { for (ScriptChunk chunk : chunks) if (chunk.isOpCode && (chunk.data[0] & 0xff) > OP_16) throw new ScriptException("Attempted to spend a P2SH scriptPubKey with a script that contained script ops"); byte[] scriptPubKeyBytes = p2shStack.pollLast(); Script scriptPubKeyP2SH = new Script(params, scriptPubKeyBytes, 0, scriptPubKeyBytes.length); executeScript(txContainingThis, scriptSigIndex, scriptPubKeyP2SH, p2shStack); if (p2shStack.size() == 0) throw new ScriptException("P2SH stack empty at end of script execution."); if (!castToBool(p2shStack.pollLast())) throw new ScriptException("P2SH script execution resulted in a non-true stack"); } } private Script(); Script(NetworkParameters params, byte[] programBytes, int offset, int length); } | Script { public void correctlySpends(Transaction txContainingThis, long scriptSigIndex, Script scriptPubKey, boolean enforceP2SH) throws ScriptException { if (program.length > 10000 || scriptPubKey.program.length > 10000) throw new ScriptException("Script larger than 10,000 bytes"); LinkedList<byte[]> stack = new LinkedList<byte[]>(); LinkedList<byte[]> p2shStack = null; executeScript(txContainingThis, scriptSigIndex, this, stack); if (enforceP2SH) p2shStack = new LinkedList<byte[]>(stack); executeScript(txContainingThis, scriptSigIndex, scriptPubKey, stack); if (stack.size() == 0) throw new ScriptException("Stack empty at end of script execution."); if (!castToBool(stack.pollLast())) throw new ScriptException("Script resulted in a non-true stack"); if (enforceP2SH && scriptPubKey.isPayToScriptHash()) { for (ScriptChunk chunk : chunks) if (chunk.isOpCode && (chunk.data[0] & 0xff) > OP_16) throw new ScriptException("Attempted to spend a P2SH scriptPubKey with a script that contained script ops"); byte[] scriptPubKeyBytes = p2shStack.pollLast(); Script scriptPubKeyP2SH = new Script(params, scriptPubKeyBytes, 0, scriptPubKeyBytes.length); executeScript(txContainingThis, scriptSigIndex, scriptPubKeyP2SH, p2shStack); if (p2shStack.size() == 0) throw new ScriptException("P2SH stack empty at end of script execution."); if (!castToBool(p2shStack.pollLast())) throw new ScriptException("P2SH script execution resulted in a non-true stack"); } } private Script(); Script(NetworkParameters params, byte[] programBytes, int offset, int length); String toString(); static String getOpCodeName(byte opCode); boolean isSentToRawPubKey(); boolean isSentToAddress(); byte[] getPubKeyHash(); byte[] getPubKey(); Address getFromAddress(); Address getToAddress(); static byte[] createOutputScript(Address to); static byte[] createOutputScript(byte[] pubkey); static byte[] createOutputScript(ECKey pubkey); static byte[] createInputScript(byte[] signature, byte[] pubkey); static byte[] createInputScript(byte[] signature); static int getSigOpCount(byte[] program); static long getP2SHSigOpCount(byte[] scriptSig); boolean isPayToScriptHash(); static byte[] removeAllInstancesOf(byte[] inputScript, byte[] chunkToRemove); static byte[] removeAllInstancesOfOp(byte[] inputScript, int opCode); void correctlySpends(Transaction txContainingThis, long scriptSigIndex, Script scriptPubKey,
boolean enforceP2SH); } | Script { public void correctlySpends(Transaction txContainingThis, long scriptSigIndex, Script scriptPubKey, boolean enforceP2SH) throws ScriptException { if (program.length > 10000 || scriptPubKey.program.length > 10000) throw new ScriptException("Script larger than 10,000 bytes"); LinkedList<byte[]> stack = new LinkedList<byte[]>(); LinkedList<byte[]> p2shStack = null; executeScript(txContainingThis, scriptSigIndex, this, stack); if (enforceP2SH) p2shStack = new LinkedList<byte[]>(stack); executeScript(txContainingThis, scriptSigIndex, scriptPubKey, stack); if (stack.size() == 0) throw new ScriptException("Stack empty at end of script execution."); if (!castToBool(stack.pollLast())) throw new ScriptException("Script resulted in a non-true stack"); if (enforceP2SH && scriptPubKey.isPayToScriptHash()) { for (ScriptChunk chunk : chunks) if (chunk.isOpCode && (chunk.data[0] & 0xff) > OP_16) throw new ScriptException("Attempted to spend a P2SH scriptPubKey with a script that contained script ops"); byte[] scriptPubKeyBytes = p2shStack.pollLast(); Script scriptPubKeyP2SH = new Script(params, scriptPubKeyBytes, 0, scriptPubKeyBytes.length); executeScript(txContainingThis, scriptSigIndex, scriptPubKeyP2SH, p2shStack); if (p2shStack.size() == 0) throw new ScriptException("P2SH stack empty at end of script execution."); if (!castToBool(p2shStack.pollLast())) throw new ScriptException("P2SH script execution resulted in a non-true stack"); } } private Script(); Script(NetworkParameters params, byte[] programBytes, int offset, int length); String toString(); static String getOpCodeName(byte opCode); boolean isSentToRawPubKey(); boolean isSentToAddress(); byte[] getPubKeyHash(); byte[] getPubKey(); Address getFromAddress(); Address getToAddress(); static byte[] createOutputScript(Address to); static byte[] createOutputScript(byte[] pubkey); static byte[] createOutputScript(ECKey pubkey); static byte[] createInputScript(byte[] signature, byte[] pubkey); static byte[] createInputScript(byte[] signature); static int getSigOpCount(byte[] program); static long getP2SHSigOpCount(byte[] scriptSig); boolean isPayToScriptHash(); static byte[] removeAllInstancesOf(byte[] inputScript, byte[] chunkToRemove); static byte[] removeAllInstancesOfOp(byte[] inputScript, int opCode); void correctlySpends(Transaction txContainingThis, long scriptSigIndex, Script scriptPubKey,
boolean enforceP2SH); static final int OP_0; static final int OP_FALSE; static final int OP_PUSHDATA1; static final int OP_PUSHDATA2; static final int OP_PUSHDATA4; static final int OP_1NEGATE; static final int OP_RESERVED; static final int OP_1; static final int OP_TRUE; static final int OP_2; static final int OP_3; static final int OP_4; static final int OP_5; static final int OP_6; static final int OP_7; static final int OP_8; static final int OP_9; static final int OP_10; static final int OP_11; static final int OP_12; static final int OP_13; static final int OP_14; static final int OP_15; static final int OP_16; static final int OP_NOP; static final int OP_VER; static final int OP_IF; static final int OP_NOTIF; static final int OP_VERIF; static final int OP_VERNOTIF; static final int OP_ELSE; static final int OP_ENDIF; static final int OP_VERIFY; static final int OP_RETURN; static final int OP_TOALTSTACK; static final int OP_FROMALTSTACK; static final int OP_2DROP; static final int OP_2DUP; static final int OP_3DUP; static final int OP_2OVER; static final int OP_2ROT; static final int OP_2SWAP; static final int OP_IFDUP; static final int OP_DEPTH; static final int OP_DROP; static final int OP_DUP; static final int OP_NIP; static final int OP_OVER; static final int OP_PICK; static final int OP_ROLL; static final int OP_ROT; static final int OP_SWAP; static final int OP_TUCK; static final int OP_CAT; static final int OP_SUBSTR; static final int OP_LEFT; static final int OP_RIGHT; static final int OP_SIZE; static final int OP_INVERT; static final int OP_AND; static final int OP_OR; static final int OP_XOR; static final int OP_EQUAL; static final int OP_EQUALVERIFY; static final int OP_RESERVED1; static final int OP_RESERVED2; static final int OP_1ADD; static final int OP_1SUB; static final int OP_2MUL; static final int OP_2DIV; static final int OP_NEGATE; static final int OP_ABS; static final int OP_NOT; static final int OP_0NOTEQUAL; static final int OP_ADD; static final int OP_SUB; static final int OP_MUL; static final int OP_DIV; static final int OP_MOD; static final int OP_LSHIFT; static final int OP_RSHIFT; static final int OP_BOOLAND; static final int OP_BOOLOR; static final int OP_NUMEQUAL; static final int OP_NUMEQUALVERIFY; static final int OP_NUMNOTEQUAL; static final int OP_LESSTHAN; static final int OP_GREATERTHAN; static final int OP_LESSTHANOREQUAL; static final int OP_GREATERTHANOREQUAL; static final int OP_MIN; static final int OP_MAX; static final int OP_WITHIN; static final int OP_RIPEMD160; static final int OP_SHA1; static final int OP_SHA256; static final int OP_HASH160; static final int OP_HASH256; static final int OP_CODESEPARATOR; static final int OP_CHECKSIG; static final int OP_CHECKSIGVERIFY; static final int OP_CHECKMULTISIG; static final int OP_CHECKMULTISIGVERIFY; static final int OP_NOP1; static final int OP_NOP2; static final int OP_NOP3; static final int OP_NOP4; static final int OP_NOP5; static final int OP_NOP6; static final int OP_NOP7; static final int OP_NOP8; static final int OP_NOP9; static final int OP_NOP10; static final int OP_INVALIDOPCODE; } |
@Test public void decoding() throws Exception { Address a = new Address(testParams, "n4eA2nbYqErp7H6jebchxAN59DmNpksexv"); assertEquals("fda79a24e50ff70ff42f7d89585da5bd19d9e5cc", Utils.bytesToHexString(a.getHash160())); Address b = new Address(prodParams, "LQz2pJYaeqntA9BFB8rDX5AL2TTKGd5AuN"); assertEquals("3f2ebb6c8d88e586b551303d2c29eba15518d8d1", Utils.bytesToHexString(b.getHash160())); } | public byte[] getHash160() { return bytes; } | Address extends VersionedChecksummedBytes { public byte[] getHash160() { return bytes; } } | Address extends VersionedChecksummedBytes { public byte[] getHash160() { return bytes; } Address(NetworkParameters params, byte[] hash160); Address(NetworkParameters params, String address); } | Address extends VersionedChecksummedBytes { public byte[] getHash160() { return bytes; } Address(NetworkParameters params, byte[] hash160); Address(NetworkParameters params, String address); byte[] getHash160(); NetworkParameters getParameters(); static NetworkParameters getParametersFromAddress(String address); } | Address extends VersionedChecksummedBytes { public byte[] getHash160() { return bytes; } Address(NetworkParameters params, byte[] hash160); Address(NetworkParameters params, String address); byte[] getHash160(); NetworkParameters getParameters(); static NetworkParameters getParametersFromAddress(String address); static final int LENGTH; } |
@Test public void getNetwork() throws Exception { NetworkParameters params = Address.getParametersFromAddress("LQz2pJYaeqntA9BFB8rDX5AL2TTKGd5AuN"); assertEquals(NetworkParameters.prodNet().getId(), params.getId()); params = Address.getParametersFromAddress("n4eA2nbYqErp7H6jebchxAN59DmNpksexv"); assertEquals(NetworkParameters.testNet().getId(), params.getId()); } | public static NetworkParameters getParametersFromAddress(String address) throws AddressFormatException { try { return new Address(null, address).getParameters(); } catch (WrongNetworkException e) { throw new RuntimeException(e); } } | Address extends VersionedChecksummedBytes { public static NetworkParameters getParametersFromAddress(String address) throws AddressFormatException { try { return new Address(null, address).getParameters(); } catch (WrongNetworkException e) { throw new RuntimeException(e); } } } | Address extends VersionedChecksummedBytes { public static NetworkParameters getParametersFromAddress(String address) throws AddressFormatException { try { return new Address(null, address).getParameters(); } catch (WrongNetworkException e) { throw new RuntimeException(e); } } Address(NetworkParameters params, byte[] hash160); Address(NetworkParameters params, String address); } | Address extends VersionedChecksummedBytes { public static NetworkParameters getParametersFromAddress(String address) throws AddressFormatException { try { return new Address(null, address).getParameters(); } catch (WrongNetworkException e) { throw new RuntimeException(e); } } Address(NetworkParameters params, byte[] hash160); Address(NetworkParameters params, String address); byte[] getHash160(); NetworkParameters getParameters(); static NetworkParameters getParametersFromAddress(String address); } | Address extends VersionedChecksummedBytes { public static NetworkParameters getParametersFromAddress(String address) throws AddressFormatException { try { return new Address(null, address).getParameters(); } catch (WrongNetworkException e) { throw new RuntimeException(e); } } Address(NetworkParameters params, byte[] hash160); Address(NetworkParameters params, String address); byte[] getHash160(); NetworkParameters getParameters(); static NetworkParameters getParametersFromAddress(String address); static final int LENGTH; } |
@Test public void testDecode() throws Exception { NetworkParameters params = NetworkParameters.unitTests(); VersionMessage ver = new VersionMessage(params, Hex.decode("71110100000000000000000048e5e95000000000000000000000000000000000000000000000ffff7f000001479d000000000000000000000000000000000000ffff7f000001479d0000000000000000172f426974436f696e4a3a302e372d534e415053484f542f0004000000")); assertTrue(!ver.relayTxesBeforeFilter); assertTrue(ver.bestHeight == 1024); assertTrue(ver.subVer.equals("/LitecoinJ:0.7-SNAPSHOT/")); ver = new VersionMessage(params, Hex.decode("71110100000000000000000048e5e95000000000000000000000000000000000000000000000ffff7f000001479d000000000000000000000000000000000000ffff7f000001479d0000000000000000172f426974436f696e4a3a302e372d534e415053484f542f00040000")); assertTrue(ver.relayTxesBeforeFilter); assertTrue(ver.bestHeight == 1024); assertTrue(ver.subVer.equals("/LitecoinJ:0.7-SNAPSHOT/")); ver = new VersionMessage(params, Hex.decode("71110100000000000000000048e5e95000000000000000000000000000000000000000000000ffff7f000001479d000000000000000000000000000000000000ffff7f000001479d0000000000000000172f426974436f696e4a3a302e372d534e415053484f542f")); assertTrue(ver.relayTxesBeforeFilter); assertTrue(ver.bestHeight == 0); assertTrue(ver.subVer.equals("/LitecoinJ:0.7-SNAPSHOT/")); ver = new VersionMessage(params, Hex.decode("71110100000000000000000048e5e95000000000000000000000000000000000000000000000ffff7f000001479d000000000000000000000000000000000000ffff7f000001479d0000000000000000")); assertTrue(ver.relayTxesBeforeFilter); assertTrue(ver.bestHeight == 0); assertTrue(ver.subVer.equals("")); } | @Override public boolean equals(Object o) { if (!(o instanceof VersionMessage)) return false; VersionMessage other = (VersionMessage) o; return other.bestHeight == bestHeight && other.clientVersion == clientVersion && other.localServices == localServices && other.time == time && other.subVer.equals(subVer) && other.myAddr.equals(myAddr) && other.theirAddr.equals(theirAddr) && other.relayTxesBeforeFilter == relayTxesBeforeFilter; } | VersionMessage extends Message { @Override public boolean equals(Object o) { if (!(o instanceof VersionMessage)) return false; VersionMessage other = (VersionMessage) o; return other.bestHeight == bestHeight && other.clientVersion == clientVersion && other.localServices == localServices && other.time == time && other.subVer.equals(subVer) && other.myAddr.equals(myAddr) && other.theirAddr.equals(theirAddr) && other.relayTxesBeforeFilter == relayTxesBeforeFilter; } } | VersionMessage extends Message { @Override public boolean equals(Object o) { if (!(o instanceof VersionMessage)) return false; VersionMessage other = (VersionMessage) o; return other.bestHeight == bestHeight && other.clientVersion == clientVersion && other.localServices == localServices && other.time == time && other.subVer.equals(subVer) && other.myAddr.equals(myAddr) && other.theirAddr.equals(theirAddr) && other.relayTxesBeforeFilter == relayTxesBeforeFilter; } VersionMessage(NetworkParameters params, byte[] msg); VersionMessage(NetworkParameters params, int newBestHeight); VersionMessage(NetworkParameters params, int newBestHeight, boolean relayTxesBeforeFilter); } | VersionMessage extends Message { @Override public boolean equals(Object o) { if (!(o instanceof VersionMessage)) return false; VersionMessage other = (VersionMessage) o; return other.bestHeight == bestHeight && other.clientVersion == clientVersion && other.localServices == localServices && other.time == time && other.subVer.equals(subVer) && other.myAddr.equals(myAddr) && other.theirAddr.equals(theirAddr) && other.relayTxesBeforeFilter == relayTxesBeforeFilter; } VersionMessage(NetworkParameters params, byte[] msg); VersionMessage(NetworkParameters params, int newBestHeight); VersionMessage(NetworkParameters params, int newBestHeight, boolean relayTxesBeforeFilter); @Override void parse(); @Override void litecoinSerializeToStream(OutputStream buf); boolean hasBlockChain(); @Override boolean equals(Object o); @Override int hashCode(); String toString(); VersionMessage duplicate(); void appendToSubVer(String name, String version, String comments); boolean isPingPongSupported(); boolean isBloomFilteringSupported(); } | VersionMessage extends Message { @Override public boolean equals(Object o) { if (!(o instanceof VersionMessage)) return false; VersionMessage other = (VersionMessage) o; return other.bestHeight == bestHeight && other.clientVersion == clientVersion && other.localServices == localServices && other.time == time && other.subVer.equals(subVer) && other.myAddr.equals(myAddr) && other.theirAddr.equals(theirAddr) && other.relayTxesBeforeFilter == relayTxesBeforeFilter; } VersionMessage(NetworkParameters params, byte[] msg); VersionMessage(NetworkParameters params, int newBestHeight); VersionMessage(NetworkParameters params, int newBestHeight, boolean relayTxesBeforeFilter); @Override void parse(); @Override void litecoinSerializeToStream(OutputStream buf); boolean hasBlockChain(); @Override boolean equals(Object o); @Override int hashCode(); String toString(); VersionMessage duplicate(); void appendToSubVer(String name, String version, String comments); boolean isPingPongSupported(); boolean isBloomFilteringSupported(); static final int NODE_NETWORK; public int clientVersion; public long localServices; public long time; public PeerAddress myAddr; public PeerAddress theirAddr; public String subVer; public long bestHeight; public boolean relayTxesBeforeFilter; static final String LITECOINJ_VERSION; static final String LIBRARY_SUBVER; } |
@Test public void testWork() throws Exception { BigInteger work = params.genesisBlock.getWork(); assertEquals(BigInteger.valueOf(536879104L), work); } | public BigInteger getWork() throws VerificationException { BigInteger target = getDifficultyTargetAsInteger(); return LARGEST_HASH.divide(target.add(BigInteger.ONE)); } | Block extends Message { public BigInteger getWork() throws VerificationException { BigInteger target = getDifficultyTargetAsInteger(); return LARGEST_HASH.divide(target.add(BigInteger.ONE)); } } | Block extends Message { public BigInteger getWork() throws VerificationException { BigInteger target = getDifficultyTargetAsInteger(); return LARGEST_HASH.divide(target.add(BigInteger.ONE)); } Block(NetworkParameters params); Block(NetworkParameters params, byte[] payloadBytes); Block(NetworkParameters params, byte[] payloadBytes, boolean parseLazy, boolean parseRetain, int length); } | Block extends Message { public BigInteger getWork() throws VerificationException { BigInteger target = getDifficultyTargetAsInteger(); return LARGEST_HASH.divide(target.add(BigInteger.ONE)); } Block(NetworkParameters params); Block(NetworkParameters params, byte[] payloadBytes); Block(NetworkParameters params, byte[] payloadBytes, boolean parseLazy, boolean parseRetain, int length); BigInteger getBlockInflation(int height); int getOptimalEncodingMessageSize(); void ensureParsed(); void ensureParsedHeader(); void ensureParsedTransactions(); byte[] litecoinSerialize(); String getHashAsString(); String getScryptHashAsString(); Sha256Hash getHash(); Sha256Hash getScryptHash(); BigInteger getWork(); Block cloneAsHeader(); @Override String toString(); BigInteger getDifficultyTargetAsInteger(); void verifyHeader(); void verifyTransactions(); void verify(); @Override boolean equals(Object o); @Override int hashCode(); Sha256Hash getMerkleRoot(); void addTransaction(Transaction t); long getVersion(); Sha256Hash getPrevBlockHash(); long getTimeSeconds(); Date getTime(); long getDifficultyTarget(); long getNonce(); List<Transaction> getTransactions(); Block createNextBlock(Address to, TransactionOutPoint prevOut); Block createNextBlock(Address to, BigInteger value); Block createNextBlock(Address to); Block createNextBlockWithCoinbase(byte[] pubKey, BigInteger coinbaseValue); } | Block extends Message { public BigInteger getWork() throws VerificationException { BigInteger target = getDifficultyTargetAsInteger(); return LARGEST_HASH.divide(target.add(BigInteger.ONE)); } Block(NetworkParameters params); Block(NetworkParameters params, byte[] payloadBytes); Block(NetworkParameters params, byte[] payloadBytes, boolean parseLazy, boolean parseRetain, int length); BigInteger getBlockInflation(int height); int getOptimalEncodingMessageSize(); void ensureParsed(); void ensureParsedHeader(); void ensureParsedTransactions(); byte[] litecoinSerialize(); String getHashAsString(); String getScryptHashAsString(); Sha256Hash getHash(); Sha256Hash getScryptHash(); BigInteger getWork(); Block cloneAsHeader(); @Override String toString(); BigInteger getDifficultyTargetAsInteger(); void verifyHeader(); void verifyTransactions(); void verify(); @Override boolean equals(Object o); @Override int hashCode(); Sha256Hash getMerkleRoot(); void addTransaction(Transaction t); long getVersion(); Sha256Hash getPrevBlockHash(); long getTimeSeconds(); Date getTime(); long getDifficultyTarget(); long getNonce(); List<Transaction> getTransactions(); Block createNextBlock(Address to, TransactionOutPoint prevOut); Block createNextBlock(Address to, BigInteger value); Block createNextBlock(Address to); Block createNextBlockWithCoinbase(byte[] pubKey, BigInteger coinbaseValue); static final int HEADER_SIZE; static final int MAX_BLOCK_SIZE; static final int MAX_BLOCK_SIGOPS; } |
@SuppressWarnings("deprecation") @Test public void testDate() throws Exception { Block block = new Block(params, blockBytes); assertEquals("4 Nov 2010 16:06:04 GMT", block.getTime().toGMTString()); } | public Date getTime() { return new Date(getTimeSeconds()*1000); } | Block extends Message { public Date getTime() { return new Date(getTimeSeconds()*1000); } } | Block extends Message { public Date getTime() { return new Date(getTimeSeconds()*1000); } Block(NetworkParameters params); Block(NetworkParameters params, byte[] payloadBytes); Block(NetworkParameters params, byte[] payloadBytes, boolean parseLazy, boolean parseRetain, int length); } | Block extends Message { public Date getTime() { return new Date(getTimeSeconds()*1000); } Block(NetworkParameters params); Block(NetworkParameters params, byte[] payloadBytes); Block(NetworkParameters params, byte[] payloadBytes, boolean parseLazy, boolean parseRetain, int length); BigInteger getBlockInflation(int height); int getOptimalEncodingMessageSize(); void ensureParsed(); void ensureParsedHeader(); void ensureParsedTransactions(); byte[] litecoinSerialize(); String getHashAsString(); String getScryptHashAsString(); Sha256Hash getHash(); Sha256Hash getScryptHash(); BigInteger getWork(); Block cloneAsHeader(); @Override String toString(); BigInteger getDifficultyTargetAsInteger(); void verifyHeader(); void verifyTransactions(); void verify(); @Override boolean equals(Object o); @Override int hashCode(); Sha256Hash getMerkleRoot(); void addTransaction(Transaction t); long getVersion(); Sha256Hash getPrevBlockHash(); long getTimeSeconds(); Date getTime(); long getDifficultyTarget(); long getNonce(); List<Transaction> getTransactions(); Block createNextBlock(Address to, TransactionOutPoint prevOut); Block createNextBlock(Address to, BigInteger value); Block createNextBlock(Address to); Block createNextBlockWithCoinbase(byte[] pubKey, BigInteger coinbaseValue); } | Block extends Message { public Date getTime() { return new Date(getTimeSeconds()*1000); } Block(NetworkParameters params); Block(NetworkParameters params, byte[] payloadBytes); Block(NetworkParameters params, byte[] payloadBytes, boolean parseLazy, boolean parseRetain, int length); BigInteger getBlockInflation(int height); int getOptimalEncodingMessageSize(); void ensureParsed(); void ensureParsedHeader(); void ensureParsedTransactions(); byte[] litecoinSerialize(); String getHashAsString(); String getScryptHashAsString(); Sha256Hash getHash(); Sha256Hash getScryptHash(); BigInteger getWork(); Block cloneAsHeader(); @Override String toString(); BigInteger getDifficultyTargetAsInteger(); void verifyHeader(); void verifyTransactions(); void verify(); @Override boolean equals(Object o); @Override int hashCode(); Sha256Hash getMerkleRoot(); void addTransaction(Transaction t); long getVersion(); Sha256Hash getPrevBlockHash(); long getTimeSeconds(); Date getTime(); long getDifficultyTarget(); long getNonce(); List<Transaction> getTransactions(); Block createNextBlock(Address to, TransactionOutPoint prevOut); Block createNextBlock(Address to, BigInteger value); Block createNextBlock(Address to); Block createNextBlockWithCoinbase(byte[] pubKey, BigInteger coinbaseValue); static final int HEADER_SIZE; static final int MAX_BLOCK_SIZE; static final int MAX_BLOCK_SIGOPS; } |
@Test public void testBadTransactions() throws Exception { Block block = new Block(params, blockBytes); Transaction tx1 = block.transactions.get(0); Transaction tx2 = block.transactions.get(1); block.transactions.set(0, tx2); block.transactions.set(1, tx1); try { block.verify(); fail(); } catch (VerificationException e) { } } | public void verify() throws VerificationException { verifyHeader(); verifyTransactions(); } | Block extends Message { public void verify() throws VerificationException { verifyHeader(); verifyTransactions(); } } | Block extends Message { public void verify() throws VerificationException { verifyHeader(); verifyTransactions(); } Block(NetworkParameters params); Block(NetworkParameters params, byte[] payloadBytes); Block(NetworkParameters params, byte[] payloadBytes, boolean parseLazy, boolean parseRetain, int length); } | Block extends Message { public void verify() throws VerificationException { verifyHeader(); verifyTransactions(); } Block(NetworkParameters params); Block(NetworkParameters params, byte[] payloadBytes); Block(NetworkParameters params, byte[] payloadBytes, boolean parseLazy, boolean parseRetain, int length); BigInteger getBlockInflation(int height); int getOptimalEncodingMessageSize(); void ensureParsed(); void ensureParsedHeader(); void ensureParsedTransactions(); byte[] litecoinSerialize(); String getHashAsString(); String getScryptHashAsString(); Sha256Hash getHash(); Sha256Hash getScryptHash(); BigInteger getWork(); Block cloneAsHeader(); @Override String toString(); BigInteger getDifficultyTargetAsInteger(); void verifyHeader(); void verifyTransactions(); void verify(); @Override boolean equals(Object o); @Override int hashCode(); Sha256Hash getMerkleRoot(); void addTransaction(Transaction t); long getVersion(); Sha256Hash getPrevBlockHash(); long getTimeSeconds(); Date getTime(); long getDifficultyTarget(); long getNonce(); List<Transaction> getTransactions(); Block createNextBlock(Address to, TransactionOutPoint prevOut); Block createNextBlock(Address to, BigInteger value); Block createNextBlock(Address to); Block createNextBlockWithCoinbase(byte[] pubKey, BigInteger coinbaseValue); } | Block extends Message { public void verify() throws VerificationException { verifyHeader(); verifyTransactions(); } Block(NetworkParameters params); Block(NetworkParameters params, byte[] payloadBytes); Block(NetworkParameters params, byte[] payloadBytes, boolean parseLazy, boolean parseRetain, int length); BigInteger getBlockInflation(int height); int getOptimalEncodingMessageSize(); void ensureParsed(); void ensureParsedHeader(); void ensureParsedTransactions(); byte[] litecoinSerialize(); String getHashAsString(); String getScryptHashAsString(); Sha256Hash getHash(); Sha256Hash getScryptHash(); BigInteger getWork(); Block cloneAsHeader(); @Override String toString(); BigInteger getDifficultyTargetAsInteger(); void verifyHeader(); void verifyTransactions(); void verify(); @Override boolean equals(Object o); @Override int hashCode(); Sha256Hash getMerkleRoot(); void addTransaction(Transaction t); long getVersion(); Sha256Hash getPrevBlockHash(); long getTimeSeconds(); Date getTime(); long getDifficultyTarget(); long getNonce(); List<Transaction> getTransactions(); Block createNextBlock(Address to, TransactionOutPoint prevOut); Block createNextBlock(Address to, BigInteger value); Block createNextBlock(Address to); Block createNextBlockWithCoinbase(byte[] pubKey, BigInteger coinbaseValue); static final int HEADER_SIZE; static final int MAX_BLOCK_SIZE; static final int MAX_BLOCK_SIGOPS; } |
@Test public void getPeers_length() throws Exception{ SeedPeers seedPeers = new SeedPeers(NetworkParameters.prodNet()); InetSocketAddress[] addresses = seedPeers.getPeers(0, TimeUnit.SECONDS); assertThat(addresses.length, equalTo(SeedPeers.seedAddrs.length)); } | public InetSocketAddress[] getPeers(long timeoutValue, TimeUnit timeoutUnit) throws PeerDiscoveryException { try { return allPeers(); } catch (UnknownHostException e) { throw new PeerDiscoveryException(e); } } | SeedPeers implements PeerDiscovery { public InetSocketAddress[] getPeers(long timeoutValue, TimeUnit timeoutUnit) throws PeerDiscoveryException { try { return allPeers(); } catch (UnknownHostException e) { throw new PeerDiscoveryException(e); } } } | SeedPeers implements PeerDiscovery { public InetSocketAddress[] getPeers(long timeoutValue, TimeUnit timeoutUnit) throws PeerDiscoveryException { try { return allPeers(); } catch (UnknownHostException e) { throw new PeerDiscoveryException(e); } } SeedPeers(NetworkParameters params); } | SeedPeers implements PeerDiscovery { public InetSocketAddress[] getPeers(long timeoutValue, TimeUnit timeoutUnit) throws PeerDiscoveryException { try { return allPeers(); } catch (UnknownHostException e) { throw new PeerDiscoveryException(e); } } SeedPeers(NetworkParameters params); InetSocketAddress getPeer(); InetSocketAddress[] getPeers(long timeoutValue, TimeUnit timeoutUnit); void shutdown(); } | SeedPeers implements PeerDiscovery { public InetSocketAddress[] getPeers(long timeoutValue, TimeUnit timeoutUnit) throws PeerDiscoveryException { try { return allPeers(); } catch (UnknownHostException e) { throw new PeerDiscoveryException(e); } } SeedPeers(NetworkParameters params); InetSocketAddress getPeer(); InetSocketAddress[] getPeers(long timeoutValue, TimeUnit timeoutUnit); void shutdown(); static int[] seedAddrs; } |
@Test public void testJavaSerialiazation() throws Exception { Block block = new Block(params, blockBytes); Transaction tx = block.transactions.get(1); ByteArrayOutputStream bos = new ByteArrayOutputStream(); ObjectOutputStream oos = new ObjectOutputStream(bos); oos.writeObject(tx); oos.close(); byte[] javaBits = bos.toByteArray(); ObjectInputStream ois = new ObjectInputStream(new ByteArrayInputStream(javaBits)); Transaction tx2 = (Transaction) ois.readObject(); ois.close(); assertEquals(tx, tx2); } | private void readObject(ObjectInputStream ois) throws ClassNotFoundException, IOException { ois.defaultReadObject(); hash = null; } | Block extends Message { private void readObject(ObjectInputStream ois) throws ClassNotFoundException, IOException { ois.defaultReadObject(); hash = null; } } | Block extends Message { private void readObject(ObjectInputStream ois) throws ClassNotFoundException, IOException { ois.defaultReadObject(); hash = null; } Block(NetworkParameters params); Block(NetworkParameters params, byte[] payloadBytes); Block(NetworkParameters params, byte[] payloadBytes, boolean parseLazy, boolean parseRetain, int length); } | Block extends Message { private void readObject(ObjectInputStream ois) throws ClassNotFoundException, IOException { ois.defaultReadObject(); hash = null; } Block(NetworkParameters params); Block(NetworkParameters params, byte[] payloadBytes); Block(NetworkParameters params, byte[] payloadBytes, boolean parseLazy, boolean parseRetain, int length); BigInteger getBlockInflation(int height); int getOptimalEncodingMessageSize(); void ensureParsed(); void ensureParsedHeader(); void ensureParsedTransactions(); byte[] litecoinSerialize(); String getHashAsString(); String getScryptHashAsString(); Sha256Hash getHash(); Sha256Hash getScryptHash(); BigInteger getWork(); Block cloneAsHeader(); @Override String toString(); BigInteger getDifficultyTargetAsInteger(); void verifyHeader(); void verifyTransactions(); void verify(); @Override boolean equals(Object o); @Override int hashCode(); Sha256Hash getMerkleRoot(); void addTransaction(Transaction t); long getVersion(); Sha256Hash getPrevBlockHash(); long getTimeSeconds(); Date getTime(); long getDifficultyTarget(); long getNonce(); List<Transaction> getTransactions(); Block createNextBlock(Address to, TransactionOutPoint prevOut); Block createNextBlock(Address to, BigInteger value); Block createNextBlock(Address to); Block createNextBlockWithCoinbase(byte[] pubKey, BigInteger coinbaseValue); } | Block extends Message { private void readObject(ObjectInputStream ois) throws ClassNotFoundException, IOException { ois.defaultReadObject(); hash = null; } Block(NetworkParameters params); Block(NetworkParameters params, byte[] payloadBytes); Block(NetworkParameters params, byte[] payloadBytes, boolean parseLazy, boolean parseRetain, int length); BigInteger getBlockInflation(int height); int getOptimalEncodingMessageSize(); void ensureParsed(); void ensureParsedHeader(); void ensureParsedTransactions(); byte[] litecoinSerialize(); String getHashAsString(); String getScryptHashAsString(); Sha256Hash getHash(); Sha256Hash getScryptHash(); BigInteger getWork(); Block cloneAsHeader(); @Override String toString(); BigInteger getDifficultyTargetAsInteger(); void verifyHeader(); void verifyTransactions(); void verify(); @Override boolean equals(Object o); @Override int hashCode(); Sha256Hash getMerkleRoot(); void addTransaction(Transaction t); long getVersion(); Sha256Hash getPrevBlockHash(); long getTimeSeconds(); Date getTime(); long getDifficultyTarget(); long getNonce(); List<Transaction> getTransactions(); Block createNextBlock(Address to, TransactionOutPoint prevOut); Block createNextBlock(Address to, BigInteger value); Block createNextBlock(Address to); Block createNextBlockWithCoinbase(byte[] pubKey, BigInteger coinbaseValue); static final int HEADER_SIZE; static final int MAX_BLOCK_SIZE; static final int MAX_BLOCK_SIGOPS; } |
@Test public void testAddEventListener() throws Exception { control.replay(); connect(); PeerEventListener listener = new AbstractPeerEventListener(); peer.addEventListener(listener); assertTrue(peer.removeEventListener(listener)); assertFalse(peer.removeEventListener(listener)); } | public void addEventListener(PeerEventListener listener) { eventListeners.add(listener); } | Peer { public void addEventListener(PeerEventListener listener) { eventListeners.add(listener); } } | Peer { public void addEventListener(PeerEventListener listener) { eventListeners.add(listener); } Peer(NetworkParameters params, AbstractBlockChain chain, VersionMessage ver); Peer(NetworkParameters params, AbstractBlockChain chain, VersionMessage ver, MemoryPool mempool); Peer(NetworkParameters params, AbstractBlockChain blockChain, String thisSoftwareName, String thisSoftwareVersion); } | Peer { public void addEventListener(PeerEventListener listener) { eventListeners.add(listener); } Peer(NetworkParameters params, AbstractBlockChain chain, VersionMessage ver); Peer(NetworkParameters params, AbstractBlockChain chain, VersionMessage ver, MemoryPool mempool); Peer(NetworkParameters params, AbstractBlockChain blockChain, String thisSoftwareName, String thisSoftwareVersion); void addEventListener(PeerEventListener listener); boolean removeEventListener(PeerEventListener listener); @Override String toString(); PeerHandler getHandler(); ListenableFuture<List<Transaction>> downloadDependencies(Transaction tx); ListenableFuture<Block> getBlock(Sha256Hash blockHash); ListenableFuture<Transaction> getPeerMempoolTransaction(Sha256Hash hash); void setDownloadParameters(long secondsSinceEpoch, boolean useFilteredBlocks); void addWallet(Wallet wallet); void removeWallet(Wallet wallet); ChannelFuture sendMessage(Message m); void startBlockChainDownload(); ListenableFuture<Long> ping(); long getLastPingTime(); long getPingTime(); int getPeerBlockHeightDifference(); boolean getDownloadData(); void setDownloadData(boolean downloadData); PeerAddress getAddress(); VersionMessage getPeerVersionMessage(); VersionMessage getVersionMessage(); long getBestHeight(); ChannelFuture setMinProtocolVersion(int minProtocolVersion); void setBloomFilter(BloomFilter filter); BloomFilter getBloomFilter(); } | Peer { public void addEventListener(PeerEventListener listener) { eventListeners.add(listener); } Peer(NetworkParameters params, AbstractBlockChain chain, VersionMessage ver); Peer(NetworkParameters params, AbstractBlockChain chain, VersionMessage ver, MemoryPool mempool); Peer(NetworkParameters params, AbstractBlockChain blockChain, String thisSoftwareName, String thisSoftwareVersion); void addEventListener(PeerEventListener listener); boolean removeEventListener(PeerEventListener listener); @Override String toString(); PeerHandler getHandler(); ListenableFuture<List<Transaction>> downloadDependencies(Transaction tx); ListenableFuture<Block> getBlock(Sha256Hash blockHash); ListenableFuture<Transaction> getPeerMempoolTransaction(Sha256Hash hash); void setDownloadParameters(long secondsSinceEpoch, boolean useFilteredBlocks); void addWallet(Wallet wallet); void removeWallet(Wallet wallet); ChannelFuture sendMessage(Message m); void startBlockChainDownload(); ListenableFuture<Long> ping(); long getLastPingTime(); long getPingTime(); int getPeerBlockHeightDifference(); boolean getDownloadData(); void setDownloadData(boolean downloadData); PeerAddress getAddress(); VersionMessage getPeerVersionMessage(); VersionMessage getVersionMessage(); long getBestHeight(); ChannelFuture setMinProtocolVersion(int minProtocolVersion); void setBloomFilter(BloomFilter filter); BloomFilter getBloomFilter(); } |
@Test public void chainDownloadEnd2End() throws Exception { Block b1 = createFakeBlock(blockStore).block; blockChain.add(b1); Block b2 = makeSolvedTestBlock(b1); Block b3 = makeSolvedTestBlock(b2); Block b4 = makeSolvedTestBlock(b3); Block b5 = makeSolvedTestBlock(b4); control.replay(); connect(); peer.startBlockChainDownload(); GetBlocksMessage getblocks = (GetBlocksMessage)outbound(); assertEquals(blockStore.getChainHead().getHeader().getHash(), getblocks.getLocator().get(0)); assertEquals(Sha256Hash.ZERO_HASH, getblocks.getStopHash()); InventoryMessage inv = new InventoryMessage(unitTestParams); inv.addBlock(b2); inv.addBlock(b3); inbound(peer, inv); GetDataMessage getdata = (GetDataMessage)outbound(); assertEquals(b2.getHash(), getdata.getItems().get(0).hash); assertEquals(b3.getHash(), getdata.getItems().get(1).hash); assertEquals(2, getdata.getItems().size()); inbound(peer, b2); inbound(peer, b3); inv = new InventoryMessage(unitTestParams); inv.addBlock(b5); inbound(peer, inv); getdata = (GetDataMessage)outbound(); assertEquals(b5.getHash(), getdata.getItems().get(0).hash); assertEquals(1, getdata.getItems().size()); inbound(peer, b5); getblocks = (GetBlocksMessage)outbound(); assertEquals(b5.getHash(), getblocks.getStopHash()); assertEquals(b3.getHash(), getblocks.getLocator().get(0)); Block b6 = makeSolvedTestBlock(b5); inv = new InventoryMessage(unitTestParams); inv.addBlock(b6); inbound(peer, inv); getdata = (GetDataMessage)outbound(); assertEquals(1, getdata.getItems().size()); assertEquals(b6.getHash(), getdata.getItems().get(0).hash); inbound(peer, b6); assertFalse(event.hasCaptured()); inv = new InventoryMessage(unitTestParams); inv.addBlock(b4); inv.addBlock(b5); inbound(peer, inv); getdata = (GetDataMessage)outbound(); assertEquals(1, getdata.getItems().size()); assertEquals(b4.getHash(), getdata.getItems().get(0).hash); inbound(peer, b4); assertFalse(event.hasCaptured()); closePeer(peer); control.verify(); } | public void startBlockChainDownload() throws IOException { setDownloadData(true); final int blocksLeft = getPeerBlockHeightDifference(); if (blocksLeft >= 0) { for (PeerEventListener listener : eventListeners) listener.onChainDownloadStarted(this, blocksLeft); blockChainDownload(Sha256Hash.ZERO_HASH); } } | Peer { public void startBlockChainDownload() throws IOException { setDownloadData(true); final int blocksLeft = getPeerBlockHeightDifference(); if (blocksLeft >= 0) { for (PeerEventListener listener : eventListeners) listener.onChainDownloadStarted(this, blocksLeft); blockChainDownload(Sha256Hash.ZERO_HASH); } } } | Peer { public void startBlockChainDownload() throws IOException { setDownloadData(true); final int blocksLeft = getPeerBlockHeightDifference(); if (blocksLeft >= 0) { for (PeerEventListener listener : eventListeners) listener.onChainDownloadStarted(this, blocksLeft); blockChainDownload(Sha256Hash.ZERO_HASH); } } Peer(NetworkParameters params, AbstractBlockChain chain, VersionMessage ver); Peer(NetworkParameters params, AbstractBlockChain chain, VersionMessage ver, MemoryPool mempool); Peer(NetworkParameters params, AbstractBlockChain blockChain, String thisSoftwareName, String thisSoftwareVersion); } | Peer { public void startBlockChainDownload() throws IOException { setDownloadData(true); final int blocksLeft = getPeerBlockHeightDifference(); if (blocksLeft >= 0) { for (PeerEventListener listener : eventListeners) listener.onChainDownloadStarted(this, blocksLeft); blockChainDownload(Sha256Hash.ZERO_HASH); } } Peer(NetworkParameters params, AbstractBlockChain chain, VersionMessage ver); Peer(NetworkParameters params, AbstractBlockChain chain, VersionMessage ver, MemoryPool mempool); Peer(NetworkParameters params, AbstractBlockChain blockChain, String thisSoftwareName, String thisSoftwareVersion); void addEventListener(PeerEventListener listener); boolean removeEventListener(PeerEventListener listener); @Override String toString(); PeerHandler getHandler(); ListenableFuture<List<Transaction>> downloadDependencies(Transaction tx); ListenableFuture<Block> getBlock(Sha256Hash blockHash); ListenableFuture<Transaction> getPeerMempoolTransaction(Sha256Hash hash); void setDownloadParameters(long secondsSinceEpoch, boolean useFilteredBlocks); void addWallet(Wallet wallet); void removeWallet(Wallet wallet); ChannelFuture sendMessage(Message m); void startBlockChainDownload(); ListenableFuture<Long> ping(); long getLastPingTime(); long getPingTime(); int getPeerBlockHeightDifference(); boolean getDownloadData(); void setDownloadData(boolean downloadData); PeerAddress getAddress(); VersionMessage getPeerVersionMessage(); VersionMessage getVersionMessage(); long getBestHeight(); ChannelFuture setMinProtocolVersion(int minProtocolVersion); void setBloomFilter(BloomFilter filter); BloomFilter getBloomFilter(); } | Peer { public void startBlockChainDownload() throws IOException { setDownloadData(true); final int blocksLeft = getPeerBlockHeightDifference(); if (blocksLeft >= 0) { for (PeerEventListener listener : eventListeners) listener.onChainDownloadStarted(this, blocksLeft); blockChainDownload(Sha256Hash.ZERO_HASH); } } Peer(NetworkParameters params, AbstractBlockChain chain, VersionMessage ver); Peer(NetworkParameters params, AbstractBlockChain chain, VersionMessage ver, MemoryPool mempool); Peer(NetworkParameters params, AbstractBlockChain blockChain, String thisSoftwareName, String thisSoftwareVersion); void addEventListener(PeerEventListener listener); boolean removeEventListener(PeerEventListener listener); @Override String toString(); PeerHandler getHandler(); ListenableFuture<List<Transaction>> downloadDependencies(Transaction tx); ListenableFuture<Block> getBlock(Sha256Hash blockHash); ListenableFuture<Transaction> getPeerMempoolTransaction(Sha256Hash hash); void setDownloadParameters(long secondsSinceEpoch, boolean useFilteredBlocks); void addWallet(Wallet wallet); void removeWallet(Wallet wallet); ChannelFuture sendMessage(Message m); void startBlockChainDownload(); ListenableFuture<Long> ping(); long getLastPingTime(); long getPingTime(); int getPeerBlockHeightDifference(); boolean getDownloadData(); void setDownloadData(boolean downloadData); PeerAddress getAddress(); VersionMessage getPeerVersionMessage(); VersionMessage getVersionMessage(); long getBestHeight(); ChannelFuture setMinProtocolVersion(int minProtocolVersion); void setBloomFilter(BloomFilter filter); BloomFilter getBloomFilter(); } |
@Test public void invNoDownload() throws Exception { peer.setDownloadData(false); control.replay(); connect(); Block b1 = createFakeBlock(blockStore).block; blockChain.add(b1); Block b2 = makeSolvedTestBlock(b1); InventoryMessage inv = new InventoryMessage(unitTestParams); InventoryItem item = new InventoryItem(InventoryItem.Type.Block, b2.getHash()); inv.addItem(item); inbound(peer, inv); control.verify(); } | public void setDownloadData(boolean downloadData) { this.vDownloadData = downloadData; } | Peer { public void setDownloadData(boolean downloadData) { this.vDownloadData = downloadData; } } | Peer { public void setDownloadData(boolean downloadData) { this.vDownloadData = downloadData; } Peer(NetworkParameters params, AbstractBlockChain chain, VersionMessage ver); Peer(NetworkParameters params, AbstractBlockChain chain, VersionMessage ver, MemoryPool mempool); Peer(NetworkParameters params, AbstractBlockChain blockChain, String thisSoftwareName, String thisSoftwareVersion); } | Peer { public void setDownloadData(boolean downloadData) { this.vDownloadData = downloadData; } Peer(NetworkParameters params, AbstractBlockChain chain, VersionMessage ver); Peer(NetworkParameters params, AbstractBlockChain chain, VersionMessage ver, MemoryPool mempool); Peer(NetworkParameters params, AbstractBlockChain blockChain, String thisSoftwareName, String thisSoftwareVersion); void addEventListener(PeerEventListener listener); boolean removeEventListener(PeerEventListener listener); @Override String toString(); PeerHandler getHandler(); ListenableFuture<List<Transaction>> downloadDependencies(Transaction tx); ListenableFuture<Block> getBlock(Sha256Hash blockHash); ListenableFuture<Transaction> getPeerMempoolTransaction(Sha256Hash hash); void setDownloadParameters(long secondsSinceEpoch, boolean useFilteredBlocks); void addWallet(Wallet wallet); void removeWallet(Wallet wallet); ChannelFuture sendMessage(Message m); void startBlockChainDownload(); ListenableFuture<Long> ping(); long getLastPingTime(); long getPingTime(); int getPeerBlockHeightDifference(); boolean getDownloadData(); void setDownloadData(boolean downloadData); PeerAddress getAddress(); VersionMessage getPeerVersionMessage(); VersionMessage getVersionMessage(); long getBestHeight(); ChannelFuture setMinProtocolVersion(int minProtocolVersion); void setBloomFilter(BloomFilter filter); BloomFilter getBloomFilter(); } | Peer { public void setDownloadData(boolean downloadData) { this.vDownloadData = downloadData; } Peer(NetworkParameters params, AbstractBlockChain chain, VersionMessage ver); Peer(NetworkParameters params, AbstractBlockChain chain, VersionMessage ver, MemoryPool mempool); Peer(NetworkParameters params, AbstractBlockChain blockChain, String thisSoftwareName, String thisSoftwareVersion); void addEventListener(PeerEventListener listener); boolean removeEventListener(PeerEventListener listener); @Override String toString(); PeerHandler getHandler(); ListenableFuture<List<Transaction>> downloadDependencies(Transaction tx); ListenableFuture<Block> getBlock(Sha256Hash blockHash); ListenableFuture<Transaction> getPeerMempoolTransaction(Sha256Hash hash); void setDownloadParameters(long secondsSinceEpoch, boolean useFilteredBlocks); void addWallet(Wallet wallet); void removeWallet(Wallet wallet); ChannelFuture sendMessage(Message m); void startBlockChainDownload(); ListenableFuture<Long> ping(); long getLastPingTime(); long getPingTime(); int getPeerBlockHeightDifference(); boolean getDownloadData(); void setDownloadData(boolean downloadData); PeerAddress getAddress(); VersionMessage getPeerVersionMessage(); VersionMessage getVersionMessage(); long getBestHeight(); ChannelFuture setMinProtocolVersion(int minProtocolVersion); void setBloomFilter(BloomFilter filter); BloomFilter getBloomFilter(); } |
@Test public void invDownloadTx() throws Exception { control.replay(); connect(); peer.setDownloadData(true); BigInteger value = Utils.toNanoCoins(1, 0); Transaction tx = createFakeTx(unitTestParams, value, address); InventoryMessage inv = new InventoryMessage(unitTestParams); InventoryItem item = new InventoryItem(InventoryItem.Type.Transaction, tx.getHash()); inv.addItem(item); inbound(peer, inv); GetDataMessage getdata = (GetDataMessage) outbound(); assertEquals(1, getdata.getItems().size()); assertEquals(tx.getHash(), getdata.getItems().get(0).hash); inbound(peer, tx); getdata = (GetDataMessage) outbound(); inbound(peer, new NotFoundMessage(unitTestParams, getdata.getItems())); assertEquals(value, wallet.getBalance(Wallet.BalanceType.ESTIMATED)); } | public void setDownloadData(boolean downloadData) { this.vDownloadData = downloadData; } | Peer { public void setDownloadData(boolean downloadData) { this.vDownloadData = downloadData; } } | Peer { public void setDownloadData(boolean downloadData) { this.vDownloadData = downloadData; } Peer(NetworkParameters params, AbstractBlockChain chain, VersionMessage ver); Peer(NetworkParameters params, AbstractBlockChain chain, VersionMessage ver, MemoryPool mempool); Peer(NetworkParameters params, AbstractBlockChain blockChain, String thisSoftwareName, String thisSoftwareVersion); } | Peer { public void setDownloadData(boolean downloadData) { this.vDownloadData = downloadData; } Peer(NetworkParameters params, AbstractBlockChain chain, VersionMessage ver); Peer(NetworkParameters params, AbstractBlockChain chain, VersionMessage ver, MemoryPool mempool); Peer(NetworkParameters params, AbstractBlockChain blockChain, String thisSoftwareName, String thisSoftwareVersion); void addEventListener(PeerEventListener listener); boolean removeEventListener(PeerEventListener listener); @Override String toString(); PeerHandler getHandler(); ListenableFuture<List<Transaction>> downloadDependencies(Transaction tx); ListenableFuture<Block> getBlock(Sha256Hash blockHash); ListenableFuture<Transaction> getPeerMempoolTransaction(Sha256Hash hash); void setDownloadParameters(long secondsSinceEpoch, boolean useFilteredBlocks); void addWallet(Wallet wallet); void removeWallet(Wallet wallet); ChannelFuture sendMessage(Message m); void startBlockChainDownload(); ListenableFuture<Long> ping(); long getLastPingTime(); long getPingTime(); int getPeerBlockHeightDifference(); boolean getDownloadData(); void setDownloadData(boolean downloadData); PeerAddress getAddress(); VersionMessage getPeerVersionMessage(); VersionMessage getVersionMessage(); long getBestHeight(); ChannelFuture setMinProtocolVersion(int minProtocolVersion); void setBloomFilter(BloomFilter filter); BloomFilter getBloomFilter(); } | Peer { public void setDownloadData(boolean downloadData) { this.vDownloadData = downloadData; } Peer(NetworkParameters params, AbstractBlockChain chain, VersionMessage ver); Peer(NetworkParameters params, AbstractBlockChain chain, VersionMessage ver, MemoryPool mempool); Peer(NetworkParameters params, AbstractBlockChain blockChain, String thisSoftwareName, String thisSoftwareVersion); void addEventListener(PeerEventListener listener); boolean removeEventListener(PeerEventListener listener); @Override String toString(); PeerHandler getHandler(); ListenableFuture<List<Transaction>> downloadDependencies(Transaction tx); ListenableFuture<Block> getBlock(Sha256Hash blockHash); ListenableFuture<Transaction> getPeerMempoolTransaction(Sha256Hash hash); void setDownloadParameters(long secondsSinceEpoch, boolean useFilteredBlocks); void addWallet(Wallet wallet); void removeWallet(Wallet wallet); ChannelFuture sendMessage(Message m); void startBlockChainDownload(); ListenableFuture<Long> ping(); long getLastPingTime(); long getPingTime(); int getPeerBlockHeightDifference(); boolean getDownloadData(); void setDownloadData(boolean downloadData); PeerAddress getAddress(); VersionMessage getPeerVersionMessage(); VersionMessage getVersionMessage(); long getBestHeight(); ChannelFuture setMinProtocolVersion(int minProtocolVersion); void setBloomFilter(BloomFilter filter); BloomFilter getBloomFilter(); } |
@Test public void startBlockChainDownload() throws Exception { PeerEventListener listener = control.createMock(PeerEventListener.class); Block b1 = createFakeBlock(blockStore).block; blockChain.add(b1); Block b2 = makeSolvedTestBlock(b1); blockChain.add(b2); listener.onChainDownloadStarted(peer, 108); expectLastCall(); control.replay(); connect(); peer.addEventListener(listener); peer.startBlockChainDownload(); control.verify(); List<Sha256Hash> expectedLocator = new ArrayList<Sha256Hash>(); expectedLocator.add(b2.getHash()); expectedLocator.add(b1.getHash()); expectedLocator.add(unitTestParams.genesisBlock.getHash()); GetBlocksMessage message = (GetBlocksMessage) event.getValue().getMessage(); assertEquals(message.getLocator(), expectedLocator); assertEquals(message.getStopHash(), Sha256Hash.ZERO_HASH); } | public void startBlockChainDownload() throws IOException { setDownloadData(true); final int blocksLeft = getPeerBlockHeightDifference(); if (blocksLeft >= 0) { for (PeerEventListener listener : eventListeners) listener.onChainDownloadStarted(this, blocksLeft); blockChainDownload(Sha256Hash.ZERO_HASH); } } | Peer { public void startBlockChainDownload() throws IOException { setDownloadData(true); final int blocksLeft = getPeerBlockHeightDifference(); if (blocksLeft >= 0) { for (PeerEventListener listener : eventListeners) listener.onChainDownloadStarted(this, blocksLeft); blockChainDownload(Sha256Hash.ZERO_HASH); } } } | Peer { public void startBlockChainDownload() throws IOException { setDownloadData(true); final int blocksLeft = getPeerBlockHeightDifference(); if (blocksLeft >= 0) { for (PeerEventListener listener : eventListeners) listener.onChainDownloadStarted(this, blocksLeft); blockChainDownload(Sha256Hash.ZERO_HASH); } } Peer(NetworkParameters params, AbstractBlockChain chain, VersionMessage ver); Peer(NetworkParameters params, AbstractBlockChain chain, VersionMessage ver, MemoryPool mempool); Peer(NetworkParameters params, AbstractBlockChain blockChain, String thisSoftwareName, String thisSoftwareVersion); } | Peer { public void startBlockChainDownload() throws IOException { setDownloadData(true); final int blocksLeft = getPeerBlockHeightDifference(); if (blocksLeft >= 0) { for (PeerEventListener listener : eventListeners) listener.onChainDownloadStarted(this, blocksLeft); blockChainDownload(Sha256Hash.ZERO_HASH); } } Peer(NetworkParameters params, AbstractBlockChain chain, VersionMessage ver); Peer(NetworkParameters params, AbstractBlockChain chain, VersionMessage ver, MemoryPool mempool); Peer(NetworkParameters params, AbstractBlockChain blockChain, String thisSoftwareName, String thisSoftwareVersion); void addEventListener(PeerEventListener listener); boolean removeEventListener(PeerEventListener listener); @Override String toString(); PeerHandler getHandler(); ListenableFuture<List<Transaction>> downloadDependencies(Transaction tx); ListenableFuture<Block> getBlock(Sha256Hash blockHash); ListenableFuture<Transaction> getPeerMempoolTransaction(Sha256Hash hash); void setDownloadParameters(long secondsSinceEpoch, boolean useFilteredBlocks); void addWallet(Wallet wallet); void removeWallet(Wallet wallet); ChannelFuture sendMessage(Message m); void startBlockChainDownload(); ListenableFuture<Long> ping(); long getLastPingTime(); long getPingTime(); int getPeerBlockHeightDifference(); boolean getDownloadData(); void setDownloadData(boolean downloadData); PeerAddress getAddress(); VersionMessage getPeerVersionMessage(); VersionMessage getVersionMessage(); long getBestHeight(); ChannelFuture setMinProtocolVersion(int minProtocolVersion); void setBloomFilter(BloomFilter filter); BloomFilter getBloomFilter(); } | Peer { public void startBlockChainDownload() throws IOException { setDownloadData(true); final int blocksLeft = getPeerBlockHeightDifference(); if (blocksLeft >= 0) { for (PeerEventListener listener : eventListeners) listener.onChainDownloadStarted(this, blocksLeft); blockChainDownload(Sha256Hash.ZERO_HASH); } } Peer(NetworkParameters params, AbstractBlockChain chain, VersionMessage ver); Peer(NetworkParameters params, AbstractBlockChain chain, VersionMessage ver, MemoryPool mempool); Peer(NetworkParameters params, AbstractBlockChain blockChain, String thisSoftwareName, String thisSoftwareVersion); void addEventListener(PeerEventListener listener); boolean removeEventListener(PeerEventListener listener); @Override String toString(); PeerHandler getHandler(); ListenableFuture<List<Transaction>> downloadDependencies(Transaction tx); ListenableFuture<Block> getBlock(Sha256Hash blockHash); ListenableFuture<Transaction> getPeerMempoolTransaction(Sha256Hash hash); void setDownloadParameters(long secondsSinceEpoch, boolean useFilteredBlocks); void addWallet(Wallet wallet); void removeWallet(Wallet wallet); ChannelFuture sendMessage(Message m); void startBlockChainDownload(); ListenableFuture<Long> ping(); long getLastPingTime(); long getPingTime(); int getPeerBlockHeightDifference(); boolean getDownloadData(); void setDownloadData(boolean downloadData); PeerAddress getAddress(); VersionMessage getPeerVersionMessage(); VersionMessage getVersionMessage(); long getBestHeight(); ChannelFuture setMinProtocolVersion(int minProtocolVersion); void setBloomFilter(BloomFilter filter); BloomFilter getBloomFilter(); } |
@Test public void getBlock() throws Exception { control.replay(); connect(); Block b1 = createFakeBlock(blockStore).block; blockChain.add(b1); Block b2 = makeSolvedTestBlock(b1); Block b3 = makeSolvedTestBlock(b2); Future<Block> resultFuture = peer.getBlock(b3.getHash()); assertFalse(resultFuture.isDone()); GetDataMessage message = (GetDataMessage) event.getValue().getMessage(); assertEquals(message.getItems().get(0).hash, b3.getHash()); assertFalse(resultFuture.isDone()); inbound(peer, b3); Block b = resultFuture.get(); assertEquals(b, b3); } | public ListenableFuture<Block> getBlock(Sha256Hash blockHash) throws IOException { log.info("Request to fetch block {}", blockHash); GetDataMessage getdata = new GetDataMessage(params); getdata.addBlock(blockHash); return sendSingleGetData(getdata); } | Peer { public ListenableFuture<Block> getBlock(Sha256Hash blockHash) throws IOException { log.info("Request to fetch block {}", blockHash); GetDataMessage getdata = new GetDataMessage(params); getdata.addBlock(blockHash); return sendSingleGetData(getdata); } } | Peer { public ListenableFuture<Block> getBlock(Sha256Hash blockHash) throws IOException { log.info("Request to fetch block {}", blockHash); GetDataMessage getdata = new GetDataMessage(params); getdata.addBlock(blockHash); return sendSingleGetData(getdata); } Peer(NetworkParameters params, AbstractBlockChain chain, VersionMessage ver); Peer(NetworkParameters params, AbstractBlockChain chain, VersionMessage ver, MemoryPool mempool); Peer(NetworkParameters params, AbstractBlockChain blockChain, String thisSoftwareName, String thisSoftwareVersion); } | Peer { public ListenableFuture<Block> getBlock(Sha256Hash blockHash) throws IOException { log.info("Request to fetch block {}", blockHash); GetDataMessage getdata = new GetDataMessage(params); getdata.addBlock(blockHash); return sendSingleGetData(getdata); } Peer(NetworkParameters params, AbstractBlockChain chain, VersionMessage ver); Peer(NetworkParameters params, AbstractBlockChain chain, VersionMessage ver, MemoryPool mempool); Peer(NetworkParameters params, AbstractBlockChain blockChain, String thisSoftwareName, String thisSoftwareVersion); void addEventListener(PeerEventListener listener); boolean removeEventListener(PeerEventListener listener); @Override String toString(); PeerHandler getHandler(); ListenableFuture<List<Transaction>> downloadDependencies(Transaction tx); ListenableFuture<Block> getBlock(Sha256Hash blockHash); ListenableFuture<Transaction> getPeerMempoolTransaction(Sha256Hash hash); void setDownloadParameters(long secondsSinceEpoch, boolean useFilteredBlocks); void addWallet(Wallet wallet); void removeWallet(Wallet wallet); ChannelFuture sendMessage(Message m); void startBlockChainDownload(); ListenableFuture<Long> ping(); long getLastPingTime(); long getPingTime(); int getPeerBlockHeightDifference(); boolean getDownloadData(); void setDownloadData(boolean downloadData); PeerAddress getAddress(); VersionMessage getPeerVersionMessage(); VersionMessage getVersionMessage(); long getBestHeight(); ChannelFuture setMinProtocolVersion(int minProtocolVersion); void setBloomFilter(BloomFilter filter); BloomFilter getBloomFilter(); } | Peer { public ListenableFuture<Block> getBlock(Sha256Hash blockHash) throws IOException { log.info("Request to fetch block {}", blockHash); GetDataMessage getdata = new GetDataMessage(params); getdata.addBlock(blockHash); return sendSingleGetData(getdata); } Peer(NetworkParameters params, AbstractBlockChain chain, VersionMessage ver); Peer(NetworkParameters params, AbstractBlockChain chain, VersionMessage ver, MemoryPool mempool); Peer(NetworkParameters params, AbstractBlockChain blockChain, String thisSoftwareName, String thisSoftwareVersion); void addEventListener(PeerEventListener listener); boolean removeEventListener(PeerEventListener listener); @Override String toString(); PeerHandler getHandler(); ListenableFuture<List<Transaction>> downloadDependencies(Transaction tx); ListenableFuture<Block> getBlock(Sha256Hash blockHash); ListenableFuture<Transaction> getPeerMempoolTransaction(Sha256Hash hash); void setDownloadParameters(long secondsSinceEpoch, boolean useFilteredBlocks); void addWallet(Wallet wallet); void removeWallet(Wallet wallet); ChannelFuture sendMessage(Message m); void startBlockChainDownload(); ListenableFuture<Long> ping(); long getLastPingTime(); long getPingTime(); int getPeerBlockHeightDifference(); boolean getDownloadData(); void setDownloadData(boolean downloadData); PeerAddress getAddress(); VersionMessage getPeerVersionMessage(); VersionMessage getVersionMessage(); long getBestHeight(); ChannelFuture setMinProtocolVersion(int minProtocolVersion); void setBloomFilter(BloomFilter filter); BloomFilter getBloomFilter(); } |
@Test public void disconnectOldVersions2() throws Exception { expect(channel.close()).andReturn(null); control.replay(); handler.connectRequested(ctx, new UpstreamChannelStateEvent(channel, ChannelState.CONNECTED, socketAddress)); VersionMessage peerVersion = new VersionMessage(unitTestParams, OTHER_PEER_CHAIN_HEIGHT); peerVersion.clientVersion = 70000; DownstreamMessageEvent versionEvent = new DownstreamMessageEvent(channel, Channels.future(channel), peerVersion, null); handler.messageReceived(ctx, versionEvent); peer.setMinProtocolVersion(500); } | public ChannelFuture setMinProtocolVersion(int minProtocolVersion) { this.vMinProtocolVersion = minProtocolVersion; if (getVersionMessage().clientVersion < minProtocolVersion) { log.warn("{}: Disconnecting due to new min protocol version {}", this, minProtocolVersion); return Channels.close(vChannel); } else { return null; } } | Peer { public ChannelFuture setMinProtocolVersion(int minProtocolVersion) { this.vMinProtocolVersion = minProtocolVersion; if (getVersionMessage().clientVersion < minProtocolVersion) { log.warn("{}: Disconnecting due to new min protocol version {}", this, minProtocolVersion); return Channels.close(vChannel); } else { return null; } } } | Peer { public ChannelFuture setMinProtocolVersion(int minProtocolVersion) { this.vMinProtocolVersion = minProtocolVersion; if (getVersionMessage().clientVersion < minProtocolVersion) { log.warn("{}: Disconnecting due to new min protocol version {}", this, minProtocolVersion); return Channels.close(vChannel); } else { return null; } } Peer(NetworkParameters params, AbstractBlockChain chain, VersionMessage ver); Peer(NetworkParameters params, AbstractBlockChain chain, VersionMessage ver, MemoryPool mempool); Peer(NetworkParameters params, AbstractBlockChain blockChain, String thisSoftwareName, String thisSoftwareVersion); } | Peer { public ChannelFuture setMinProtocolVersion(int minProtocolVersion) { this.vMinProtocolVersion = minProtocolVersion; if (getVersionMessage().clientVersion < minProtocolVersion) { log.warn("{}: Disconnecting due to new min protocol version {}", this, minProtocolVersion); return Channels.close(vChannel); } else { return null; } } Peer(NetworkParameters params, AbstractBlockChain chain, VersionMessage ver); Peer(NetworkParameters params, AbstractBlockChain chain, VersionMessage ver, MemoryPool mempool); Peer(NetworkParameters params, AbstractBlockChain blockChain, String thisSoftwareName, String thisSoftwareVersion); void addEventListener(PeerEventListener listener); boolean removeEventListener(PeerEventListener listener); @Override String toString(); PeerHandler getHandler(); ListenableFuture<List<Transaction>> downloadDependencies(Transaction tx); ListenableFuture<Block> getBlock(Sha256Hash blockHash); ListenableFuture<Transaction> getPeerMempoolTransaction(Sha256Hash hash); void setDownloadParameters(long secondsSinceEpoch, boolean useFilteredBlocks); void addWallet(Wallet wallet); void removeWallet(Wallet wallet); ChannelFuture sendMessage(Message m); void startBlockChainDownload(); ListenableFuture<Long> ping(); long getLastPingTime(); long getPingTime(); int getPeerBlockHeightDifference(); boolean getDownloadData(); void setDownloadData(boolean downloadData); PeerAddress getAddress(); VersionMessage getPeerVersionMessage(); VersionMessage getVersionMessage(); long getBestHeight(); ChannelFuture setMinProtocolVersion(int minProtocolVersion); void setBloomFilter(BloomFilter filter); BloomFilter getBloomFilter(); } | Peer { public ChannelFuture setMinProtocolVersion(int minProtocolVersion) { this.vMinProtocolVersion = minProtocolVersion; if (getVersionMessage().clientVersion < minProtocolVersion) { log.warn("{}: Disconnecting due to new min protocol version {}", this, minProtocolVersion); return Channels.close(vChannel); } else { return null; } } Peer(NetworkParameters params, AbstractBlockChain chain, VersionMessage ver); Peer(NetworkParameters params, AbstractBlockChain chain, VersionMessage ver, MemoryPool mempool); Peer(NetworkParameters params, AbstractBlockChain blockChain, String thisSoftwareName, String thisSoftwareVersion); void addEventListener(PeerEventListener listener); boolean removeEventListener(PeerEventListener listener); @Override String toString(); PeerHandler getHandler(); ListenableFuture<List<Transaction>> downloadDependencies(Transaction tx); ListenableFuture<Block> getBlock(Sha256Hash blockHash); ListenableFuture<Transaction> getPeerMempoolTransaction(Sha256Hash hash); void setDownloadParameters(long secondsSinceEpoch, boolean useFilteredBlocks); void addWallet(Wallet wallet); void removeWallet(Wallet wallet); ChannelFuture sendMessage(Message m); void startBlockChainDownload(); ListenableFuture<Long> ping(); long getLastPingTime(); long getPingTime(); int getPeerBlockHeightDifference(); boolean getDownloadData(); void setDownloadData(boolean downloadData); PeerAddress getAddress(); VersionMessage getPeerVersionMessage(); VersionMessage getVersionMessage(); long getBestHeight(); ChannelFuture setMinProtocolVersion(int minProtocolVersion); void setBloomFilter(BloomFilter filter); BloomFilter getBloomFilter(); } |
@Test public void peerDiscoveryPolling() throws Exception { final Semaphore sem = new Semaphore(0); final boolean[] result = new boolean[1]; result[0] = false; peerGroup.addPeerDiscovery(new PeerDiscovery() { public InetSocketAddress[] getPeers(long unused, TimeUnit unused2) throws PeerDiscoveryException { if (result[0] == false) { result[0] = true; throw new PeerDiscoveryException("test failure"); } else { sem.release(); return new InetSocketAddress[]{new InetSocketAddress("localhost", 0)}; } } public void shutdown() { } }); peerGroup.startAndWait(); sem.acquire(); assertTrue(result[0]); } | public void addPeerDiscovery(PeerDiscovery peerDiscovery) { lock.lock(); try { if (getMaxConnections() == 0) setMaxConnections(DEFAULT_CONNECTIONS); peerDiscoverers.add(peerDiscovery); } finally { lock.unlock(); } } | PeerGroup extends AbstractIdleService { public void addPeerDiscovery(PeerDiscovery peerDiscovery) { lock.lock(); try { if (getMaxConnections() == 0) setMaxConnections(DEFAULT_CONNECTIONS); peerDiscoverers.add(peerDiscovery); } finally { lock.unlock(); } } } | PeerGroup extends AbstractIdleService { public void addPeerDiscovery(PeerDiscovery peerDiscovery) { lock.lock(); try { if (getMaxConnections() == 0) setMaxConnections(DEFAULT_CONNECTIONS); peerDiscoverers.add(peerDiscovery); } finally { lock.unlock(); } } PeerGroup(NetworkParameters params); PeerGroup(NetworkParameters params, AbstractBlockChain chain); PeerGroup(NetworkParameters params, AbstractBlockChain chain, ClientBootstrap bootstrap); } | PeerGroup extends AbstractIdleService { public void addPeerDiscovery(PeerDiscovery peerDiscovery) { lock.lock(); try { if (getMaxConnections() == 0) setMaxConnections(DEFAULT_CONNECTIONS); peerDiscoverers.add(peerDiscovery); } finally { lock.unlock(); } } PeerGroup(NetworkParameters params); PeerGroup(NetworkParameters params, AbstractBlockChain chain); PeerGroup(NetworkParameters params, AbstractBlockChain chain, ClientBootstrap bootstrap); static ClientBootstrap createClientBootstrap(); void setMaxConnections(int maxConnections); int getMaxConnections(); void setVersionMessage(VersionMessage ver); VersionMessage getVersionMessage(); void setUserAgent(String name, String version, String comments); void setUserAgent(String name, String version); void addEventListener(PeerEventListener listener); boolean removeEventListener(PeerEventListener listener); List<Peer> getConnectedPeers(); List<Peer> getPendingPeers(); void addAddress(PeerAddress peerAddress); void addAddress(InetAddress address); void addPeerDiscovery(PeerDiscovery peerDiscovery); void addWallet(Wallet wallet); void removeWallet(Wallet wallet); void setBloomFilterFalsePositiveRate(double bloomFilterFPRate); int numConnectedPeers(); ChannelFuture connectTo(SocketAddress address); static Peer peerFromChannelFuture(ChannelFuture future); static Peer peerFromChannel(Channel channel); void startBlockChainDownload(PeerEventListener listener); void downloadBlockChain(); MemoryPool getMemoryPool(); void setFastCatchupTimeSecs(long secondsSinceEpoch); long getFastCatchupTimeSecs(); ListenableFuture<PeerGroup> waitForPeers(final int numPeers); int getMinBroadcastConnections(); void setMinBroadcastConnections(int value); ListenableFuture<Transaction> broadcastTransaction(final Transaction tx); ListenableFuture<Transaction> broadcastTransaction(final Transaction tx, final int minConnections); long getPingIntervalMsec(); void setPingIntervalMsec(long pingIntervalMsec); int getMostCommonChainHeight(); Peer getDownloadPeer(); } | PeerGroup extends AbstractIdleService { public void addPeerDiscovery(PeerDiscovery peerDiscovery) { lock.lock(); try { if (getMaxConnections() == 0) setMaxConnections(DEFAULT_CONNECTIONS); peerDiscoverers.add(peerDiscovery); } finally { lock.unlock(); } } PeerGroup(NetworkParameters params); PeerGroup(NetworkParameters params, AbstractBlockChain chain); PeerGroup(NetworkParameters params, AbstractBlockChain chain, ClientBootstrap bootstrap); static ClientBootstrap createClientBootstrap(); void setMaxConnections(int maxConnections); int getMaxConnections(); void setVersionMessage(VersionMessage ver); VersionMessage getVersionMessage(); void setUserAgent(String name, String version, String comments); void setUserAgent(String name, String version); void addEventListener(PeerEventListener listener); boolean removeEventListener(PeerEventListener listener); List<Peer> getConnectedPeers(); List<Peer> getPendingPeers(); void addAddress(PeerAddress peerAddress); void addAddress(InetAddress address); void addPeerDiscovery(PeerDiscovery peerDiscovery); void addWallet(Wallet wallet); void removeWallet(Wallet wallet); void setBloomFilterFalsePositiveRate(double bloomFilterFPRate); int numConnectedPeers(); ChannelFuture connectTo(SocketAddress address); static Peer peerFromChannelFuture(ChannelFuture future); static Peer peerFromChannel(Channel channel); void startBlockChainDownload(PeerEventListener listener); void downloadBlockChain(); MemoryPool getMemoryPool(); void setFastCatchupTimeSecs(long secondsSinceEpoch); long getFastCatchupTimeSecs(); ListenableFuture<PeerGroup> waitForPeers(final int numPeers); int getMinBroadcastConnections(); void setMinBroadcastConnections(int value); ListenableFuture<Transaction> broadcastTransaction(final Transaction tx); ListenableFuture<Transaction> broadcastTransaction(final Transaction tx, final int minConnections); long getPingIntervalMsec(); void setPingIntervalMsec(long pingIntervalMsec); int getMostCommonChainHeight(); Peer getDownloadPeer(); static final long DEFAULT_PING_INTERVAL_MSEC; static final double DEFAULT_BLOOM_FILTER_FP_RATE; } |
@Test public void singleDownloadPeer1() throws Exception { peerGroup.startAndWait(); FakeChannel p1 = connectPeer(1); FakeChannel p2 = connectPeer(2); assertEquals(2, peerGroup.numConnectedPeers()); Block b1 = TestUtils.createFakeBlock(blockStore).block; blockChain.add(b1); Block b2 = TestUtils.makeSolvedTestBlock(b1); Block b3 = TestUtils.makeSolvedTestBlock(b2); InventoryMessage inv = new InventoryMessage(params); inv.addBlock(b3); inbound(p1, inv); assertTrue(outbound(p1) instanceof GetDataMessage); assertNull(outbound(p2)); closePeer(peerOf(p1)); inbound(p2, inv); assertTrue(outbound(p2) instanceof GetDataMessage); peerGroup.stop(); } | public int numConnectedPeers() { return peers.size(); } | PeerGroup extends AbstractIdleService { public int numConnectedPeers() { return peers.size(); } } | PeerGroup extends AbstractIdleService { public int numConnectedPeers() { return peers.size(); } PeerGroup(NetworkParameters params); PeerGroup(NetworkParameters params, AbstractBlockChain chain); PeerGroup(NetworkParameters params, AbstractBlockChain chain, ClientBootstrap bootstrap); } | PeerGroup extends AbstractIdleService { public int numConnectedPeers() { return peers.size(); } PeerGroup(NetworkParameters params); PeerGroup(NetworkParameters params, AbstractBlockChain chain); PeerGroup(NetworkParameters params, AbstractBlockChain chain, ClientBootstrap bootstrap); static ClientBootstrap createClientBootstrap(); void setMaxConnections(int maxConnections); int getMaxConnections(); void setVersionMessage(VersionMessage ver); VersionMessage getVersionMessage(); void setUserAgent(String name, String version, String comments); void setUserAgent(String name, String version); void addEventListener(PeerEventListener listener); boolean removeEventListener(PeerEventListener listener); List<Peer> getConnectedPeers(); List<Peer> getPendingPeers(); void addAddress(PeerAddress peerAddress); void addAddress(InetAddress address); void addPeerDiscovery(PeerDiscovery peerDiscovery); void addWallet(Wallet wallet); void removeWallet(Wallet wallet); void setBloomFilterFalsePositiveRate(double bloomFilterFPRate); int numConnectedPeers(); ChannelFuture connectTo(SocketAddress address); static Peer peerFromChannelFuture(ChannelFuture future); static Peer peerFromChannel(Channel channel); void startBlockChainDownload(PeerEventListener listener); void downloadBlockChain(); MemoryPool getMemoryPool(); void setFastCatchupTimeSecs(long secondsSinceEpoch); long getFastCatchupTimeSecs(); ListenableFuture<PeerGroup> waitForPeers(final int numPeers); int getMinBroadcastConnections(); void setMinBroadcastConnections(int value); ListenableFuture<Transaction> broadcastTransaction(final Transaction tx); ListenableFuture<Transaction> broadcastTransaction(final Transaction tx, final int minConnections); long getPingIntervalMsec(); void setPingIntervalMsec(long pingIntervalMsec); int getMostCommonChainHeight(); Peer getDownloadPeer(); } | PeerGroup extends AbstractIdleService { public int numConnectedPeers() { return peers.size(); } PeerGroup(NetworkParameters params); PeerGroup(NetworkParameters params, AbstractBlockChain chain); PeerGroup(NetworkParameters params, AbstractBlockChain chain, ClientBootstrap bootstrap); static ClientBootstrap createClientBootstrap(); void setMaxConnections(int maxConnections); int getMaxConnections(); void setVersionMessage(VersionMessage ver); VersionMessage getVersionMessage(); void setUserAgent(String name, String version, String comments); void setUserAgent(String name, String version); void addEventListener(PeerEventListener listener); boolean removeEventListener(PeerEventListener listener); List<Peer> getConnectedPeers(); List<Peer> getPendingPeers(); void addAddress(PeerAddress peerAddress); void addAddress(InetAddress address); void addPeerDiscovery(PeerDiscovery peerDiscovery); void addWallet(Wallet wallet); void removeWallet(Wallet wallet); void setBloomFilterFalsePositiveRate(double bloomFilterFPRate); int numConnectedPeers(); ChannelFuture connectTo(SocketAddress address); static Peer peerFromChannelFuture(ChannelFuture future); static Peer peerFromChannel(Channel channel); void startBlockChainDownload(PeerEventListener listener); void downloadBlockChain(); MemoryPool getMemoryPool(); void setFastCatchupTimeSecs(long secondsSinceEpoch); long getFastCatchupTimeSecs(); ListenableFuture<PeerGroup> waitForPeers(final int numPeers); int getMinBroadcastConnections(); void setMinBroadcastConnections(int value); ListenableFuture<Transaction> broadcastTransaction(final Transaction tx); ListenableFuture<Transaction> broadcastTransaction(final Transaction tx, final int minConnections); long getPingIntervalMsec(); void setPingIntervalMsec(long pingIntervalMsec); int getMostCommonChainHeight(); Peer getDownloadPeer(); static final long DEFAULT_PING_INTERVAL_MSEC; static final double DEFAULT_BLOOM_FILTER_FP_RATE; } |
@Test public void testParseUserList() throws UnknownHostException { String[] userList = new String[]{ "x201500200","u4stwEBjT6FYyVV", "u5BKEqDApa8SbA7"}; ArrayList<InetSocketAddress> addresses = IrcDiscovery.parseUserList(userList); assertEquals("Too many addresses.", 2, addresses.size()); String[] ips = new String[]{"69.4.98.82:8333","74.92.222.129:8333"}; InetSocketAddress[] decoded = addresses.toArray(new InetSocketAddress[]{}); for (int i = 0; i < decoded.length; i++) { String formattedIP = decoded[i].getAddress().getHostAddress() + ":" + ((Integer)decoded[i].getPort()) .toString(); assertEquals("IPs decoded improperly", ips[i], formattedIP); } } | static ArrayList<InetSocketAddress> parseUserList(String[] userNames) throws UnknownHostException { ArrayList<InetSocketAddress> addresses = new ArrayList<InetSocketAddress>(); for (String user : userNames) { if (!user.startsWith("u")) { continue; } byte[] addressBytes; try { addressBytes = Base58.decodeChecked(user.substring(1)); } catch (AddressFormatException e) { log.warn("IRC nick does not parse as base58: " + user); continue; } if (addressBytes.length != 6) { continue; } byte[] ipBytes = new byte[]{addressBytes[0], addressBytes[1], addressBytes[2], addressBytes[3]}; int port = Utils.readUint16BE(addressBytes, 4); InetAddress ip; try { ip = InetAddress.getByAddress(ipBytes); } catch (UnknownHostException e) { continue; } InetSocketAddress address = new InetSocketAddress(ip, port); addresses.add(address); } return addresses; } | IrcDiscovery implements PeerDiscovery { static ArrayList<InetSocketAddress> parseUserList(String[] userNames) throws UnknownHostException { ArrayList<InetSocketAddress> addresses = new ArrayList<InetSocketAddress>(); for (String user : userNames) { if (!user.startsWith("u")) { continue; } byte[] addressBytes; try { addressBytes = Base58.decodeChecked(user.substring(1)); } catch (AddressFormatException e) { log.warn("IRC nick does not parse as base58: " + user); continue; } if (addressBytes.length != 6) { continue; } byte[] ipBytes = new byte[]{addressBytes[0], addressBytes[1], addressBytes[2], addressBytes[3]}; int port = Utils.readUint16BE(addressBytes, 4); InetAddress ip; try { ip = InetAddress.getByAddress(ipBytes); } catch (UnknownHostException e) { continue; } InetSocketAddress address = new InetSocketAddress(ip, port); addresses.add(address); } return addresses; } } | IrcDiscovery implements PeerDiscovery { static ArrayList<InetSocketAddress> parseUserList(String[] userNames) throws UnknownHostException { ArrayList<InetSocketAddress> addresses = new ArrayList<InetSocketAddress>(); for (String user : userNames) { if (!user.startsWith("u")) { continue; } byte[] addressBytes; try { addressBytes = Base58.decodeChecked(user.substring(1)); } catch (AddressFormatException e) { log.warn("IRC nick does not parse as base58: " + user); continue; } if (addressBytes.length != 6) { continue; } byte[] ipBytes = new byte[]{addressBytes[0], addressBytes[1], addressBytes[2], addressBytes[3]}; int port = Utils.readUint16BE(addressBytes, 4); InetAddress ip; try { ip = InetAddress.getByAddress(ipBytes); } catch (UnknownHostException e) { continue; } InetSocketAddress address = new InetSocketAddress(ip, port); addresses.add(address); } return addresses; } IrcDiscovery(String channel); IrcDiscovery(String channel, String server, int port); } | IrcDiscovery implements PeerDiscovery { static ArrayList<InetSocketAddress> parseUserList(String[] userNames) throws UnknownHostException { ArrayList<InetSocketAddress> addresses = new ArrayList<InetSocketAddress>(); for (String user : userNames) { if (!user.startsWith("u")) { continue; } byte[] addressBytes; try { addressBytes = Base58.decodeChecked(user.substring(1)); } catch (AddressFormatException e) { log.warn("IRC nick does not parse as base58: " + user); continue; } if (addressBytes.length != 6) { continue; } byte[] ipBytes = new byte[]{addressBytes[0], addressBytes[1], addressBytes[2], addressBytes[3]}; int port = Utils.readUint16BE(addressBytes, 4); InetAddress ip; try { ip = InetAddress.getByAddress(ipBytes); } catch (UnknownHostException e) { continue; } InetSocketAddress address = new InetSocketAddress(ip, port); addresses.add(address); } return addresses; } IrcDiscovery(String channel); IrcDiscovery(String channel, String server, int port); void shutdown(); InetSocketAddress[] getPeers(long timeoutValue, TimeUnit timeoutUnit); } | IrcDiscovery implements PeerDiscovery { static ArrayList<InetSocketAddress> parseUserList(String[] userNames) throws UnknownHostException { ArrayList<InetSocketAddress> addresses = new ArrayList<InetSocketAddress>(); for (String user : userNames) { if (!user.startsWith("u")) { continue; } byte[] addressBytes; try { addressBytes = Base58.decodeChecked(user.substring(1)); } catch (AddressFormatException e) { log.warn("IRC nick does not parse as base58: " + user); continue; } if (addressBytes.length != 6) { continue; } byte[] ipBytes = new byte[]{addressBytes[0], addressBytes[1], addressBytes[2], addressBytes[3]}; int port = Utils.readUint16BE(addressBytes, 4); InetAddress ip; try { ip = InetAddress.getByAddress(ipBytes); } catch (UnknownHostException e) { continue; } InetSocketAddress address = new InetSocketAddress(ip, port); addresses.add(address); } return addresses; } IrcDiscovery(String channel); IrcDiscovery(String channel, String server, int port); void shutdown(); InetSocketAddress[] getPeers(long timeoutValue, TimeUnit timeoutUnit); } |
@Test public void singleDownloadPeer2() throws Exception { peerGroup.startAndWait(); FakeChannel p1 = connectPeer(1); Block b1 = TestUtils.createFakeBlock(blockStore).block; Block b2 = TestUtils.makeSolvedTestBlock(b1); Block b3 = TestUtils.makeSolvedTestBlock(b2); peerGroup.startBlockChainDownload(new AbstractPeerEventListener() { }); GetBlocksMessage getblocks = (GetBlocksMessage) outbound(p1); assertEquals(Sha256Hash.ZERO_HASH, getblocks.getStopHash()); InventoryMessage inv = new InventoryMessage(params); inv.addBlock(b1); inv.addBlock(b2); inv.addBlock(b3); inbound(p1, inv); assertTrue(outbound(p1) instanceof GetDataMessage); inbound(p1, b1); FakeChannel p2 = connectPeer(2); Message message = (Message)outbound(p2); assertNull(message == null ? "" : message.toString(), message); peerGroup.stop(); } | public void startBlockChainDownload(PeerEventListener listener) { lock.lock(); try { this.downloadListener = listener; synchronized (peers) { if (!peers.isEmpty()) { startBlockChainDownloadFromPeer(peers.iterator().next()); } } } finally { lock.unlock(); } } | PeerGroup extends AbstractIdleService { public void startBlockChainDownload(PeerEventListener listener) { lock.lock(); try { this.downloadListener = listener; synchronized (peers) { if (!peers.isEmpty()) { startBlockChainDownloadFromPeer(peers.iterator().next()); } } } finally { lock.unlock(); } } } | PeerGroup extends AbstractIdleService { public void startBlockChainDownload(PeerEventListener listener) { lock.lock(); try { this.downloadListener = listener; synchronized (peers) { if (!peers.isEmpty()) { startBlockChainDownloadFromPeer(peers.iterator().next()); } } } finally { lock.unlock(); } } PeerGroup(NetworkParameters params); PeerGroup(NetworkParameters params, AbstractBlockChain chain); PeerGroup(NetworkParameters params, AbstractBlockChain chain, ClientBootstrap bootstrap); } | PeerGroup extends AbstractIdleService { public void startBlockChainDownload(PeerEventListener listener) { lock.lock(); try { this.downloadListener = listener; synchronized (peers) { if (!peers.isEmpty()) { startBlockChainDownloadFromPeer(peers.iterator().next()); } } } finally { lock.unlock(); } } PeerGroup(NetworkParameters params); PeerGroup(NetworkParameters params, AbstractBlockChain chain); PeerGroup(NetworkParameters params, AbstractBlockChain chain, ClientBootstrap bootstrap); static ClientBootstrap createClientBootstrap(); void setMaxConnections(int maxConnections); int getMaxConnections(); void setVersionMessage(VersionMessage ver); VersionMessage getVersionMessage(); void setUserAgent(String name, String version, String comments); void setUserAgent(String name, String version); void addEventListener(PeerEventListener listener); boolean removeEventListener(PeerEventListener listener); List<Peer> getConnectedPeers(); List<Peer> getPendingPeers(); void addAddress(PeerAddress peerAddress); void addAddress(InetAddress address); void addPeerDiscovery(PeerDiscovery peerDiscovery); void addWallet(Wallet wallet); void removeWallet(Wallet wallet); void setBloomFilterFalsePositiveRate(double bloomFilterFPRate); int numConnectedPeers(); ChannelFuture connectTo(SocketAddress address); static Peer peerFromChannelFuture(ChannelFuture future); static Peer peerFromChannel(Channel channel); void startBlockChainDownload(PeerEventListener listener); void downloadBlockChain(); MemoryPool getMemoryPool(); void setFastCatchupTimeSecs(long secondsSinceEpoch); long getFastCatchupTimeSecs(); ListenableFuture<PeerGroup> waitForPeers(final int numPeers); int getMinBroadcastConnections(); void setMinBroadcastConnections(int value); ListenableFuture<Transaction> broadcastTransaction(final Transaction tx); ListenableFuture<Transaction> broadcastTransaction(final Transaction tx, final int minConnections); long getPingIntervalMsec(); void setPingIntervalMsec(long pingIntervalMsec); int getMostCommonChainHeight(); Peer getDownloadPeer(); } | PeerGroup extends AbstractIdleService { public void startBlockChainDownload(PeerEventListener listener) { lock.lock(); try { this.downloadListener = listener; synchronized (peers) { if (!peers.isEmpty()) { startBlockChainDownloadFromPeer(peers.iterator().next()); } } } finally { lock.unlock(); } } PeerGroup(NetworkParameters params); PeerGroup(NetworkParameters params, AbstractBlockChain chain); PeerGroup(NetworkParameters params, AbstractBlockChain chain, ClientBootstrap bootstrap); static ClientBootstrap createClientBootstrap(); void setMaxConnections(int maxConnections); int getMaxConnections(); void setVersionMessage(VersionMessage ver); VersionMessage getVersionMessage(); void setUserAgent(String name, String version, String comments); void setUserAgent(String name, String version); void addEventListener(PeerEventListener listener); boolean removeEventListener(PeerEventListener listener); List<Peer> getConnectedPeers(); List<Peer> getPendingPeers(); void addAddress(PeerAddress peerAddress); void addAddress(InetAddress address); void addPeerDiscovery(PeerDiscovery peerDiscovery); void addWallet(Wallet wallet); void removeWallet(Wallet wallet); void setBloomFilterFalsePositiveRate(double bloomFilterFPRate); int numConnectedPeers(); ChannelFuture connectTo(SocketAddress address); static Peer peerFromChannelFuture(ChannelFuture future); static Peer peerFromChannel(Channel channel); void startBlockChainDownload(PeerEventListener listener); void downloadBlockChain(); MemoryPool getMemoryPool(); void setFastCatchupTimeSecs(long secondsSinceEpoch); long getFastCatchupTimeSecs(); ListenableFuture<PeerGroup> waitForPeers(final int numPeers); int getMinBroadcastConnections(); void setMinBroadcastConnections(int value); ListenableFuture<Transaction> broadcastTransaction(final Transaction tx); ListenableFuture<Transaction> broadcastTransaction(final Transaction tx, final int minConnections); long getPingIntervalMsec(); void setPingIntervalMsec(long pingIntervalMsec); int getMostCommonChainHeight(); Peer getDownloadPeer(); static final long DEFAULT_PING_INTERVAL_MSEC; static final double DEFAULT_BLOOM_FILTER_FP_RATE; } |
@Test public void testHeaders1() throws Exception { LitecoinSerializer bs = new LitecoinSerializer(NetworkParameters.prodNet()); ByteArrayInputStream bais = new ByteArrayInputStream(Hex.decode("fbc0b6db686561" + "646572730000000000520000005d4fab8101010000006fe28c0ab6f1b372c1a6a246ae6" + "3f74f931e8365e15a089c68d6190000000000982051fd1e4ba744bbbe680e1fee14677b" + "a1a3c3540bf7b1cdb606e857233e0e61bc6649ffff001d01e3629900")); HeadersMessage hm = (HeadersMessage) bs.deserialize(bais); Block block = hm.getBlockHeaders().get(0); String hash = block.getHashAsString(); assertEquals(hash, "00000000839a8e6886ab5951d76f411475428afc90947ee320161bbf18eb6048"); assertNull(block.transactions); assertEquals(Utils.bytesToHexString(block.getMerkleRoot().getBytes()), "0e3e2357e806b6cdb1f70b54c3a3a17b6714ee1f0e68bebb44a74b1efd512098"); } | public Message deserialize(InputStream in) throws ProtocolException, IOException { seekPastMagicBytes(in); LitecoinPacketHeader header = new LitecoinPacketHeader(in); return deserializePayload(header, in); } | LitecoinSerializer { public Message deserialize(InputStream in) throws ProtocolException, IOException { seekPastMagicBytes(in); LitecoinPacketHeader header = new LitecoinPacketHeader(in); return deserializePayload(header, in); } } | LitecoinSerializer { public Message deserialize(InputStream in) throws ProtocolException, IOException { seekPastMagicBytes(in); LitecoinPacketHeader header = new LitecoinPacketHeader(in); return deserializePayload(header, in); } LitecoinSerializer(NetworkParameters params); LitecoinSerializer(NetworkParameters params, boolean parseLazy, boolean parseRetain); } | LitecoinSerializer { public Message deserialize(InputStream in) throws ProtocolException, IOException { seekPastMagicBytes(in); LitecoinPacketHeader header = new LitecoinPacketHeader(in); return deserializePayload(header, in); } LitecoinSerializer(NetworkParameters params); LitecoinSerializer(NetworkParameters params, boolean parseLazy, boolean parseRetain); void serialize(Message message, OutputStream out); Message deserialize(InputStream in); LitecoinPacketHeader deserializeHeader(InputStream in); Message deserializePayload(LitecoinPacketHeader header, InputStream in); void seekPastMagicBytes(InputStream in); boolean isParseLazyMode(); boolean isParseRetainMode(); } | LitecoinSerializer { public Message deserialize(InputStream in) throws ProtocolException, IOException { seekPastMagicBytes(in); LitecoinPacketHeader header = new LitecoinPacketHeader(in); return deserializePayload(header, in); } LitecoinSerializer(NetworkParameters params); LitecoinSerializer(NetworkParameters params, boolean parseLazy, boolean parseRetain); void serialize(Message message, OutputStream out); Message deserialize(InputStream in); LitecoinPacketHeader deserializeHeader(InputStream in); Message deserializePayload(LitecoinPacketHeader header, InputStream in); void seekPastMagicBytes(InputStream in); boolean isParseLazyMode(); boolean isParseRetainMode(); } |
@Test public void testHeaders2() throws Exception { LitecoinSerializer bs = new LitecoinSerializer(NetworkParameters.prodNet()); ByteArrayInputStream bais = new ByteArrayInputStream(Hex.decode("fbc0b6db6865616465" + "72730000000000e701000085acd4ea06010000006fe28c0ab6f1b372c1a6a246ae63f74f931e" + "8365e15a089c68d6190000000000982051fd1e4ba744bbbe680e1fee14677ba1a3c3540bf7b1c" + "db606e857233e0e61bc6649ffff001d01e3629900010000004860eb18bf1b1620e37e9490fc8a" + "427514416fd75159ab86688e9a8300000000d5fdcc541e25de1c7a5addedf24858b8bb665c9f36" + "ef744ee42c316022c90f9bb0bc6649ffff001d08d2bd610001000000bddd99ccfda39da1b108ce1" + "a5d70038d0a967bacb68b6b63065f626a0000000044f672226090d85db9a9f2fbfe5f0f9609b387" + "af7be5b7fbb7a1767c831c9e995dbe6649ffff001d05e0ed6d00010000004944469562ae1c2c74" + "d9a535e00b6f3e40ffbad4f2fda3895501b582000000007a06ea98cd40ba2e3288262b28638cec" + "5337c1456aaf5eedc8e9e5a20f062bdf8cc16649ffff001d2bfee0a9000100000085144a84488e" + "a88d221c8bd6c059da090e88f8a2c99690ee55dbba4e00000000e11c48fecdd9e72510ca84f023" + "370c9a38bf91ac5cae88019bee94d24528526344c36649ffff001d1d03e4770001000000fc33f5" + "96f822a0a1951ffdbf2a897b095636ad871707bf5d3162729b00000000379dfb96a5ea8c81700ea4" + "ac6b97ae9a9312b2d4301a29580e924ee6761a2520adc46649ffff001d189c4c9700")); HeadersMessage hm = (HeadersMessage) bs.deserialize(bais); int nBlocks = hm.getBlockHeaders().size(); assertEquals(nBlocks, 6); Block zeroBlock = hm.getBlockHeaders().get(0); String zeroBlockHash = zeroBlock.getHashAsString(); assertEquals("00000000839a8e6886ab5951d76f411475428afc90947ee320161bbf18eb6048", zeroBlockHash); assertEquals(zeroBlock.getNonce(), 2573394689L); Block thirdBlock = hm.getBlockHeaders().get(3); String thirdBlockHash = thirdBlock.getHashAsString(); assertEquals("000000004ebadb55ee9096c9a2f8880e09da59c0d68b1c228da88e48844a1485", thirdBlockHash); assertEquals(thirdBlock.getNonce(), 2850094635L); } | public Message deserialize(InputStream in) throws ProtocolException, IOException { seekPastMagicBytes(in); LitecoinPacketHeader header = new LitecoinPacketHeader(in); return deserializePayload(header, in); } | LitecoinSerializer { public Message deserialize(InputStream in) throws ProtocolException, IOException { seekPastMagicBytes(in); LitecoinPacketHeader header = new LitecoinPacketHeader(in); return deserializePayload(header, in); } } | LitecoinSerializer { public Message deserialize(InputStream in) throws ProtocolException, IOException { seekPastMagicBytes(in); LitecoinPacketHeader header = new LitecoinPacketHeader(in); return deserializePayload(header, in); } LitecoinSerializer(NetworkParameters params); LitecoinSerializer(NetworkParameters params, boolean parseLazy, boolean parseRetain); } | LitecoinSerializer { public Message deserialize(InputStream in) throws ProtocolException, IOException { seekPastMagicBytes(in); LitecoinPacketHeader header = new LitecoinPacketHeader(in); return deserializePayload(header, in); } LitecoinSerializer(NetworkParameters params); LitecoinSerializer(NetworkParameters params, boolean parseLazy, boolean parseRetain); void serialize(Message message, OutputStream out); Message deserialize(InputStream in); LitecoinPacketHeader deserializeHeader(InputStream in); Message deserializePayload(LitecoinPacketHeader header, InputStream in); void seekPastMagicBytes(InputStream in); boolean isParseLazyMode(); boolean isParseRetainMode(); } | LitecoinSerializer { public Message deserialize(InputStream in) throws ProtocolException, IOException { seekPastMagicBytes(in); LitecoinPacketHeader header = new LitecoinPacketHeader(in); return deserializePayload(header, in); } LitecoinSerializer(NetworkParameters params); LitecoinSerializer(NetworkParameters params, boolean parseLazy, boolean parseRetain); void serialize(Message message, OutputStream out); Message deserialize(InputStream in); LitecoinPacketHeader deserializeHeader(InputStream in); Message deserializePayload(LitecoinPacketHeader header, InputStream in); void seekPastMagicBytes(InputStream in); boolean isParseLazyMode(); boolean isParseRetainMode(); } |
@Test public void verifyMessage() throws Exception { String message = "hello"; String sigBase64 = "HxNZdo6ggZ41hd3mM3gfJRqOQPZYcO8z8qdX2BwmpbF11CaOQV+QiZGGQxaYOncKoNW61oRuSMMF8udfK54XqI8="; Address expectedAddress = new Address(NetworkParameters.prodNet(), "LNmLhahYB2gb3Hf3ZJsGaTyhG3HPDEPXfn"); ECKey key = ECKey.signedMessageToKey(message, sigBase64); Address gotAddress = key.toAddress(NetworkParameters.prodNet()); assertEquals(expectedAddress, gotAddress); } | public void verifyMessage(String message, String signatureBase64) throws SignatureException { ECKey key = ECKey.signedMessageToKey(message, signatureBase64); if (!Arrays.equals(key.getPubKey(), pub)) throw new SignatureException("Signature did not match for message"); } | ECKey implements Serializable { public void verifyMessage(String message, String signatureBase64) throws SignatureException { ECKey key = ECKey.signedMessageToKey(message, signatureBase64); if (!Arrays.equals(key.getPubKey(), pub)) throw new SignatureException("Signature did not match for message"); } } | ECKey implements Serializable { public void verifyMessage(String message, String signatureBase64) throws SignatureException { ECKey key = ECKey.signedMessageToKey(message, signatureBase64); if (!Arrays.equals(key.getPubKey(), pub)) throw new SignatureException("Signature did not match for message"); } ECKey(); ECKey(BigInteger privKey); ECKey(BigInteger privKey, BigInteger pubKey); ECKey(byte[] privKeyBytes, byte[] pubKey); ECKey(EncryptedPrivateKey encryptedPrivateKey, byte[] pubKey, KeyCrypter keyCrypter); ECKey(BigInteger privKey, byte[] pubKey, boolean compressed); private ECKey(BigInteger privKey, byte[] pubKey); } | ECKey implements Serializable { public void verifyMessage(String message, String signatureBase64) throws SignatureException { ECKey key = ECKey.signedMessageToKey(message, signatureBase64); if (!Arrays.equals(key.getPubKey(), pub)) throw new SignatureException("Signature did not match for message"); } ECKey(); ECKey(BigInteger privKey); ECKey(BigInteger privKey, BigInteger pubKey); ECKey(byte[] privKeyBytes, byte[] pubKey); ECKey(EncryptedPrivateKey encryptedPrivateKey, byte[] pubKey, KeyCrypter keyCrypter); ECKey(BigInteger privKey, byte[] pubKey, boolean compressed); private ECKey(BigInteger privKey, byte[] pubKey); static ECKey fromASN1(byte[] asn1privkey); byte[] toASN1(); static byte[] publicKeyFromPrivate(BigInteger privKey, boolean compressed); byte[] getPubKeyHash(); byte[] getPubKey(); boolean isCompressed(); String toString(); String toStringWithPrivate(); Address toAddress(NetworkParameters params); void clearPrivateKey(); ECDSASignature sign(Sha256Hash input); ECDSASignature sign(Sha256Hash input, KeyParameter aesKey); static boolean verify(byte[] data, byte[] signature, byte[] pub); boolean verify(byte[] data, byte[] signature); String signMessage(String message); String signMessage(String message, KeyParameter aesKey); static ECKey signedMessageToKey(String message, String signatureBase64); void verifyMessage(String message, String signatureBase64); static ECKey recoverFromSignature(int recId, ECDSASignature sig, Sha256Hash message, boolean compressed); byte[] getPrivKeyBytes(); DumpedPrivateKey getPrivateKeyEncoded(NetworkParameters params); long getCreationTimeSeconds(); void setCreationTimeSeconds(long newCreationTimeSeconds); @Override boolean equals(Object o); @Override int hashCode(); ECKey encrypt(KeyCrypter keyCrypter, KeyParameter aesKey); ECKey decrypt(KeyCrypter keyCrypter, KeyParameter aesKey); static boolean encryptionIsReversible(ECKey originalKey, ECKey encryptedKey, KeyCrypter keyCrypter, KeyParameter aesKey); boolean isEncrypted(); EncryptedPrivateKey getEncryptedPrivateKey(); KeyCrypter getKeyCrypter(); } | ECKey implements Serializable { public void verifyMessage(String message, String signatureBase64) throws SignatureException { ECKey key = ECKey.signedMessageToKey(message, signatureBase64); if (!Arrays.equals(key.getPubKey(), pub)) throw new SignatureException("Signature did not match for message"); } ECKey(); ECKey(BigInteger privKey); ECKey(BigInteger privKey, BigInteger pubKey); ECKey(byte[] privKeyBytes, byte[] pubKey); ECKey(EncryptedPrivateKey encryptedPrivateKey, byte[] pubKey, KeyCrypter keyCrypter); ECKey(BigInteger privKey, byte[] pubKey, boolean compressed); private ECKey(BigInteger privKey, byte[] pubKey); static ECKey fromASN1(byte[] asn1privkey); byte[] toASN1(); static byte[] publicKeyFromPrivate(BigInteger privKey, boolean compressed); byte[] getPubKeyHash(); byte[] getPubKey(); boolean isCompressed(); String toString(); String toStringWithPrivate(); Address toAddress(NetworkParameters params); void clearPrivateKey(); ECDSASignature sign(Sha256Hash input); ECDSASignature sign(Sha256Hash input, KeyParameter aesKey); static boolean verify(byte[] data, byte[] signature, byte[] pub); boolean verify(byte[] data, byte[] signature); String signMessage(String message); String signMessage(String message, KeyParameter aesKey); static ECKey signedMessageToKey(String message, String signatureBase64); void verifyMessage(String message, String signatureBase64); static ECKey recoverFromSignature(int recId, ECDSASignature sig, Sha256Hash message, boolean compressed); byte[] getPrivKeyBytes(); DumpedPrivateKey getPrivateKeyEncoded(NetworkParameters params); long getCreationTimeSeconds(); void setCreationTimeSeconds(long newCreationTimeSeconds); @Override boolean equals(Object o); @Override int hashCode(); ECKey encrypt(KeyCrypter keyCrypter, KeyParameter aesKey); ECKey decrypt(KeyCrypter keyCrypter, KeyParameter aesKey); static boolean encryptionIsReversible(ECKey originalKey, ECKey encryptedKey, KeyCrypter keyCrypter, KeyParameter aesKey); boolean isEncrypted(); EncryptedPrivateKey getEncryptedPrivateKey(); KeyCrypter getKeyCrypter(); } |
@Test public void testEncryptionIsReversible() throws Exception { ECKey originalUnencryptedKey = new ECKey(); EncryptedPrivateKey encryptedPrivateKey = keyCrypter.encrypt(originalUnencryptedKey.getPrivKeyBytes(), keyCrypter.deriveKey(PASSWORD1)); ECKey encryptedKey = new ECKey(encryptedPrivateKey, originalUnencryptedKey.getPubKey(), keyCrypter); assertTrue("Key not encrypted at start", encryptedKey.isEncrypted()); assertTrue("Key encryption is not reversible but it should be", ECKey.encryptionIsReversible(originalUnencryptedKey, encryptedKey, keyCrypter, keyCrypter.deriveKey(PASSWORD1))); assertTrue("Key encryption is reversible with wrong password", !ECKey.encryptionIsReversible(originalUnencryptedKey, encryptedKey, keyCrypter, keyCrypter.deriveKey(WRONG_PASSWORD))); byte[] goodEncryptedPrivateKeyBytes = encryptedPrivateKey.getEncryptedBytes(); byte[] badEncryptedPrivateKeyBytes = goodEncryptedPrivateKeyBytes; badEncryptedPrivateKeyBytes[16] = (byte) (badEncryptedPrivateKeyBytes[12] ^ new Byte("12").byteValue()); encryptedPrivateKey.setEncryptedPrivateBytes(badEncryptedPrivateKeyBytes); ECKey badEncryptedKey = new ECKey(encryptedPrivateKey, originalUnencryptedKey.getPubKey(), keyCrypter); assertTrue("Key encryption is reversible with faulty encrypted bytes", !ECKey.encryptionIsReversible(originalUnencryptedKey, badEncryptedKey, keyCrypter, keyCrypter.deriveKey(PASSWORD1))); } | public static boolean encryptionIsReversible(ECKey originalKey, ECKey encryptedKey, KeyCrypter keyCrypter, KeyParameter aesKey) { String genericErrorText = "The check that encryption could be reversed failed for key " + originalKey.toString() + ". "; try { ECKey rebornUnencryptedKey = encryptedKey.decrypt(keyCrypter, aesKey); if (rebornUnencryptedKey == null) { log.error(genericErrorText + "The test decrypted key was missing."); return false; } byte[] originalPrivateKeyBytes = originalKey.getPrivKeyBytes(); if (originalPrivateKeyBytes != null) { if (rebornUnencryptedKey.getPrivKeyBytes() == null) { log.error(genericErrorText + "The test decrypted key was missing."); return false; } else { if (originalPrivateKeyBytes.length != rebornUnencryptedKey.getPrivKeyBytes().length) { log.error(genericErrorText + "The test decrypted private key was a different length to the original."); return false; } else { for (int i = 0; i < originalPrivateKeyBytes.length; i++) { if (originalPrivateKeyBytes[i] != rebornUnencryptedKey.getPrivKeyBytes()[i]) { log.error(genericErrorText + "Byte " + i + " of the private key did not match the original."); return false; } } } } } } catch (KeyCrypterException kce) { log.error(kce.getMessage()); return false; } return true; } | ECKey implements Serializable { public static boolean encryptionIsReversible(ECKey originalKey, ECKey encryptedKey, KeyCrypter keyCrypter, KeyParameter aesKey) { String genericErrorText = "The check that encryption could be reversed failed for key " + originalKey.toString() + ". "; try { ECKey rebornUnencryptedKey = encryptedKey.decrypt(keyCrypter, aesKey); if (rebornUnencryptedKey == null) { log.error(genericErrorText + "The test decrypted key was missing."); return false; } byte[] originalPrivateKeyBytes = originalKey.getPrivKeyBytes(); if (originalPrivateKeyBytes != null) { if (rebornUnencryptedKey.getPrivKeyBytes() == null) { log.error(genericErrorText + "The test decrypted key was missing."); return false; } else { if (originalPrivateKeyBytes.length != rebornUnencryptedKey.getPrivKeyBytes().length) { log.error(genericErrorText + "The test decrypted private key was a different length to the original."); return false; } else { for (int i = 0; i < originalPrivateKeyBytes.length; i++) { if (originalPrivateKeyBytes[i] != rebornUnencryptedKey.getPrivKeyBytes()[i]) { log.error(genericErrorText + "Byte " + i + " of the private key did not match the original."); return false; } } } } } } catch (KeyCrypterException kce) { log.error(kce.getMessage()); return false; } return true; } } | ECKey implements Serializable { public static boolean encryptionIsReversible(ECKey originalKey, ECKey encryptedKey, KeyCrypter keyCrypter, KeyParameter aesKey) { String genericErrorText = "The check that encryption could be reversed failed for key " + originalKey.toString() + ". "; try { ECKey rebornUnencryptedKey = encryptedKey.decrypt(keyCrypter, aesKey); if (rebornUnencryptedKey == null) { log.error(genericErrorText + "The test decrypted key was missing."); return false; } byte[] originalPrivateKeyBytes = originalKey.getPrivKeyBytes(); if (originalPrivateKeyBytes != null) { if (rebornUnencryptedKey.getPrivKeyBytes() == null) { log.error(genericErrorText + "The test decrypted key was missing."); return false; } else { if (originalPrivateKeyBytes.length != rebornUnencryptedKey.getPrivKeyBytes().length) { log.error(genericErrorText + "The test decrypted private key was a different length to the original."); return false; } else { for (int i = 0; i < originalPrivateKeyBytes.length; i++) { if (originalPrivateKeyBytes[i] != rebornUnencryptedKey.getPrivKeyBytes()[i]) { log.error(genericErrorText + "Byte " + i + " of the private key did not match the original."); return false; } } } } } } catch (KeyCrypterException kce) { log.error(kce.getMessage()); return false; } return true; } ECKey(); ECKey(BigInteger privKey); ECKey(BigInteger privKey, BigInteger pubKey); ECKey(byte[] privKeyBytes, byte[] pubKey); ECKey(EncryptedPrivateKey encryptedPrivateKey, byte[] pubKey, KeyCrypter keyCrypter); ECKey(BigInteger privKey, byte[] pubKey, boolean compressed); private ECKey(BigInteger privKey, byte[] pubKey); } | ECKey implements Serializable { public static boolean encryptionIsReversible(ECKey originalKey, ECKey encryptedKey, KeyCrypter keyCrypter, KeyParameter aesKey) { String genericErrorText = "The check that encryption could be reversed failed for key " + originalKey.toString() + ". "; try { ECKey rebornUnencryptedKey = encryptedKey.decrypt(keyCrypter, aesKey); if (rebornUnencryptedKey == null) { log.error(genericErrorText + "The test decrypted key was missing."); return false; } byte[] originalPrivateKeyBytes = originalKey.getPrivKeyBytes(); if (originalPrivateKeyBytes != null) { if (rebornUnencryptedKey.getPrivKeyBytes() == null) { log.error(genericErrorText + "The test decrypted key was missing."); return false; } else { if (originalPrivateKeyBytes.length != rebornUnencryptedKey.getPrivKeyBytes().length) { log.error(genericErrorText + "The test decrypted private key was a different length to the original."); return false; } else { for (int i = 0; i < originalPrivateKeyBytes.length; i++) { if (originalPrivateKeyBytes[i] != rebornUnencryptedKey.getPrivKeyBytes()[i]) { log.error(genericErrorText + "Byte " + i + " of the private key did not match the original."); return false; } } } } } } catch (KeyCrypterException kce) { log.error(kce.getMessage()); return false; } return true; } ECKey(); ECKey(BigInteger privKey); ECKey(BigInteger privKey, BigInteger pubKey); ECKey(byte[] privKeyBytes, byte[] pubKey); ECKey(EncryptedPrivateKey encryptedPrivateKey, byte[] pubKey, KeyCrypter keyCrypter); ECKey(BigInteger privKey, byte[] pubKey, boolean compressed); private ECKey(BigInteger privKey, byte[] pubKey); static ECKey fromASN1(byte[] asn1privkey); byte[] toASN1(); static byte[] publicKeyFromPrivate(BigInteger privKey, boolean compressed); byte[] getPubKeyHash(); byte[] getPubKey(); boolean isCompressed(); String toString(); String toStringWithPrivate(); Address toAddress(NetworkParameters params); void clearPrivateKey(); ECDSASignature sign(Sha256Hash input); ECDSASignature sign(Sha256Hash input, KeyParameter aesKey); static boolean verify(byte[] data, byte[] signature, byte[] pub); boolean verify(byte[] data, byte[] signature); String signMessage(String message); String signMessage(String message, KeyParameter aesKey); static ECKey signedMessageToKey(String message, String signatureBase64); void verifyMessage(String message, String signatureBase64); static ECKey recoverFromSignature(int recId, ECDSASignature sig, Sha256Hash message, boolean compressed); byte[] getPrivKeyBytes(); DumpedPrivateKey getPrivateKeyEncoded(NetworkParameters params); long getCreationTimeSeconds(); void setCreationTimeSeconds(long newCreationTimeSeconds); @Override boolean equals(Object o); @Override int hashCode(); ECKey encrypt(KeyCrypter keyCrypter, KeyParameter aesKey); ECKey decrypt(KeyCrypter keyCrypter, KeyParameter aesKey); static boolean encryptionIsReversible(ECKey originalKey, ECKey encryptedKey, KeyCrypter keyCrypter, KeyParameter aesKey); boolean isEncrypted(); EncryptedPrivateKey getEncryptedPrivateKey(); KeyCrypter getKeyCrypter(); } | ECKey implements Serializable { public static boolean encryptionIsReversible(ECKey originalKey, ECKey encryptedKey, KeyCrypter keyCrypter, KeyParameter aesKey) { String genericErrorText = "The check that encryption could be reversed failed for key " + originalKey.toString() + ". "; try { ECKey rebornUnencryptedKey = encryptedKey.decrypt(keyCrypter, aesKey); if (rebornUnencryptedKey == null) { log.error(genericErrorText + "The test decrypted key was missing."); return false; } byte[] originalPrivateKeyBytes = originalKey.getPrivKeyBytes(); if (originalPrivateKeyBytes != null) { if (rebornUnencryptedKey.getPrivKeyBytes() == null) { log.error(genericErrorText + "The test decrypted key was missing."); return false; } else { if (originalPrivateKeyBytes.length != rebornUnencryptedKey.getPrivKeyBytes().length) { log.error(genericErrorText + "The test decrypted private key was a different length to the original."); return false; } else { for (int i = 0; i < originalPrivateKeyBytes.length; i++) { if (originalPrivateKeyBytes[i] != rebornUnencryptedKey.getPrivKeyBytes()[i]) { log.error(genericErrorText + "Byte " + i + " of the private key did not match the original."); return false; } } } } } } catch (KeyCrypterException kce) { log.error(kce.getMessage()); return false; } return true; } ECKey(); ECKey(BigInteger privKey); ECKey(BigInteger privKey, BigInteger pubKey); ECKey(byte[] privKeyBytes, byte[] pubKey); ECKey(EncryptedPrivateKey encryptedPrivateKey, byte[] pubKey, KeyCrypter keyCrypter); ECKey(BigInteger privKey, byte[] pubKey, boolean compressed); private ECKey(BigInteger privKey, byte[] pubKey); static ECKey fromASN1(byte[] asn1privkey); byte[] toASN1(); static byte[] publicKeyFromPrivate(BigInteger privKey, boolean compressed); byte[] getPubKeyHash(); byte[] getPubKey(); boolean isCompressed(); String toString(); String toStringWithPrivate(); Address toAddress(NetworkParameters params); void clearPrivateKey(); ECDSASignature sign(Sha256Hash input); ECDSASignature sign(Sha256Hash input, KeyParameter aesKey); static boolean verify(byte[] data, byte[] signature, byte[] pub); boolean verify(byte[] data, byte[] signature); String signMessage(String message); String signMessage(String message, KeyParameter aesKey); static ECKey signedMessageToKey(String message, String signatureBase64); void verifyMessage(String message, String signatureBase64); static ECKey recoverFromSignature(int recId, ECDSASignature sig, Sha256Hash message, boolean compressed); byte[] getPrivKeyBytes(); DumpedPrivateKey getPrivateKeyEncoded(NetworkParameters params); long getCreationTimeSeconds(); void setCreationTimeSeconds(long newCreationTimeSeconds); @Override boolean equals(Object o); @Override int hashCode(); ECKey encrypt(KeyCrypter keyCrypter, KeyParameter aesKey); ECKey decrypt(KeyCrypter keyCrypter, KeyParameter aesKey); static boolean encryptionIsReversible(ECKey originalKey, ECKey encryptedKey, KeyCrypter keyCrypter, KeyParameter aesKey); boolean isEncrypted(); EncryptedPrivateKey getEncryptedPrivateKey(); KeyCrypter getKeyCrypter(); } |
@Test public void testToString() throws Exception { ECKey key = new ECKey(BigInteger.TEN); assertEquals("pub:04a0434d9e47f3c86235477c7b1ae6ae5d3442d49b1943c2b752a68e2a47e247c7893aba425419bc27a3b6c7e693a24c696f794c2ed877a1593cbee53b037368d7", key.toString()); assertEquals("pub:04a0434d9e47f3c86235477c7b1ae6ae5d3442d49b1943c2b752a68e2a47e247c7893aba425419bc27a3b6c7e693a24c696f794c2ed877a1593cbee53b037368d7 priv:0a", key.toStringWithPrivate()); } | public String toString() { StringBuilder b = new StringBuilder(); b.append("pub:").append(Utils.bytesToHexString(pub)); if (creationTimeSeconds != 0) { b.append(" timestamp:").append(creationTimeSeconds); } if (isEncrypted()) { b.append(" encrypted"); } return b.toString(); } | ECKey implements Serializable { public String toString() { StringBuilder b = new StringBuilder(); b.append("pub:").append(Utils.bytesToHexString(pub)); if (creationTimeSeconds != 0) { b.append(" timestamp:").append(creationTimeSeconds); } if (isEncrypted()) { b.append(" encrypted"); } return b.toString(); } } | ECKey implements Serializable { public String toString() { StringBuilder b = new StringBuilder(); b.append("pub:").append(Utils.bytesToHexString(pub)); if (creationTimeSeconds != 0) { b.append(" timestamp:").append(creationTimeSeconds); } if (isEncrypted()) { b.append(" encrypted"); } return b.toString(); } ECKey(); ECKey(BigInteger privKey); ECKey(BigInteger privKey, BigInteger pubKey); ECKey(byte[] privKeyBytes, byte[] pubKey); ECKey(EncryptedPrivateKey encryptedPrivateKey, byte[] pubKey, KeyCrypter keyCrypter); ECKey(BigInteger privKey, byte[] pubKey, boolean compressed); private ECKey(BigInteger privKey, byte[] pubKey); } | ECKey implements Serializable { public String toString() { StringBuilder b = new StringBuilder(); b.append("pub:").append(Utils.bytesToHexString(pub)); if (creationTimeSeconds != 0) { b.append(" timestamp:").append(creationTimeSeconds); } if (isEncrypted()) { b.append(" encrypted"); } return b.toString(); } ECKey(); ECKey(BigInteger privKey); ECKey(BigInteger privKey, BigInteger pubKey); ECKey(byte[] privKeyBytes, byte[] pubKey); ECKey(EncryptedPrivateKey encryptedPrivateKey, byte[] pubKey, KeyCrypter keyCrypter); ECKey(BigInteger privKey, byte[] pubKey, boolean compressed); private ECKey(BigInteger privKey, byte[] pubKey); static ECKey fromASN1(byte[] asn1privkey); byte[] toASN1(); static byte[] publicKeyFromPrivate(BigInteger privKey, boolean compressed); byte[] getPubKeyHash(); byte[] getPubKey(); boolean isCompressed(); String toString(); String toStringWithPrivate(); Address toAddress(NetworkParameters params); void clearPrivateKey(); ECDSASignature sign(Sha256Hash input); ECDSASignature sign(Sha256Hash input, KeyParameter aesKey); static boolean verify(byte[] data, byte[] signature, byte[] pub); boolean verify(byte[] data, byte[] signature); String signMessage(String message); String signMessage(String message, KeyParameter aesKey); static ECKey signedMessageToKey(String message, String signatureBase64); void verifyMessage(String message, String signatureBase64); static ECKey recoverFromSignature(int recId, ECDSASignature sig, Sha256Hash message, boolean compressed); byte[] getPrivKeyBytes(); DumpedPrivateKey getPrivateKeyEncoded(NetworkParameters params); long getCreationTimeSeconds(); void setCreationTimeSeconds(long newCreationTimeSeconds); @Override boolean equals(Object o); @Override int hashCode(); ECKey encrypt(KeyCrypter keyCrypter, KeyParameter aesKey); ECKey decrypt(KeyCrypter keyCrypter, KeyParameter aesKey); static boolean encryptionIsReversible(ECKey originalKey, ECKey encryptedKey, KeyCrypter keyCrypter, KeyParameter aesKey); boolean isEncrypted(); EncryptedPrivateKey getEncryptedPrivateKey(); KeyCrypter getKeyCrypter(); } | ECKey implements Serializable { public String toString() { StringBuilder b = new StringBuilder(); b.append("pub:").append(Utils.bytesToHexString(pub)); if (creationTimeSeconds != 0) { b.append(" timestamp:").append(creationTimeSeconds); } if (isEncrypted()) { b.append(" encrypted"); } return b.toString(); } ECKey(); ECKey(BigInteger privKey); ECKey(BigInteger privKey, BigInteger pubKey); ECKey(byte[] privKeyBytes, byte[] pubKey); ECKey(EncryptedPrivateKey encryptedPrivateKey, byte[] pubKey, KeyCrypter keyCrypter); ECKey(BigInteger privKey, byte[] pubKey, boolean compressed); private ECKey(BigInteger privKey, byte[] pubKey); static ECKey fromASN1(byte[] asn1privkey); byte[] toASN1(); static byte[] publicKeyFromPrivate(BigInteger privKey, boolean compressed); byte[] getPubKeyHash(); byte[] getPubKey(); boolean isCompressed(); String toString(); String toStringWithPrivate(); Address toAddress(NetworkParameters params); void clearPrivateKey(); ECDSASignature sign(Sha256Hash input); ECDSASignature sign(Sha256Hash input, KeyParameter aesKey); static boolean verify(byte[] data, byte[] signature, byte[] pub); boolean verify(byte[] data, byte[] signature); String signMessage(String message); String signMessage(String message, KeyParameter aesKey); static ECKey signedMessageToKey(String message, String signatureBase64); void verifyMessage(String message, String signatureBase64); static ECKey recoverFromSignature(int recId, ECDSASignature sig, Sha256Hash message, boolean compressed); byte[] getPrivKeyBytes(); DumpedPrivateKey getPrivateKeyEncoded(NetworkParameters params); long getCreationTimeSeconds(); void setCreationTimeSeconds(long newCreationTimeSeconds); @Override boolean equals(Object o); @Override int hashCode(); ECKey encrypt(KeyCrypter keyCrypter, KeyParameter aesKey); ECKey decrypt(KeyCrypter keyCrypter, KeyParameter aesKey); static boolean encryptionIsReversible(ECKey originalKey, ECKey encryptedKey, KeyCrypter keyCrypter, KeyParameter aesKey); boolean isEncrypted(); EncryptedPrivateKey getEncryptedPrivateKey(); KeyCrypter getKeyCrypter(); } |
@Test public void testToNanoCoins() { assertEquals(CENT, toNanoCoins("0.01")); assertEquals(CENT, toNanoCoins("1E-2")); assertEquals(COIN.add(Utils.CENT), toNanoCoins("1.01")); try { toNanoCoins("2E-20"); org.junit.Assert.fail("should not have accepted fractional nanocoins"); } catch (ArithmeticException e) { } assertEquals(CENT, toNanoCoins(0, 1)); assertEquals(COIN.subtract(CENT), toNanoCoins(1, -1)); assertEquals(COIN.negate(), toNanoCoins(-1, 0)); assertEquals(COIN.negate(), toNanoCoins("-1")); } | public static BigInteger toNanoCoins(int coins, int cents) { checkArgument(cents < 100); BigInteger bi = BigInteger.valueOf(coins).multiply(COIN); bi = bi.add(BigInteger.valueOf(cents).multiply(CENT)); return bi; } | Utils { public static BigInteger toNanoCoins(int coins, int cents) { checkArgument(cents < 100); BigInteger bi = BigInteger.valueOf(coins).multiply(COIN); bi = bi.add(BigInteger.valueOf(cents).multiply(CENT)); return bi; } } | Utils { public static BigInteger toNanoCoins(int coins, int cents) { checkArgument(cents < 100); BigInteger bi = BigInteger.valueOf(coins).multiply(COIN); bi = bi.add(BigInteger.valueOf(cents).multiply(CENT)); return bi; } } | Utils { public static BigInteger toNanoCoins(int coins, int cents) { checkArgument(cents < 100); BigInteger bi = BigInteger.valueOf(coins).multiply(COIN); bi = bi.add(BigInteger.valueOf(cents).multiply(CENT)); return bi; } static BigInteger toNanoCoins(int coins, int cents); static byte[] bigIntegerToBytes(BigInteger b, int numBytes); static BigInteger toNanoCoins(String coins); static void uint32ToByteArrayBE(long val, byte[] out, int offset); static void uint32ToByteArrayLE(long val, byte[] out, int offset); static void uint32ToByteStreamLE(long val, OutputStream stream); static void int64ToByteStreamLE(long val, OutputStream stream); static void uint64ToByteStreamLE(BigInteger val, OutputStream stream); static byte[] doubleDigest(byte[] input); static byte[] scryptDigest(byte[] input); static byte[] doubleDigest(byte[] input, int offset, int length); static byte[] singleDigest(byte[] input, int offset, int length); static byte[] doubleDigestTwoBuffers(byte[] input1, int offset1, int length1,
byte[] input2, int offset2, int length2); static boolean isLessThanUnsigned(long n1, long n2); static String bytesToHexString(byte[] bytes); static byte[] reverseBytes(byte[] bytes); static byte[] reverseDwordBytes(byte[] bytes, int trimLength); static long readUint32(byte[] bytes, int offset); static long readInt64(byte[] bytes, int offset); static long readUint32BE(byte[] bytes, int offset); static int readUint16BE(byte[] bytes, int offset); static byte[] sha256hash160(byte[] input); static String litecoinValueToFriendlyString(BigInteger value); static String litecoinValueToPlainString(BigInteger value); static BigInteger decodeCompactBits(long compact); static Date rollMockClock(int seconds); static Date now(); static byte[] copyOf(byte[] in, int length); static byte[] parseAsHexOrBase58(String data); static boolean isWindows(); static byte[] formatMessageForSigning(String message); static boolean checkBitLE(byte[] data, int index); static void setBitLE(byte[] data, int index); } | Utils { public static BigInteger toNanoCoins(int coins, int cents) { checkArgument(cents < 100); BigInteger bi = BigInteger.valueOf(coins).multiply(COIN); bi = bi.add(BigInteger.valueOf(cents).multiply(CENT)); return bi; } static BigInteger toNanoCoins(int coins, int cents); static byte[] bigIntegerToBytes(BigInteger b, int numBytes); static BigInteger toNanoCoins(String coins); static void uint32ToByteArrayBE(long val, byte[] out, int offset); static void uint32ToByteArrayLE(long val, byte[] out, int offset); static void uint32ToByteStreamLE(long val, OutputStream stream); static void int64ToByteStreamLE(long val, OutputStream stream); static void uint64ToByteStreamLE(BigInteger val, OutputStream stream); static byte[] doubleDigest(byte[] input); static byte[] scryptDigest(byte[] input); static byte[] doubleDigest(byte[] input, int offset, int length); static byte[] singleDigest(byte[] input, int offset, int length); static byte[] doubleDigestTwoBuffers(byte[] input1, int offset1, int length1,
byte[] input2, int offset2, int length2); static boolean isLessThanUnsigned(long n1, long n2); static String bytesToHexString(byte[] bytes); static byte[] reverseBytes(byte[] bytes); static byte[] reverseDwordBytes(byte[] bytes, int trimLength); static long readUint32(byte[] bytes, int offset); static long readInt64(byte[] bytes, int offset); static long readUint32BE(byte[] bytes, int offset); static int readUint16BE(byte[] bytes, int offset); static byte[] sha256hash160(byte[] input); static String litecoinValueToFriendlyString(BigInteger value); static String litecoinValueToPlainString(BigInteger value); static BigInteger decodeCompactBits(long compact); static Date rollMockClock(int seconds); static Date now(); static byte[] copyOf(byte[] in, int length); static byte[] parseAsHexOrBase58(String data); static boolean isWindows(); static byte[] formatMessageForSigning(String message); static boolean checkBitLE(byte[] data, int index); static void setBitLE(byte[] data, int index); static final String LITECOIN_SIGNED_MESSAGE_HEADER; static final BigInteger COIN; static final BigInteger CENT; static volatile Date mockTime; } |
@Test public void testLitecoinValueToPlainString() { try { litecoinValueToPlainString(null); org.junit.Assert.fail("Expecting IllegalArgumentException"); } catch (IllegalArgumentException e) { assertTrue(e.getMessage().contains("Value cannot be null")); } assertEquals("0.0015", litecoinValueToPlainString(BigInteger.valueOf(150000))); assertEquals("1.23", litecoinValueToPlainString(toNanoCoins("1.23"))); assertEquals("-1.23", litecoinValueToPlainString(toNanoCoins("-1.23"))); assertEquals("0.1", litecoinValueToPlainString(toNanoCoins("0.1"))); assertEquals("1.1", litecoinValueToPlainString(toNanoCoins("1.1"))); assertEquals("21.12", litecoinValueToPlainString(toNanoCoins("21.12"))); assertEquals("321.123", litecoinValueToPlainString(toNanoCoins("321.123"))); assertEquals("4321.1234", litecoinValueToPlainString(toNanoCoins("4321.1234"))); assertEquals("54321.12345", litecoinValueToPlainString(toNanoCoins("54321.12345"))); assertEquals("654321.123456", litecoinValueToPlainString(toNanoCoins("654321.123456"))); assertEquals("7654321.1234567", litecoinValueToPlainString(toNanoCoins("7654321.1234567"))); assertEquals("87654321.12345678", litecoinValueToPlainString(toNanoCoins("87654321.12345678"))); assertEquals("1", litecoinValueToPlainString(toNanoCoins("1.0"))); assertEquals("2", litecoinValueToPlainString(toNanoCoins("2.00"))); assertEquals("3", litecoinValueToPlainString(toNanoCoins("3.000"))); assertEquals("4", litecoinValueToPlainString(toNanoCoins("4.0000"))); assertEquals("5", litecoinValueToPlainString(toNanoCoins("5.00000"))); assertEquals("6", litecoinValueToPlainString(toNanoCoins("6.000000"))); assertEquals("7", litecoinValueToPlainString(toNanoCoins("7.0000000"))); assertEquals("8", litecoinValueToPlainString(toNanoCoins("8.00000000"))); } | public static String litecoinValueToPlainString(BigInteger value) { if (value == null) { throw new IllegalArgumentException("Value cannot be null"); } BigDecimal valueInBTC = new BigDecimal(value).divide(new BigDecimal(Utils.COIN)); return valueInBTC.toPlainString(); } | Utils { public static String litecoinValueToPlainString(BigInteger value) { if (value == null) { throw new IllegalArgumentException("Value cannot be null"); } BigDecimal valueInBTC = new BigDecimal(value).divide(new BigDecimal(Utils.COIN)); return valueInBTC.toPlainString(); } } | Utils { public static String litecoinValueToPlainString(BigInteger value) { if (value == null) { throw new IllegalArgumentException("Value cannot be null"); } BigDecimal valueInBTC = new BigDecimal(value).divide(new BigDecimal(Utils.COIN)); return valueInBTC.toPlainString(); } } | Utils { public static String litecoinValueToPlainString(BigInteger value) { if (value == null) { throw new IllegalArgumentException("Value cannot be null"); } BigDecimal valueInBTC = new BigDecimal(value).divide(new BigDecimal(Utils.COIN)); return valueInBTC.toPlainString(); } static BigInteger toNanoCoins(int coins, int cents); static byte[] bigIntegerToBytes(BigInteger b, int numBytes); static BigInteger toNanoCoins(String coins); static void uint32ToByteArrayBE(long val, byte[] out, int offset); static void uint32ToByteArrayLE(long val, byte[] out, int offset); static void uint32ToByteStreamLE(long val, OutputStream stream); static void int64ToByteStreamLE(long val, OutputStream stream); static void uint64ToByteStreamLE(BigInteger val, OutputStream stream); static byte[] doubleDigest(byte[] input); static byte[] scryptDigest(byte[] input); static byte[] doubleDigest(byte[] input, int offset, int length); static byte[] singleDigest(byte[] input, int offset, int length); static byte[] doubleDigestTwoBuffers(byte[] input1, int offset1, int length1,
byte[] input2, int offset2, int length2); static boolean isLessThanUnsigned(long n1, long n2); static String bytesToHexString(byte[] bytes); static byte[] reverseBytes(byte[] bytes); static byte[] reverseDwordBytes(byte[] bytes, int trimLength); static long readUint32(byte[] bytes, int offset); static long readInt64(byte[] bytes, int offset); static long readUint32BE(byte[] bytes, int offset); static int readUint16BE(byte[] bytes, int offset); static byte[] sha256hash160(byte[] input); static String litecoinValueToFriendlyString(BigInteger value); static String litecoinValueToPlainString(BigInteger value); static BigInteger decodeCompactBits(long compact); static Date rollMockClock(int seconds); static Date now(); static byte[] copyOf(byte[] in, int length); static byte[] parseAsHexOrBase58(String data); static boolean isWindows(); static byte[] formatMessageForSigning(String message); static boolean checkBitLE(byte[] data, int index); static void setBitLE(byte[] data, int index); } | Utils { public static String litecoinValueToPlainString(BigInteger value) { if (value == null) { throw new IllegalArgumentException("Value cannot be null"); } BigDecimal valueInBTC = new BigDecimal(value).divide(new BigDecimal(Utils.COIN)); return valueInBTC.toPlainString(); } static BigInteger toNanoCoins(int coins, int cents); static byte[] bigIntegerToBytes(BigInteger b, int numBytes); static BigInteger toNanoCoins(String coins); static void uint32ToByteArrayBE(long val, byte[] out, int offset); static void uint32ToByteArrayLE(long val, byte[] out, int offset); static void uint32ToByteStreamLE(long val, OutputStream stream); static void int64ToByteStreamLE(long val, OutputStream stream); static void uint64ToByteStreamLE(BigInteger val, OutputStream stream); static byte[] doubleDigest(byte[] input); static byte[] scryptDigest(byte[] input); static byte[] doubleDigest(byte[] input, int offset, int length); static byte[] singleDigest(byte[] input, int offset, int length); static byte[] doubleDigestTwoBuffers(byte[] input1, int offset1, int length1,
byte[] input2, int offset2, int length2); static boolean isLessThanUnsigned(long n1, long n2); static String bytesToHexString(byte[] bytes); static byte[] reverseBytes(byte[] bytes); static byte[] reverseDwordBytes(byte[] bytes, int trimLength); static long readUint32(byte[] bytes, int offset); static long readInt64(byte[] bytes, int offset); static long readUint32BE(byte[] bytes, int offset); static int readUint16BE(byte[] bytes, int offset); static byte[] sha256hash160(byte[] input); static String litecoinValueToFriendlyString(BigInteger value); static String litecoinValueToPlainString(BigInteger value); static BigInteger decodeCompactBits(long compact); static Date rollMockClock(int seconds); static Date now(); static byte[] copyOf(byte[] in, int length); static byte[] parseAsHexOrBase58(String data); static boolean isWindows(); static byte[] formatMessageForSigning(String message); static boolean checkBitLE(byte[] data, int index); static void setBitLE(byte[] data, int index); static final String LITECOIN_SIGNED_MESSAGE_HEADER; static final BigInteger COIN; static final BigInteger CENT; static volatile Date mockTime; } |
@Test public void testReverseBytes() { Assert.assertArrayEquals(new byte[] {1,2,3,4,5}, Utils.reverseBytes(new byte[] {5,4,3,2,1})); } | public static byte[] reverseBytes(byte[] bytes) { byte[] buf = new byte[bytes.length]; for (int i = 0; i < bytes.length; i++) buf[i] = bytes[bytes.length - 1 - i]; return buf; } | Utils { public static byte[] reverseBytes(byte[] bytes) { byte[] buf = new byte[bytes.length]; for (int i = 0; i < bytes.length; i++) buf[i] = bytes[bytes.length - 1 - i]; return buf; } } | Utils { public static byte[] reverseBytes(byte[] bytes) { byte[] buf = new byte[bytes.length]; for (int i = 0; i < bytes.length; i++) buf[i] = bytes[bytes.length - 1 - i]; return buf; } } | Utils { public static byte[] reverseBytes(byte[] bytes) { byte[] buf = new byte[bytes.length]; for (int i = 0; i < bytes.length; i++) buf[i] = bytes[bytes.length - 1 - i]; return buf; } static BigInteger toNanoCoins(int coins, int cents); static byte[] bigIntegerToBytes(BigInteger b, int numBytes); static BigInteger toNanoCoins(String coins); static void uint32ToByteArrayBE(long val, byte[] out, int offset); static void uint32ToByteArrayLE(long val, byte[] out, int offset); static void uint32ToByteStreamLE(long val, OutputStream stream); static void int64ToByteStreamLE(long val, OutputStream stream); static void uint64ToByteStreamLE(BigInteger val, OutputStream stream); static byte[] doubleDigest(byte[] input); static byte[] scryptDigest(byte[] input); static byte[] doubleDigest(byte[] input, int offset, int length); static byte[] singleDigest(byte[] input, int offset, int length); static byte[] doubleDigestTwoBuffers(byte[] input1, int offset1, int length1,
byte[] input2, int offset2, int length2); static boolean isLessThanUnsigned(long n1, long n2); static String bytesToHexString(byte[] bytes); static byte[] reverseBytes(byte[] bytes); static byte[] reverseDwordBytes(byte[] bytes, int trimLength); static long readUint32(byte[] bytes, int offset); static long readInt64(byte[] bytes, int offset); static long readUint32BE(byte[] bytes, int offset); static int readUint16BE(byte[] bytes, int offset); static byte[] sha256hash160(byte[] input); static String litecoinValueToFriendlyString(BigInteger value); static String litecoinValueToPlainString(BigInteger value); static BigInteger decodeCompactBits(long compact); static Date rollMockClock(int seconds); static Date now(); static byte[] copyOf(byte[] in, int length); static byte[] parseAsHexOrBase58(String data); static boolean isWindows(); static byte[] formatMessageForSigning(String message); static boolean checkBitLE(byte[] data, int index); static void setBitLE(byte[] data, int index); } | Utils { public static byte[] reverseBytes(byte[] bytes) { byte[] buf = new byte[bytes.length]; for (int i = 0; i < bytes.length; i++) buf[i] = bytes[bytes.length - 1 - i]; return buf; } static BigInteger toNanoCoins(int coins, int cents); static byte[] bigIntegerToBytes(BigInteger b, int numBytes); static BigInteger toNanoCoins(String coins); static void uint32ToByteArrayBE(long val, byte[] out, int offset); static void uint32ToByteArrayLE(long val, byte[] out, int offset); static void uint32ToByteStreamLE(long val, OutputStream stream); static void int64ToByteStreamLE(long val, OutputStream stream); static void uint64ToByteStreamLE(BigInteger val, OutputStream stream); static byte[] doubleDigest(byte[] input); static byte[] scryptDigest(byte[] input); static byte[] doubleDigest(byte[] input, int offset, int length); static byte[] singleDigest(byte[] input, int offset, int length); static byte[] doubleDigestTwoBuffers(byte[] input1, int offset1, int length1,
byte[] input2, int offset2, int length2); static boolean isLessThanUnsigned(long n1, long n2); static String bytesToHexString(byte[] bytes); static byte[] reverseBytes(byte[] bytes); static byte[] reverseDwordBytes(byte[] bytes, int trimLength); static long readUint32(byte[] bytes, int offset); static long readInt64(byte[] bytes, int offset); static long readUint32BE(byte[] bytes, int offset); static int readUint16BE(byte[] bytes, int offset); static byte[] sha256hash160(byte[] input); static String litecoinValueToFriendlyString(BigInteger value); static String litecoinValueToPlainString(BigInteger value); static BigInteger decodeCompactBits(long compact); static Date rollMockClock(int seconds); static Date now(); static byte[] copyOf(byte[] in, int length); static byte[] parseAsHexOrBase58(String data); static boolean isWindows(); static byte[] formatMessageForSigning(String message); static boolean checkBitLE(byte[] data, int index); static void setBitLE(byte[] data, int index); static final String LITECOIN_SIGNED_MESSAGE_HEADER; static final BigInteger COIN; static final BigInteger CENT; static volatile Date mockTime; } |
@Test public void testReverseDwordBytes() { Assert.assertArrayEquals(new byte[] {1,2,3,4,5,6,7,8}, Utils.reverseDwordBytes(new byte[] {4,3,2,1,8,7,6,5}, -1)); Assert.assertArrayEquals(new byte[] {1,2,3,4}, Utils.reverseDwordBytes(new byte[] {4,3,2,1,8,7,6,5}, 4)); Assert.assertArrayEquals(new byte[0], Utils.reverseDwordBytes(new byte[] {4,3,2,1,8,7,6,5}, 0)); Assert.assertArrayEquals(new byte[0], Utils.reverseDwordBytes(new byte[0], 0)); } | public static byte[] reverseDwordBytes(byte[] bytes, int trimLength) { checkArgument(bytes.length % 4 == 0); checkArgument(trimLength < 0 || trimLength % 4 == 0); byte[] rev = new byte[trimLength >= 0 && bytes.length > trimLength ? trimLength : bytes.length]; for (int i = 0; i < rev.length; i += 4) { System.arraycopy(bytes, i, rev, i , 4); for (int j = 0; j < 4; j++) { rev[i + j] = bytes[i + 3 - j]; } } return rev; } | Utils { public static byte[] reverseDwordBytes(byte[] bytes, int trimLength) { checkArgument(bytes.length % 4 == 0); checkArgument(trimLength < 0 || trimLength % 4 == 0); byte[] rev = new byte[trimLength >= 0 && bytes.length > trimLength ? trimLength : bytes.length]; for (int i = 0; i < rev.length; i += 4) { System.arraycopy(bytes, i, rev, i , 4); for (int j = 0; j < 4; j++) { rev[i + j] = bytes[i + 3 - j]; } } return rev; } } | Utils { public static byte[] reverseDwordBytes(byte[] bytes, int trimLength) { checkArgument(bytes.length % 4 == 0); checkArgument(trimLength < 0 || trimLength % 4 == 0); byte[] rev = new byte[trimLength >= 0 && bytes.length > trimLength ? trimLength : bytes.length]; for (int i = 0; i < rev.length; i += 4) { System.arraycopy(bytes, i, rev, i , 4); for (int j = 0; j < 4; j++) { rev[i + j] = bytes[i + 3 - j]; } } return rev; } } | Utils { public static byte[] reverseDwordBytes(byte[] bytes, int trimLength) { checkArgument(bytes.length % 4 == 0); checkArgument(trimLength < 0 || trimLength % 4 == 0); byte[] rev = new byte[trimLength >= 0 && bytes.length > trimLength ? trimLength : bytes.length]; for (int i = 0; i < rev.length; i += 4) { System.arraycopy(bytes, i, rev, i , 4); for (int j = 0; j < 4; j++) { rev[i + j] = bytes[i + 3 - j]; } } return rev; } static BigInteger toNanoCoins(int coins, int cents); static byte[] bigIntegerToBytes(BigInteger b, int numBytes); static BigInteger toNanoCoins(String coins); static void uint32ToByteArrayBE(long val, byte[] out, int offset); static void uint32ToByteArrayLE(long val, byte[] out, int offset); static void uint32ToByteStreamLE(long val, OutputStream stream); static void int64ToByteStreamLE(long val, OutputStream stream); static void uint64ToByteStreamLE(BigInteger val, OutputStream stream); static byte[] doubleDigest(byte[] input); static byte[] scryptDigest(byte[] input); static byte[] doubleDigest(byte[] input, int offset, int length); static byte[] singleDigest(byte[] input, int offset, int length); static byte[] doubleDigestTwoBuffers(byte[] input1, int offset1, int length1,
byte[] input2, int offset2, int length2); static boolean isLessThanUnsigned(long n1, long n2); static String bytesToHexString(byte[] bytes); static byte[] reverseBytes(byte[] bytes); static byte[] reverseDwordBytes(byte[] bytes, int trimLength); static long readUint32(byte[] bytes, int offset); static long readInt64(byte[] bytes, int offset); static long readUint32BE(byte[] bytes, int offset); static int readUint16BE(byte[] bytes, int offset); static byte[] sha256hash160(byte[] input); static String litecoinValueToFriendlyString(BigInteger value); static String litecoinValueToPlainString(BigInteger value); static BigInteger decodeCompactBits(long compact); static Date rollMockClock(int seconds); static Date now(); static byte[] copyOf(byte[] in, int length); static byte[] parseAsHexOrBase58(String data); static boolean isWindows(); static byte[] formatMessageForSigning(String message); static boolean checkBitLE(byte[] data, int index); static void setBitLE(byte[] data, int index); } | Utils { public static byte[] reverseDwordBytes(byte[] bytes, int trimLength) { checkArgument(bytes.length % 4 == 0); checkArgument(trimLength < 0 || trimLength % 4 == 0); byte[] rev = new byte[trimLength >= 0 && bytes.length > trimLength ? trimLength : bytes.length]; for (int i = 0; i < rev.length; i += 4) { System.arraycopy(bytes, i, rev, i , 4); for (int j = 0; j < 4; j++) { rev[i + j] = bytes[i + 3 - j]; } } return rev; } static BigInteger toNanoCoins(int coins, int cents); static byte[] bigIntegerToBytes(BigInteger b, int numBytes); static BigInteger toNanoCoins(String coins); static void uint32ToByteArrayBE(long val, byte[] out, int offset); static void uint32ToByteArrayLE(long val, byte[] out, int offset); static void uint32ToByteStreamLE(long val, OutputStream stream); static void int64ToByteStreamLE(long val, OutputStream stream); static void uint64ToByteStreamLE(BigInteger val, OutputStream stream); static byte[] doubleDigest(byte[] input); static byte[] scryptDigest(byte[] input); static byte[] doubleDigest(byte[] input, int offset, int length); static byte[] singleDigest(byte[] input, int offset, int length); static byte[] doubleDigestTwoBuffers(byte[] input1, int offset1, int length1,
byte[] input2, int offset2, int length2); static boolean isLessThanUnsigned(long n1, long n2); static String bytesToHexString(byte[] bytes); static byte[] reverseBytes(byte[] bytes); static byte[] reverseDwordBytes(byte[] bytes, int trimLength); static long readUint32(byte[] bytes, int offset); static long readInt64(byte[] bytes, int offset); static long readUint32BE(byte[] bytes, int offset); static int readUint16BE(byte[] bytes, int offset); static byte[] sha256hash160(byte[] input); static String litecoinValueToFriendlyString(BigInteger value); static String litecoinValueToPlainString(BigInteger value); static BigInteger decodeCompactBits(long compact); static Date rollMockClock(int seconds); static Date now(); static byte[] copyOf(byte[] in, int length); static byte[] parseAsHexOrBase58(String data); static boolean isWindows(); static byte[] formatMessageForSigning(String message); static boolean checkBitLE(byte[] data, int index); static void setBitLE(byte[] data, int index); static final String LITECOIN_SIGNED_MESSAGE_HEADER; static final BigInteger COIN; static final BigInteger CENT; static volatile Date mockTime; } |
@Test public void testConvertToLitecoinURI() throws Exception { Address goodAddress = new Address(NetworkParameters.prodNet(), PRODNET_GOOD_ADDRESS); assertEquals("litecoin:" + PRODNET_GOOD_ADDRESS + "?amount=12.34&label=Hello&message=AMessage", LitecoinURI.convertToLitecoinURI(goodAddress, Utils.toNanoCoins("12.34"), "Hello", "AMessage")); assertEquals("litecoin:" + PRODNET_GOOD_ADDRESS + "?amount=12.34&label=Hello%20World&message=Mess%20%26%20age%20%2B%20hope", LitecoinURI.convertToLitecoinURI(goodAddress, Utils.toNanoCoins("12.34"), "Hello World", "Mess & age + hope")); try { LitecoinURI.convertToLitecoinURI(goodAddress, Utils.toNanoCoins("-0.1"), "hope", "glory"); fail("Expecting IllegalArgumentException"); } catch (IllegalArgumentException e) { assertTrue(e.getMessage().contains("Amount must be positive")); } assertEquals("litecoin:" + PRODNET_GOOD_ADDRESS + "?label=Hello&message=glory", LitecoinURI.convertToLitecoinURI(goodAddress, null, "Hello", "glory")); assertEquals("litecoin:" + PRODNET_GOOD_ADDRESS + "?amount=0.1&message=glory", LitecoinURI.convertToLitecoinURI(goodAddress, Utils.toNanoCoins("0.1"), null, "glory")); assertEquals("litecoin:" + PRODNET_GOOD_ADDRESS + "?amount=0.1&message=glory", LitecoinURI.convertToLitecoinURI(goodAddress, Utils.toNanoCoins("0.1"), "", "glory")); assertEquals("litecoin:" + PRODNET_GOOD_ADDRESS + "?amount=12.34&label=Hello", LitecoinURI.convertToLitecoinURI(goodAddress,Utils.toNanoCoins("12.34"), "Hello", null)); assertEquals("litecoin:" + PRODNET_GOOD_ADDRESS + "?amount=12.34&label=Hello", LitecoinURI.convertToLitecoinURI(goodAddress, Utils.toNanoCoins("12.34"), "Hello", "")); assertEquals("litecoin:" + PRODNET_GOOD_ADDRESS + "?amount=1000", LitecoinURI.convertToLitecoinURI(goodAddress, Utils.toNanoCoins("1000"), null, null)); assertEquals("litecoin:" + PRODNET_GOOD_ADDRESS + "?amount=1000", LitecoinURI.convertToLitecoinURI(goodAddress, Utils.toNanoCoins("1000"), "", "")); assertEquals("litecoin:" + PRODNET_GOOD_ADDRESS + "?label=Hello", LitecoinURI.convertToLitecoinURI(goodAddress, null, "Hello", null)); assertEquals("litecoin:" + PRODNET_GOOD_ADDRESS + "?message=Agatha", LitecoinURI.convertToLitecoinURI(goodAddress, null, null, "Agatha")); assertEquals("litecoin:" + PRODNET_GOOD_ADDRESS + "?message=Agatha", LitecoinURI.convertToLitecoinURI(goodAddress, null, "", "Agatha")); assertEquals("litecoin:" + PRODNET_GOOD_ADDRESS, LitecoinURI.convertToLitecoinURI(goodAddress, null, null, null)); assertEquals("litecoin:" + PRODNET_GOOD_ADDRESS, LitecoinURI.convertToLitecoinURI(goodAddress, null, "", "")); } | public static String convertToLitecoinURI(Address address, BigInteger amount, String label, String message) { return convertToLitecoinURI(address.toString(), amount, label, message); } | LitecoinURI { public static String convertToLitecoinURI(Address address, BigInteger amount, String label, String message) { return convertToLitecoinURI(address.toString(), amount, label, message); } } | LitecoinURI { public static String convertToLitecoinURI(Address address, BigInteger amount, String label, String message) { return convertToLitecoinURI(address.toString(), amount, label, message); } LitecoinURI(String uri); LitecoinURI(NetworkParameters params, String input); } | LitecoinURI { public static String convertToLitecoinURI(Address address, BigInteger amount, String label, String message) { return convertToLitecoinURI(address.toString(), amount, label, message); } LitecoinURI(String uri); LitecoinURI(NetworkParameters params, String input); Address getAddress(); BigInteger getAmount(); String getLabel(); String getMessage(); Object getParameterByName(String name); @Override String toString(); static String convertToLitecoinURI(Address address, BigInteger amount, String label, String message); static String convertToLitecoinURI(String address, BigInteger amount, String label, String message); } | LitecoinURI { public static String convertToLitecoinURI(Address address, BigInteger amount, String label, String message) { return convertToLitecoinURI(address.toString(), amount, label, message); } LitecoinURI(String uri); LitecoinURI(NetworkParameters params, String input); Address getAddress(); BigInteger getAmount(); String getLabel(); String getMessage(); Object getParameterByName(String name); @Override String toString(); static String convertToLitecoinURI(Address address, BigInteger amount, String label, String message); static String convertToLitecoinURI(String address, BigInteger amount, String label, String message); static final String FIELD_MESSAGE; static final String FIELD_LABEL; static final String FIELD_AMOUNT; static final String FIELD_ADDRESS; static final String LITECOIN_SCHEME; } |
@Test public void testBad_BadSyntax() { try { testObject = new LitecoinURI(NetworkParameters.prodNet(), LitecoinURI.LITECOIN_SCHEME + "|" + PRODNET_GOOD_ADDRESS); fail("Expecting LitecoinURIParseException"); } catch (LitecoinURIParseException e) { assertTrue(e.getMessage().contains("Bad URI syntax")); } try { testObject = new LitecoinURI(NetworkParameters.prodNet(), LitecoinURI.LITECOIN_SCHEME + ":" + PRODNET_GOOD_ADDRESS + "\\"); fail("Expecting LitecoinURIParseException"); } catch (LitecoinURIParseException e) { assertTrue(e.getMessage().contains("Bad URI syntax")); } try { testObject = new LitecoinURI(NetworkParameters.prodNet(), LitecoinURI.LITECOIN_SCHEME + ":"); fail("Expecting LitecoinURIParseException"); } catch (LitecoinURIParseException e) { assertTrue(e.getMessage().contains("Bad URI syntax")); } } | public String getMessage() { return (String) parameterMap.get(FIELD_MESSAGE); } | LitecoinURI { public String getMessage() { return (String) parameterMap.get(FIELD_MESSAGE); } } | LitecoinURI { public String getMessage() { return (String) parameterMap.get(FIELD_MESSAGE); } LitecoinURI(String uri); LitecoinURI(NetworkParameters params, String input); } | LitecoinURI { public String getMessage() { return (String) parameterMap.get(FIELD_MESSAGE); } LitecoinURI(String uri); LitecoinURI(NetworkParameters params, String input); Address getAddress(); BigInteger getAmount(); String getLabel(); String getMessage(); Object getParameterByName(String name); @Override String toString(); static String convertToLitecoinURI(Address address, BigInteger amount, String label, String message); static String convertToLitecoinURI(String address, BigInteger amount, String label, String message); } | LitecoinURI { public String getMessage() { return (String) parameterMap.get(FIELD_MESSAGE); } LitecoinURI(String uri); LitecoinURI(NetworkParameters params, String input); Address getAddress(); BigInteger getAmount(); String getLabel(); String getMessage(); Object getParameterByName(String name); @Override String toString(); static String convertToLitecoinURI(Address address, BigInteger amount, String label, String message); static String convertToLitecoinURI(String address, BigInteger amount, String label, String message); static final String FIELD_MESSAGE; static final String FIELD_LABEL; static final String FIELD_AMOUNT; static final String FIELD_ADDRESS; static final String LITECOIN_SCHEME; } |
@Test public void testBad_IncorrectAddressType() { try { testObject = new LitecoinURI(NetworkParameters.testNet(), LitecoinURI.LITECOIN_SCHEME + ":" + PRODNET_GOOD_ADDRESS); fail("Expecting LitecoinURIParseException"); } catch (LitecoinURIParseException e) { assertTrue(e.getMessage().contains("Bad address")); } } | public String getMessage() { return (String) parameterMap.get(FIELD_MESSAGE); } | LitecoinURI { public String getMessage() { return (String) parameterMap.get(FIELD_MESSAGE); } } | LitecoinURI { public String getMessage() { return (String) parameterMap.get(FIELD_MESSAGE); } LitecoinURI(String uri); LitecoinURI(NetworkParameters params, String input); } | LitecoinURI { public String getMessage() { return (String) parameterMap.get(FIELD_MESSAGE); } LitecoinURI(String uri); LitecoinURI(NetworkParameters params, String input); Address getAddress(); BigInteger getAmount(); String getLabel(); String getMessage(); Object getParameterByName(String name); @Override String toString(); static String convertToLitecoinURI(Address address, BigInteger amount, String label, String message); static String convertToLitecoinURI(String address, BigInteger amount, String label, String message); } | LitecoinURI { public String getMessage() { return (String) parameterMap.get(FIELD_MESSAGE); } LitecoinURI(String uri); LitecoinURI(NetworkParameters params, String input); Address getAddress(); BigInteger getAmount(); String getLabel(); String getMessage(); Object getParameterByName(String name); @Override String toString(); static String convertToLitecoinURI(Address address, BigInteger amount, String label, String message); static String convertToLitecoinURI(String address, BigInteger amount, String label, String message); static final String FIELD_MESSAGE; static final String FIELD_LABEL; static final String FIELD_AMOUNT; static final String FIELD_ADDRESS; static final String LITECOIN_SCHEME; } |
@Test public void testGood_Label() throws LitecoinURIParseException { testObject = new LitecoinURI(NetworkParameters.prodNet(), LitecoinURI.LITECOIN_SCHEME + ":" + PRODNET_GOOD_ADDRESS + "?label=Hello%20World"); assertEquals("Hello World", testObject.getLabel()); } | public String getLabel() { return (String) parameterMap.get(FIELD_LABEL); } | LitecoinURI { public String getLabel() { return (String) parameterMap.get(FIELD_LABEL); } } | LitecoinURI { public String getLabel() { return (String) parameterMap.get(FIELD_LABEL); } LitecoinURI(String uri); LitecoinURI(NetworkParameters params, String input); } | LitecoinURI { public String getLabel() { return (String) parameterMap.get(FIELD_LABEL); } LitecoinURI(String uri); LitecoinURI(NetworkParameters params, String input); Address getAddress(); BigInteger getAmount(); String getLabel(); String getMessage(); Object getParameterByName(String name); @Override String toString(); static String convertToLitecoinURI(Address address, BigInteger amount, String label, String message); static String convertToLitecoinURI(String address, BigInteger amount, String label, String message); } | LitecoinURI { public String getLabel() { return (String) parameterMap.get(FIELD_LABEL); } LitecoinURI(String uri); LitecoinURI(NetworkParameters params, String input); Address getAddress(); BigInteger getAmount(); String getLabel(); String getMessage(); Object getParameterByName(String name); @Override String toString(); static String convertToLitecoinURI(Address address, BigInteger amount, String label, String message); static String convertToLitecoinURI(String address, BigInteger amount, String label, String message); static final String FIELD_MESSAGE; static final String FIELD_LABEL; static final String FIELD_AMOUNT; static final String FIELD_ADDRESS; static final String LITECOIN_SCHEME; } |
@Test public void testGood_Message() throws LitecoinURIParseException { testObject = new LitecoinURI(NetworkParameters.prodNet(), LitecoinURI.LITECOIN_SCHEME + ":" + PRODNET_GOOD_ADDRESS + "?message=Hello%20World"); assertEquals("Hello World", testObject.getMessage()); } | public String getMessage() { return (String) parameterMap.get(FIELD_MESSAGE); } | LitecoinURI { public String getMessage() { return (String) parameterMap.get(FIELD_MESSAGE); } } | LitecoinURI { public String getMessage() { return (String) parameterMap.get(FIELD_MESSAGE); } LitecoinURI(String uri); LitecoinURI(NetworkParameters params, String input); } | LitecoinURI { public String getMessage() { return (String) parameterMap.get(FIELD_MESSAGE); } LitecoinURI(String uri); LitecoinURI(NetworkParameters params, String input); Address getAddress(); BigInteger getAmount(); String getLabel(); String getMessage(); Object getParameterByName(String name); @Override String toString(); static String convertToLitecoinURI(Address address, BigInteger amount, String label, String message); static String convertToLitecoinURI(String address, BigInteger amount, String label, String message); } | LitecoinURI { public String getMessage() { return (String) parameterMap.get(FIELD_MESSAGE); } LitecoinURI(String uri); LitecoinURI(NetworkParameters params, String input); Address getAddress(); BigInteger getAmount(); String getLabel(); String getMessage(); Object getParameterByName(String name); @Override String toString(); static String convertToLitecoinURI(Address address, BigInteger amount, String label, String message); static String convertToLitecoinURI(String address, BigInteger amount, String label, String message); static final String FIELD_MESSAGE; static final String FIELD_LABEL; static final String FIELD_AMOUNT; static final String FIELD_ADDRESS; static final String LITECOIN_SCHEME; } |
@Test public void testGood_Combinations() throws LitecoinURIParseException { testObject = new LitecoinURI(NetworkParameters.prodNet(), LitecoinURI.LITECOIN_SCHEME + ":" + PRODNET_GOOD_ADDRESS + "?amount=9876543210&label=Hello%20World&message=Be%20well"); assertEquals( "LitecoinURI['address'='LQz2pJYaeqntA9BFB8rDX5AL2TTKGd5AuN','amount'='987654321000000000','label'='Hello World','message'='Be well']", testObject.toString()); } | @Override public String toString() { StringBuilder builder = new StringBuilder("LitecoinURI["); boolean first = true; for (Map.Entry<String, Object> entry : parameterMap.entrySet()) { if (first) { first = false; } else { builder.append(","); } builder.append("'").append(entry.getKey()).append("'=").append("'").append(entry.getValue().toString()).append("'"); } builder.append("]"); return builder.toString(); } | LitecoinURI { @Override public String toString() { StringBuilder builder = new StringBuilder("LitecoinURI["); boolean first = true; for (Map.Entry<String, Object> entry : parameterMap.entrySet()) { if (first) { first = false; } else { builder.append(","); } builder.append("'").append(entry.getKey()).append("'=").append("'").append(entry.getValue().toString()).append("'"); } builder.append("]"); return builder.toString(); } } | LitecoinURI { @Override public String toString() { StringBuilder builder = new StringBuilder("LitecoinURI["); boolean first = true; for (Map.Entry<String, Object> entry : parameterMap.entrySet()) { if (first) { first = false; } else { builder.append(","); } builder.append("'").append(entry.getKey()).append("'=").append("'").append(entry.getValue().toString()).append("'"); } builder.append("]"); return builder.toString(); } LitecoinURI(String uri); LitecoinURI(NetworkParameters params, String input); } | LitecoinURI { @Override public String toString() { StringBuilder builder = new StringBuilder("LitecoinURI["); boolean first = true; for (Map.Entry<String, Object> entry : parameterMap.entrySet()) { if (first) { first = false; } else { builder.append(","); } builder.append("'").append(entry.getKey()).append("'=").append("'").append(entry.getValue().toString()).append("'"); } builder.append("]"); return builder.toString(); } LitecoinURI(String uri); LitecoinURI(NetworkParameters params, String input); Address getAddress(); BigInteger getAmount(); String getLabel(); String getMessage(); Object getParameterByName(String name); @Override String toString(); static String convertToLitecoinURI(Address address, BigInteger amount, String label, String message); static String convertToLitecoinURI(String address, BigInteger amount, String label, String message); } | LitecoinURI { @Override public String toString() { StringBuilder builder = new StringBuilder("LitecoinURI["); boolean first = true; for (Map.Entry<String, Object> entry : parameterMap.entrySet()) { if (first) { first = false; } else { builder.append(","); } builder.append("'").append(entry.getKey()).append("'=").append("'").append(entry.getValue().toString()).append("'"); } builder.append("]"); return builder.toString(); } LitecoinURI(String uri); LitecoinURI(NetworkParameters params, String input); Address getAddress(); BigInteger getAmount(); String getLabel(); String getMessage(); Object getParameterByName(String name); @Override String toString(); static String convertToLitecoinURI(Address address, BigInteger amount, String label, String message); static String convertToLitecoinURI(String address, BigInteger amount, String label, String message); static final String FIELD_MESSAGE; static final String FIELD_LABEL; static final String FIELD_AMOUNT; static final String FIELD_ADDRESS; static final String LITECOIN_SCHEME; } |
@Test public void getRecipients() { dao.getRecipients(); } | public List<Recipient> getRecipients() { return mapper.scan(Recipient.class, new DynamoDBScanExpression()); } | CloudNoticeDAO { public List<Recipient> getRecipients() { return mapper.scan(Recipient.class, new DynamoDBScanExpression()); } } | CloudNoticeDAO { public List<Recipient> getRecipients() { return mapper.scan(Recipient.class, new DynamoDBScanExpression()); } CloudNoticeDAO(boolean local); } | CloudNoticeDAO { public List<Recipient> getRecipients() { return mapper.scan(Recipient.class, new DynamoDBScanExpression()); } CloudNoticeDAO(boolean local); List<Recipient> getRecipients(); void saveRecipient(Recipient recip); void deleteRecipient(Recipient recip); void shutdown(); } | CloudNoticeDAO { public List<Recipient> getRecipients() { return mapper.scan(Recipient.class, new DynamoDBScanExpression()); } CloudNoticeDAO(boolean local); List<Recipient> getRecipients(); void saveRecipient(Recipient recip); void deleteRecipient(Recipient recip); void shutdown(); static final String TABLE_NAME; } |
@Test public void nowWithoutSpacesAndTime() { Queue<Token> words = parser.parse("now+03:04"); Assert.assertTrue(words.poll() instanceof TimeToken); Assert.assertTrue(words.poll() instanceof OperatorToken); Assert.assertTrue(words.poll() instanceof TimeToken); } | public Queue<Token> parse(String text) { final Queue<Token> tokens = new ArrayDeque<>(); if (text != null) { text = text.trim(); if (!text.isEmpty()) { boolean matchFound = false; for (InfoWrapper iw : infos) { final Matcher matcher = iw.pattern.matcher(text); if (matcher.find()) { matchFound = true; String match = matcher.group().trim(); tokens.add(iw.info.getToken(match)); tokens.addAll(parse(text.substring(match.length()))); break; } } if (!matchFound) { throw new DateCalcException("Could not parse the expression: " + text); } } } return tokens; } | DateCalcExpressionParser { public Queue<Token> parse(String text) { final Queue<Token> tokens = new ArrayDeque<>(); if (text != null) { text = text.trim(); if (!text.isEmpty()) { boolean matchFound = false; for (InfoWrapper iw : infos) { final Matcher matcher = iw.pattern.matcher(text); if (matcher.find()) { matchFound = true; String match = matcher.group().trim(); tokens.add(iw.info.getToken(match)); tokens.addAll(parse(text.substring(match.length()))); break; } } if (!matchFound) { throw new DateCalcException("Could not parse the expression: " + text); } } } return tokens; } } | DateCalcExpressionParser { public Queue<Token> parse(String text) { final Queue<Token> tokens = new ArrayDeque<>(); if (text != null) { text = text.trim(); if (!text.isEmpty()) { boolean matchFound = false; for (InfoWrapper iw : infos) { final Matcher matcher = iw.pattern.matcher(text); if (matcher.find()) { matchFound = true; String match = matcher.group().trim(); tokens.add(iw.info.getToken(match)); tokens.addAll(parse(text.substring(match.length()))); break; } } if (!matchFound) { throw new DateCalcException("Could not parse the expression: " + text); } } } return tokens; } DateCalcExpressionParser(); } | DateCalcExpressionParser { public Queue<Token> parse(String text) { final Queue<Token> tokens = new ArrayDeque<>(); if (text != null) { text = text.trim(); if (!text.isEmpty()) { boolean matchFound = false; for (InfoWrapper iw : infos) { final Matcher matcher = iw.pattern.matcher(text); if (matcher.find()) { matchFound = true; String match = matcher.group().trim(); tokens.add(iw.info.getToken(match)); tokens.addAll(parse(text.substring(match.length()))); break; } } if (!matchFound) { throw new DateCalcException("Could not parse the expression: " + text); } } } return tokens; } DateCalcExpressionParser(); Queue<Token> parse(String text); } | DateCalcExpressionParser { public Queue<Token> parse(String text) { final Queue<Token> tokens = new ArrayDeque<>(); if (text != null) { text = text.trim(); if (!text.isEmpty()) { boolean matchFound = false; for (InfoWrapper iw : infos) { final Matcher matcher = iw.pattern.matcher(text); if (matcher.find()) { matchFound = true; String match = matcher.group().trim(); tokens.add(iw.info.getToken(match)); tokens.addAll(parse(text.substring(match.length()))); break; } } if (!matchFound) { throw new DateCalcException("Could not parse the expression: " + text); } } } return tokens; } DateCalcExpressionParser(); Queue<Token> parse(String text); } |
@Test public void nowWithoutSpacesAndUnitOfMeasure() { Queue<Token> tokens = parser.parse("now+3h4m"); Assert.assertEquals(tokens.size(), 6); Assert.assertTrue(tokens.poll() instanceof TimeToken); Assert.assertTrue(tokens.poll() instanceof OperatorToken); Assert.assertTrue(tokens.poll() instanceof IntegerToken); Assert.assertTrue(tokens.poll() instanceof UnitOfMeasureToken); Assert.assertTrue(tokens.poll() instanceof IntegerToken); Assert.assertTrue(tokens.poll() instanceof UnitOfMeasureToken); } | public Queue<Token> parse(String text) { final Queue<Token> tokens = new ArrayDeque<>(); if (text != null) { text = text.trim(); if (!text.isEmpty()) { boolean matchFound = false; for (InfoWrapper iw : infos) { final Matcher matcher = iw.pattern.matcher(text); if (matcher.find()) { matchFound = true; String match = matcher.group().trim(); tokens.add(iw.info.getToken(match)); tokens.addAll(parse(text.substring(match.length()))); break; } } if (!matchFound) { throw new DateCalcException("Could not parse the expression: " + text); } } } return tokens; } | DateCalcExpressionParser { public Queue<Token> parse(String text) { final Queue<Token> tokens = new ArrayDeque<>(); if (text != null) { text = text.trim(); if (!text.isEmpty()) { boolean matchFound = false; for (InfoWrapper iw : infos) { final Matcher matcher = iw.pattern.matcher(text); if (matcher.find()) { matchFound = true; String match = matcher.group().trim(); tokens.add(iw.info.getToken(match)); tokens.addAll(parse(text.substring(match.length()))); break; } } if (!matchFound) { throw new DateCalcException("Could not parse the expression: " + text); } } } return tokens; } } | DateCalcExpressionParser { public Queue<Token> parse(String text) { final Queue<Token> tokens = new ArrayDeque<>(); if (text != null) { text = text.trim(); if (!text.isEmpty()) { boolean matchFound = false; for (InfoWrapper iw : infos) { final Matcher matcher = iw.pattern.matcher(text); if (matcher.find()) { matchFound = true; String match = matcher.group().trim(); tokens.add(iw.info.getToken(match)); tokens.addAll(parse(text.substring(match.length()))); break; } } if (!matchFound) { throw new DateCalcException("Could not parse the expression: " + text); } } } return tokens; } DateCalcExpressionParser(); } | DateCalcExpressionParser { public Queue<Token> parse(String text) { final Queue<Token> tokens = new ArrayDeque<>(); if (text != null) { text = text.trim(); if (!text.isEmpty()) { boolean matchFound = false; for (InfoWrapper iw : infos) { final Matcher matcher = iw.pattern.matcher(text); if (matcher.find()) { matchFound = true; String match = matcher.group().trim(); tokens.add(iw.info.getToken(match)); tokens.addAll(parse(text.substring(match.length()))); break; } } if (!matchFound) { throw new DateCalcException("Could not parse the expression: " + text); } } } return tokens; } DateCalcExpressionParser(); Queue<Token> parse(String text); } | DateCalcExpressionParser { public Queue<Token> parse(String text) { final Queue<Token> tokens = new ArrayDeque<>(); if (text != null) { text = text.trim(); if (!text.isEmpty()) { boolean matchFound = false; for (InfoWrapper iw : infos) { final Matcher matcher = iw.pattern.matcher(text); if (matcher.find()) { matchFound = true; String match = matcher.group().trim(); tokens.add(iw.info.getToken(match)); tokens.addAll(parse(text.substring(match.length()))); break; } } if (!matchFound) { throw new DateCalcException("Could not parse the expression: " + text); } } } return tokens; } DateCalcExpressionParser(); Queue<Token> parse(String text); } |
@Test public void timeAdditionWithSpaces() { Queue<Token> words = parser.parse("12:37 + 0:42"); Assert.assertTrue(words.poll() instanceof TimeToken); Assert.assertTrue(words.poll() instanceof OperatorToken); Assert.assertTrue(words.poll() instanceof TimeToken); } | public Queue<Token> parse(String text) { final Queue<Token> tokens = new ArrayDeque<>(); if (text != null) { text = text.trim(); if (!text.isEmpty()) { boolean matchFound = false; for (InfoWrapper iw : infos) { final Matcher matcher = iw.pattern.matcher(text); if (matcher.find()) { matchFound = true; String match = matcher.group().trim(); tokens.add(iw.info.getToken(match)); tokens.addAll(parse(text.substring(match.length()))); break; } } if (!matchFound) { throw new DateCalcException("Could not parse the expression: " + text); } } } return tokens; } | DateCalcExpressionParser { public Queue<Token> parse(String text) { final Queue<Token> tokens = new ArrayDeque<>(); if (text != null) { text = text.trim(); if (!text.isEmpty()) { boolean matchFound = false; for (InfoWrapper iw : infos) { final Matcher matcher = iw.pattern.matcher(text); if (matcher.find()) { matchFound = true; String match = matcher.group().trim(); tokens.add(iw.info.getToken(match)); tokens.addAll(parse(text.substring(match.length()))); break; } } if (!matchFound) { throw new DateCalcException("Could not parse the expression: " + text); } } } return tokens; } } | DateCalcExpressionParser { public Queue<Token> parse(String text) { final Queue<Token> tokens = new ArrayDeque<>(); if (text != null) { text = text.trim(); if (!text.isEmpty()) { boolean matchFound = false; for (InfoWrapper iw : infos) { final Matcher matcher = iw.pattern.matcher(text); if (matcher.find()) { matchFound = true; String match = matcher.group().trim(); tokens.add(iw.info.getToken(match)); tokens.addAll(parse(text.substring(match.length()))); break; } } if (!matchFound) { throw new DateCalcException("Could not parse the expression: " + text); } } } return tokens; } DateCalcExpressionParser(); } | DateCalcExpressionParser { public Queue<Token> parse(String text) { final Queue<Token> tokens = new ArrayDeque<>(); if (text != null) { text = text.trim(); if (!text.isEmpty()) { boolean matchFound = false; for (InfoWrapper iw : infos) { final Matcher matcher = iw.pattern.matcher(text); if (matcher.find()) { matchFound = true; String match = matcher.group().trim(); tokens.add(iw.info.getToken(match)); tokens.addAll(parse(text.substring(match.length()))); break; } } if (!matchFound) { throw new DateCalcException("Could not parse the expression: " + text); } } } return tokens; } DateCalcExpressionParser(); Queue<Token> parse(String text); } | DateCalcExpressionParser { public Queue<Token> parse(String text) { final Queue<Token> tokens = new ArrayDeque<>(); if (text != null) { text = text.trim(); if (!text.isEmpty()) { boolean matchFound = false; for (InfoWrapper iw : infos) { final Matcher matcher = iw.pattern.matcher(text); if (matcher.find()) { matchFound = true; String match = matcher.group().trim(); tokens.add(iw.info.getToken(match)); tokens.addAll(parse(text.substring(match.length()))); break; } } if (!matchFound) { throw new DateCalcException("Could not parse the expression: " + text); } } } return tokens; } DateCalcExpressionParser(); Queue<Token> parse(String text); } |
@Test public void timeAdditionWithoutSpaces() { Queue<Token> words = parser.parse("12:37+0:42"); Assert.assertTrue(words.poll() instanceof TimeToken); Assert.assertTrue(words.poll() instanceof OperatorToken); Assert.assertTrue(words.poll() instanceof TimeToken); } | public Queue<Token> parse(String text) { final Queue<Token> tokens = new ArrayDeque<>(); if (text != null) { text = text.trim(); if (!text.isEmpty()) { boolean matchFound = false; for (InfoWrapper iw : infos) { final Matcher matcher = iw.pattern.matcher(text); if (matcher.find()) { matchFound = true; String match = matcher.group().trim(); tokens.add(iw.info.getToken(match)); tokens.addAll(parse(text.substring(match.length()))); break; } } if (!matchFound) { throw new DateCalcException("Could not parse the expression: " + text); } } } return tokens; } | DateCalcExpressionParser { public Queue<Token> parse(String text) { final Queue<Token> tokens = new ArrayDeque<>(); if (text != null) { text = text.trim(); if (!text.isEmpty()) { boolean matchFound = false; for (InfoWrapper iw : infos) { final Matcher matcher = iw.pattern.matcher(text); if (matcher.find()) { matchFound = true; String match = matcher.group().trim(); tokens.add(iw.info.getToken(match)); tokens.addAll(parse(text.substring(match.length()))); break; } } if (!matchFound) { throw new DateCalcException("Could not parse the expression: " + text); } } } return tokens; } } | DateCalcExpressionParser { public Queue<Token> parse(String text) { final Queue<Token> tokens = new ArrayDeque<>(); if (text != null) { text = text.trim(); if (!text.isEmpty()) { boolean matchFound = false; for (InfoWrapper iw : infos) { final Matcher matcher = iw.pattern.matcher(text); if (matcher.find()) { matchFound = true; String match = matcher.group().trim(); tokens.add(iw.info.getToken(match)); tokens.addAll(parse(text.substring(match.length()))); break; } } if (!matchFound) { throw new DateCalcException("Could not parse the expression: " + text); } } } return tokens; } DateCalcExpressionParser(); } | DateCalcExpressionParser { public Queue<Token> parse(String text) { final Queue<Token> tokens = new ArrayDeque<>(); if (text != null) { text = text.trim(); if (!text.isEmpty()) { boolean matchFound = false; for (InfoWrapper iw : infos) { final Matcher matcher = iw.pattern.matcher(text); if (matcher.find()) { matchFound = true; String match = matcher.group().trim(); tokens.add(iw.info.getToken(match)); tokens.addAll(parse(text.substring(match.length()))); break; } } if (!matchFound) { throw new DateCalcException("Could not parse the expression: " + text); } } } return tokens; } DateCalcExpressionParser(); Queue<Token> parse(String text); } | DateCalcExpressionParser { public Queue<Token> parse(String text) { final Queue<Token> tokens = new ArrayDeque<>(); if (text != null) { text = text.trim(); if (!text.isEmpty()) { boolean matchFound = false; for (InfoWrapper iw : infos) { final Matcher matcher = iw.pattern.matcher(text); if (matcher.find()) { matchFound = true; String match = matcher.group().trim(); tokens.add(iw.info.getToken(match)); tokens.addAll(parse(text.substring(match.length()))); break; } } if (!matchFound) { throw new DateCalcException("Could not parse the expression: " + text); } } } return tokens; } DateCalcExpressionParser(); Queue<Token> parse(String text); } |
@Test public void dateMathWithSpaces() { Queue<Token> words = parser.parse("2016/09/27 - 3 months"); Assert.assertTrue(words.poll() instanceof DateToken); Assert.assertTrue(words.poll() instanceof OperatorToken); Assert.assertTrue(words.poll() instanceof IntegerToken); Assert.assertTrue(words.poll() instanceof UnitOfMeasureToken); } | public Queue<Token> parse(String text) { final Queue<Token> tokens = new ArrayDeque<>(); if (text != null) { text = text.trim(); if (!text.isEmpty()) { boolean matchFound = false; for (InfoWrapper iw : infos) { final Matcher matcher = iw.pattern.matcher(text); if (matcher.find()) { matchFound = true; String match = matcher.group().trim(); tokens.add(iw.info.getToken(match)); tokens.addAll(parse(text.substring(match.length()))); break; } } if (!matchFound) { throw new DateCalcException("Could not parse the expression: " + text); } } } return tokens; } | DateCalcExpressionParser { public Queue<Token> parse(String text) { final Queue<Token> tokens = new ArrayDeque<>(); if (text != null) { text = text.trim(); if (!text.isEmpty()) { boolean matchFound = false; for (InfoWrapper iw : infos) { final Matcher matcher = iw.pattern.matcher(text); if (matcher.find()) { matchFound = true; String match = matcher.group().trim(); tokens.add(iw.info.getToken(match)); tokens.addAll(parse(text.substring(match.length()))); break; } } if (!matchFound) { throw new DateCalcException("Could not parse the expression: " + text); } } } return tokens; } } | DateCalcExpressionParser { public Queue<Token> parse(String text) { final Queue<Token> tokens = new ArrayDeque<>(); if (text != null) { text = text.trim(); if (!text.isEmpty()) { boolean matchFound = false; for (InfoWrapper iw : infos) { final Matcher matcher = iw.pattern.matcher(text); if (matcher.find()) { matchFound = true; String match = matcher.group().trim(); tokens.add(iw.info.getToken(match)); tokens.addAll(parse(text.substring(match.length()))); break; } } if (!matchFound) { throw new DateCalcException("Could not parse the expression: " + text); } } } return tokens; } DateCalcExpressionParser(); } | DateCalcExpressionParser { public Queue<Token> parse(String text) { final Queue<Token> tokens = new ArrayDeque<>(); if (text != null) { text = text.trim(); if (!text.isEmpty()) { boolean matchFound = false; for (InfoWrapper iw : infos) { final Matcher matcher = iw.pattern.matcher(text); if (matcher.find()) { matchFound = true; String match = matcher.group().trim(); tokens.add(iw.info.getToken(match)); tokens.addAll(parse(text.substring(match.length()))); break; } } if (!matchFound) { throw new DateCalcException("Could not parse the expression: " + text); } } } return tokens; } DateCalcExpressionParser(); Queue<Token> parse(String text); } | DateCalcExpressionParser { public Queue<Token> parse(String text) { final Queue<Token> tokens = new ArrayDeque<>(); if (text != null) { text = text.trim(); if (!text.isEmpty()) { boolean matchFound = false; for (InfoWrapper iw : infos) { final Matcher matcher = iw.pattern.matcher(text); if (matcher.find()) { matchFound = true; String match = matcher.group().trim(); tokens.add(iw.info.getToken(match)); tokens.addAll(parse(text.substring(match.length()))); break; } } if (!matchFound) { throw new DateCalcException("Could not parse the expression: " + text); } } } return tokens; } DateCalcExpressionParser(); Queue<Token> parse(String text); } |
@Test public void dateDiffWithoutSpaces() { Queue<Token> words = parser.parse("2016/12/25-2016/07/04"); Assert.assertTrue(words.poll() instanceof DateToken); Assert.assertTrue(words.poll() instanceof OperatorToken); Assert.assertTrue(words.poll() instanceof DateToken); } | public Queue<Token> parse(String text) { final Queue<Token> tokens = new ArrayDeque<>(); if (text != null) { text = text.trim(); if (!text.isEmpty()) { boolean matchFound = false; for (InfoWrapper iw : infos) { final Matcher matcher = iw.pattern.matcher(text); if (matcher.find()) { matchFound = true; String match = matcher.group().trim(); tokens.add(iw.info.getToken(match)); tokens.addAll(parse(text.substring(match.length()))); break; } } if (!matchFound) { throw new DateCalcException("Could not parse the expression: " + text); } } } return tokens; } | DateCalcExpressionParser { public Queue<Token> parse(String text) { final Queue<Token> tokens = new ArrayDeque<>(); if (text != null) { text = text.trim(); if (!text.isEmpty()) { boolean matchFound = false; for (InfoWrapper iw : infos) { final Matcher matcher = iw.pattern.matcher(text); if (matcher.find()) { matchFound = true; String match = matcher.group().trim(); tokens.add(iw.info.getToken(match)); tokens.addAll(parse(text.substring(match.length()))); break; } } if (!matchFound) { throw new DateCalcException("Could not parse the expression: " + text); } } } return tokens; } } | DateCalcExpressionParser { public Queue<Token> parse(String text) { final Queue<Token> tokens = new ArrayDeque<>(); if (text != null) { text = text.trim(); if (!text.isEmpty()) { boolean matchFound = false; for (InfoWrapper iw : infos) { final Matcher matcher = iw.pattern.matcher(text); if (matcher.find()) { matchFound = true; String match = matcher.group().trim(); tokens.add(iw.info.getToken(match)); tokens.addAll(parse(text.substring(match.length()))); break; } } if (!matchFound) { throw new DateCalcException("Could not parse the expression: " + text); } } } return tokens; } DateCalcExpressionParser(); } | DateCalcExpressionParser { public Queue<Token> parse(String text) { final Queue<Token> tokens = new ArrayDeque<>(); if (text != null) { text = text.trim(); if (!text.isEmpty()) { boolean matchFound = false; for (InfoWrapper iw : infos) { final Matcher matcher = iw.pattern.matcher(text); if (matcher.find()) { matchFound = true; String match = matcher.group().trim(); tokens.add(iw.info.getToken(match)); tokens.addAll(parse(text.substring(match.length()))); break; } } if (!matchFound) { throw new DateCalcException("Could not parse the expression: " + text); } } } return tokens; } DateCalcExpressionParser(); Queue<Token> parse(String text); } | DateCalcExpressionParser { public Queue<Token> parse(String text) { final Queue<Token> tokens = new ArrayDeque<>(); if (text != null) { text = text.trim(); if (!text.isEmpty()) { boolean matchFound = false; for (InfoWrapper iw : infos) { final Matcher matcher = iw.pattern.matcher(text); if (matcher.find()) { matchFound = true; String match = matcher.group().trim(); tokens.add(iw.info.getToken(match)); tokens.addAll(parse(text.substring(match.length()))); break; } } if (!matchFound) { throw new DateCalcException("Could not parse the expression: " + text); } } } return tokens; } DateCalcExpressionParser(); Queue<Token> parse(String text); } |
@Test public void dateMinusDuration() { Queue<Token> tokens = parser.parse("2016/09/27 - 3 months"); Assert.assertEquals(tokens.size(), 4); Assert.assertTrue(tokens.poll() instanceof DateToken); Assert.assertTrue(tokens.poll() instanceof OperatorToken); Assert.assertTrue(tokens.poll() instanceof IntegerToken); Assert.assertTrue(tokens.poll() instanceof UnitOfMeasureToken); } | public Queue<Token> parse(String text) { final Queue<Token> tokens = new ArrayDeque<>(); if (text != null) { text = text.trim(); if (!text.isEmpty()) { boolean matchFound = false; for (InfoWrapper iw : infos) { final Matcher matcher = iw.pattern.matcher(text); if (matcher.find()) { matchFound = true; String match = matcher.group().trim(); tokens.add(iw.info.getToken(match)); tokens.addAll(parse(text.substring(match.length()))); break; } } if (!matchFound) { throw new DateCalcException("Could not parse the expression: " + text); } } } return tokens; } | DateCalcExpressionParser { public Queue<Token> parse(String text) { final Queue<Token> tokens = new ArrayDeque<>(); if (text != null) { text = text.trim(); if (!text.isEmpty()) { boolean matchFound = false; for (InfoWrapper iw : infos) { final Matcher matcher = iw.pattern.matcher(text); if (matcher.find()) { matchFound = true; String match = matcher.group().trim(); tokens.add(iw.info.getToken(match)); tokens.addAll(parse(text.substring(match.length()))); break; } } if (!matchFound) { throw new DateCalcException("Could not parse the expression: " + text); } } } return tokens; } } | DateCalcExpressionParser { public Queue<Token> parse(String text) { final Queue<Token> tokens = new ArrayDeque<>(); if (text != null) { text = text.trim(); if (!text.isEmpty()) { boolean matchFound = false; for (InfoWrapper iw : infos) { final Matcher matcher = iw.pattern.matcher(text); if (matcher.find()) { matchFound = true; String match = matcher.group().trim(); tokens.add(iw.info.getToken(match)); tokens.addAll(parse(text.substring(match.length()))); break; } } if (!matchFound) { throw new DateCalcException("Could not parse the expression: " + text); } } } return tokens; } DateCalcExpressionParser(); } | DateCalcExpressionParser { public Queue<Token> parse(String text) { final Queue<Token> tokens = new ArrayDeque<>(); if (text != null) { text = text.trim(); if (!text.isEmpty()) { boolean matchFound = false; for (InfoWrapper iw : infos) { final Matcher matcher = iw.pattern.matcher(text); if (matcher.find()) { matchFound = true; String match = matcher.group().trim(); tokens.add(iw.info.getToken(match)); tokens.addAll(parse(text.substring(match.length()))); break; } } if (!matchFound) { throw new DateCalcException("Could not parse the expression: " + text); } } } return tokens; } DateCalcExpressionParser(); Queue<Token> parse(String text); } | DateCalcExpressionParser { public Queue<Token> parse(String text) { final Queue<Token> tokens = new ArrayDeque<>(); if (text != null) { text = text.trim(); if (!text.isEmpty()) { boolean matchFound = false; for (InfoWrapper iw : infos) { final Matcher matcher = iw.pattern.matcher(text); if (matcher.find()) { matchFound = true; String match = matcher.group().trim(); tokens.add(iw.info.getToken(match)); tokens.addAll(parse(text.substring(match.length()))); break; } } if (!matchFound) { throw new DateCalcException("Could not parse the expression: " + text); } } } return tokens; } DateCalcExpressionParser(); Queue<Token> parse(String text); } |
@Test public void dateMinusDate() { Queue<Token> tokens = parser.parse("2016/12/25-2016/07/04"); Assert.assertEquals(tokens.size(), 3); Assert.assertTrue(tokens.poll() instanceof DateToken); Assert.assertTrue(tokens.poll() instanceof OperatorToken); Assert.assertTrue(tokens.poll() instanceof DateToken); } | public Queue<Token> parse(String text) { final Queue<Token> tokens = new ArrayDeque<>(); if (text != null) { text = text.trim(); if (!text.isEmpty()) { boolean matchFound = false; for (InfoWrapper iw : infos) { final Matcher matcher = iw.pattern.matcher(text); if (matcher.find()) { matchFound = true; String match = matcher.group().trim(); tokens.add(iw.info.getToken(match)); tokens.addAll(parse(text.substring(match.length()))); break; } } if (!matchFound) { throw new DateCalcException("Could not parse the expression: " + text); } } } return tokens; } | DateCalcExpressionParser { public Queue<Token> parse(String text) { final Queue<Token> tokens = new ArrayDeque<>(); if (text != null) { text = text.trim(); if (!text.isEmpty()) { boolean matchFound = false; for (InfoWrapper iw : infos) { final Matcher matcher = iw.pattern.matcher(text); if (matcher.find()) { matchFound = true; String match = matcher.group().trim(); tokens.add(iw.info.getToken(match)); tokens.addAll(parse(text.substring(match.length()))); break; } } if (!matchFound) { throw new DateCalcException("Could not parse the expression: " + text); } } } return tokens; } } | DateCalcExpressionParser { public Queue<Token> parse(String text) { final Queue<Token> tokens = new ArrayDeque<>(); if (text != null) { text = text.trim(); if (!text.isEmpty()) { boolean matchFound = false; for (InfoWrapper iw : infos) { final Matcher matcher = iw.pattern.matcher(text); if (matcher.find()) { matchFound = true; String match = matcher.group().trim(); tokens.add(iw.info.getToken(match)); tokens.addAll(parse(text.substring(match.length()))); break; } } if (!matchFound) { throw new DateCalcException("Could not parse the expression: " + text); } } } return tokens; } DateCalcExpressionParser(); } | DateCalcExpressionParser { public Queue<Token> parse(String text) { final Queue<Token> tokens = new ArrayDeque<>(); if (text != null) { text = text.trim(); if (!text.isEmpty()) { boolean matchFound = false; for (InfoWrapper iw : infos) { final Matcher matcher = iw.pattern.matcher(text); if (matcher.find()) { matchFound = true; String match = matcher.group().trim(); tokens.add(iw.info.getToken(match)); tokens.addAll(parse(text.substring(match.length()))); break; } } if (!matchFound) { throw new DateCalcException("Could not parse the expression: " + text); } } } return tokens; } DateCalcExpressionParser(); Queue<Token> parse(String text); } | DateCalcExpressionParser { public Queue<Token> parse(String text) { final Queue<Token> tokens = new ArrayDeque<>(); if (text != null) { text = text.trim(); if (!text.isEmpty()) { boolean matchFound = false; for (InfoWrapper iw : infos) { final Matcher matcher = iw.pattern.matcher(text); if (matcher.find()) { matchFound = true; String match = matcher.group().trim(); tokens.add(iw.info.getToken(match)); tokens.addAll(parse(text.substring(match.length()))); break; } } if (!matchFound) { throw new DateCalcException("Could not parse the expression: " + text); } } } return tokens; } DateCalcExpressionParser(); Queue<Token> parse(String text); } |
@Test public void dateMinusDateWithSpaces() { Queue<Token> tokens = parser.parse("2016/12/25 - 2016/07/04"); Assert.assertEquals(tokens.size(), 3); Assert.assertTrue(tokens.poll() instanceof DateToken); Assert.assertTrue(tokens.poll() instanceof OperatorToken); Assert.assertTrue(tokens.poll() instanceof DateToken); } | public Queue<Token> parse(String text) { final Queue<Token> tokens = new ArrayDeque<>(); if (text != null) { text = text.trim(); if (!text.isEmpty()) { boolean matchFound = false; for (InfoWrapper iw : infos) { final Matcher matcher = iw.pattern.matcher(text); if (matcher.find()) { matchFound = true; String match = matcher.group().trim(); tokens.add(iw.info.getToken(match)); tokens.addAll(parse(text.substring(match.length()))); break; } } if (!matchFound) { throw new DateCalcException("Could not parse the expression: " + text); } } } return tokens; } | DateCalcExpressionParser { public Queue<Token> parse(String text) { final Queue<Token> tokens = new ArrayDeque<>(); if (text != null) { text = text.trim(); if (!text.isEmpty()) { boolean matchFound = false; for (InfoWrapper iw : infos) { final Matcher matcher = iw.pattern.matcher(text); if (matcher.find()) { matchFound = true; String match = matcher.group().trim(); tokens.add(iw.info.getToken(match)); tokens.addAll(parse(text.substring(match.length()))); break; } } if (!matchFound) { throw new DateCalcException("Could not parse the expression: " + text); } } } return tokens; } } | DateCalcExpressionParser { public Queue<Token> parse(String text) { final Queue<Token> tokens = new ArrayDeque<>(); if (text != null) { text = text.trim(); if (!text.isEmpty()) { boolean matchFound = false; for (InfoWrapper iw : infos) { final Matcher matcher = iw.pattern.matcher(text); if (matcher.find()) { matchFound = true; String match = matcher.group().trim(); tokens.add(iw.info.getToken(match)); tokens.addAll(parse(text.substring(match.length()))); break; } } if (!matchFound) { throw new DateCalcException("Could not parse the expression: " + text); } } } return tokens; } DateCalcExpressionParser(); } | DateCalcExpressionParser { public Queue<Token> parse(String text) { final Queue<Token> tokens = new ArrayDeque<>(); if (text != null) { text = text.trim(); if (!text.isEmpty()) { boolean matchFound = false; for (InfoWrapper iw : infos) { final Matcher matcher = iw.pattern.matcher(text); if (matcher.find()) { matchFound = true; String match = matcher.group().trim(); tokens.add(iw.info.getToken(match)); tokens.addAll(parse(text.substring(match.length()))); break; } } if (!matchFound) { throw new DateCalcException("Could not parse the expression: " + text); } } } return tokens; } DateCalcExpressionParser(); Queue<Token> parse(String text); } | DateCalcExpressionParser { public Queue<Token> parse(String text) { final Queue<Token> tokens = new ArrayDeque<>(); if (text != null) { text = text.trim(); if (!text.isEmpty()) { boolean matchFound = false; for (InfoWrapper iw : infos) { final Matcher matcher = iw.pattern.matcher(text); if (matcher.find()) { matchFound = true; String match = matcher.group().trim(); tokens.add(iw.info.getToken(match)); tokens.addAll(parse(text.substring(match.length()))); break; } } if (!matchFound) { throw new DateCalcException("Could not parse the expression: " + text); } } } return tokens; } DateCalcExpressionParser(); Queue<Token> parse(String text); } |
@Test public void dateMinusDateWithInvalidOperator() { try { Queue<Token> tokens = parser.parse("2016/12/25 * 2016/07/04"); Assert.fail("A DateCalcException should have been thrown for an illegal character"); } catch (DateCalcException dce) { } } | public Queue<Token> parse(String text) { final Queue<Token> tokens = new ArrayDeque<>(); if (text != null) { text = text.trim(); if (!text.isEmpty()) { boolean matchFound = false; for (InfoWrapper iw : infos) { final Matcher matcher = iw.pattern.matcher(text); if (matcher.find()) { matchFound = true; String match = matcher.group().trim(); tokens.add(iw.info.getToken(match)); tokens.addAll(parse(text.substring(match.length()))); break; } } if (!matchFound) { throw new DateCalcException("Could not parse the expression: " + text); } } } return tokens; } | DateCalcExpressionParser { public Queue<Token> parse(String text) { final Queue<Token> tokens = new ArrayDeque<>(); if (text != null) { text = text.trim(); if (!text.isEmpty()) { boolean matchFound = false; for (InfoWrapper iw : infos) { final Matcher matcher = iw.pattern.matcher(text); if (matcher.find()) { matchFound = true; String match = matcher.group().trim(); tokens.add(iw.info.getToken(match)); tokens.addAll(parse(text.substring(match.length()))); break; } } if (!matchFound) { throw new DateCalcException("Could not parse the expression: " + text); } } } return tokens; } } | DateCalcExpressionParser { public Queue<Token> parse(String text) { final Queue<Token> tokens = new ArrayDeque<>(); if (text != null) { text = text.trim(); if (!text.isEmpty()) { boolean matchFound = false; for (InfoWrapper iw : infos) { final Matcher matcher = iw.pattern.matcher(text); if (matcher.find()) { matchFound = true; String match = matcher.group().trim(); tokens.add(iw.info.getToken(match)); tokens.addAll(parse(text.substring(match.length()))); break; } } if (!matchFound) { throw new DateCalcException("Could not parse the expression: " + text); } } } return tokens; } DateCalcExpressionParser(); } | DateCalcExpressionParser { public Queue<Token> parse(String text) { final Queue<Token> tokens = new ArrayDeque<>(); if (text != null) { text = text.trim(); if (!text.isEmpty()) { boolean matchFound = false; for (InfoWrapper iw : infos) { final Matcher matcher = iw.pattern.matcher(text); if (matcher.find()) { matchFound = true; String match = matcher.group().trim(); tokens.add(iw.info.getToken(match)); tokens.addAll(parse(text.substring(match.length()))); break; } } if (!matchFound) { throw new DateCalcException("Could not parse the expression: " + text); } } } return tokens; } DateCalcExpressionParser(); Queue<Token> parse(String text); } | DateCalcExpressionParser { public Queue<Token> parse(String text) { final Queue<Token> tokens = new ArrayDeque<>(); if (text != null) { text = text.trim(); if (!text.isEmpty()) { boolean matchFound = false; for (InfoWrapper iw : infos) { final Matcher matcher = iw.pattern.matcher(text); if (matcher.find()) { matchFound = true; String match = matcher.group().trim(); tokens.add(iw.info.getToken(match)); tokens.addAll(parse(text.substring(match.length()))); break; } } if (!matchFound) { throw new DateCalcException("Could not parse the expression: " + text); } } } return tokens; } DateCalcExpressionParser(); Queue<Token> parse(String text); } |
@Test public void deleteRecipient() { Recipient recip = new Recipient("SMS", "[email protected]"); dao.saveRecipient(recip); Assert.assertEquals(1, dao.getRecipients().size()); dao.deleteRecipient(recip); Assert.assertEquals(0, dao.getRecipients().size()); } | public void deleteRecipient(Recipient recip) { mapper.delete(recip); } | CloudNoticeDAO { public void deleteRecipient(Recipient recip) { mapper.delete(recip); } } | CloudNoticeDAO { public void deleteRecipient(Recipient recip) { mapper.delete(recip); } CloudNoticeDAO(boolean local); } | CloudNoticeDAO { public void deleteRecipient(Recipient recip) { mapper.delete(recip); } CloudNoticeDAO(boolean local); List<Recipient> getRecipients(); void saveRecipient(Recipient recip); void deleteRecipient(Recipient recip); void shutdown(); } | CloudNoticeDAO { public void deleteRecipient(Recipient recip) { mapper.delete(recip); } CloudNoticeDAO(boolean local); List<Recipient> getRecipients(); void saveRecipient(Recipient recip); void deleteRecipient(Recipient recip); void shutdown(); static final String TABLE_NAME; } |
@Test public void timePlusDuration() { Queue<Token> tokens = parser.parse("12:37+42m"); Assert.assertEquals(tokens.size(), 4); Assert.assertTrue(tokens.poll() instanceof TimeToken); Assert.assertTrue(tokens.poll() instanceof OperatorToken); Assert.assertTrue(tokens.poll() instanceof IntegerToken); Assert.assertTrue(tokens.poll() instanceof UnitOfMeasureToken); } | public Queue<Token> parse(String text) { final Queue<Token> tokens = new ArrayDeque<>(); if (text != null) { text = text.trim(); if (!text.isEmpty()) { boolean matchFound = false; for (InfoWrapper iw : infos) { final Matcher matcher = iw.pattern.matcher(text); if (matcher.find()) { matchFound = true; String match = matcher.group().trim(); tokens.add(iw.info.getToken(match)); tokens.addAll(parse(text.substring(match.length()))); break; } } if (!matchFound) { throw new DateCalcException("Could not parse the expression: " + text); } } } return tokens; } | DateCalcExpressionParser { public Queue<Token> parse(String text) { final Queue<Token> tokens = new ArrayDeque<>(); if (text != null) { text = text.trim(); if (!text.isEmpty()) { boolean matchFound = false; for (InfoWrapper iw : infos) { final Matcher matcher = iw.pattern.matcher(text); if (matcher.find()) { matchFound = true; String match = matcher.group().trim(); tokens.add(iw.info.getToken(match)); tokens.addAll(parse(text.substring(match.length()))); break; } } if (!matchFound) { throw new DateCalcException("Could not parse the expression: " + text); } } } return tokens; } } | DateCalcExpressionParser { public Queue<Token> parse(String text) { final Queue<Token> tokens = new ArrayDeque<>(); if (text != null) { text = text.trim(); if (!text.isEmpty()) { boolean matchFound = false; for (InfoWrapper iw : infos) { final Matcher matcher = iw.pattern.matcher(text); if (matcher.find()) { matchFound = true; String match = matcher.group().trim(); tokens.add(iw.info.getToken(match)); tokens.addAll(parse(text.substring(match.length()))); break; } } if (!matchFound) { throw new DateCalcException("Could not parse the expression: " + text); } } } return tokens; } DateCalcExpressionParser(); } | DateCalcExpressionParser { public Queue<Token> parse(String text) { final Queue<Token> tokens = new ArrayDeque<>(); if (text != null) { text = text.trim(); if (!text.isEmpty()) { boolean matchFound = false; for (InfoWrapper iw : infos) { final Matcher matcher = iw.pattern.matcher(text); if (matcher.find()) { matchFound = true; String match = matcher.group().trim(); tokens.add(iw.info.getToken(match)); tokens.addAll(parse(text.substring(match.length()))); break; } } if (!matchFound) { throw new DateCalcException("Could not parse the expression: " + text); } } } return tokens; } DateCalcExpressionParser(); Queue<Token> parse(String text); } | DateCalcExpressionParser { public Queue<Token> parse(String text) { final Queue<Token> tokens = new ArrayDeque<>(); if (text != null) { text = text.trim(); if (!text.isEmpty()) { boolean matchFound = false; for (InfoWrapper iw : infos) { final Matcher matcher = iw.pattern.matcher(text); if (matcher.find()) { matchFound = true; String match = matcher.group().trim(); tokens.add(iw.info.getToken(match)); tokens.addAll(parse(text.substring(match.length()))); break; } } if (!matchFound) { throw new DateCalcException("Could not parse the expression: " + text); } } } return tokens; } DateCalcExpressionParser(); Queue<Token> parse(String text); } |
@Test public void timePlusDurationWithSpaces() { Queue<Token> tokens = parser.parse("12:37 + 42 m"); Assert.assertEquals(tokens.size(), 4); Assert.assertTrue(tokens.poll() instanceof TimeToken); Assert.assertTrue(tokens.poll() instanceof OperatorToken); Assert.assertTrue(tokens.poll() instanceof IntegerToken); Assert.assertTrue(tokens.poll() instanceof UnitOfMeasureToken); } | public Queue<Token> parse(String text) { final Queue<Token> tokens = new ArrayDeque<>(); if (text != null) { text = text.trim(); if (!text.isEmpty()) { boolean matchFound = false; for (InfoWrapper iw : infos) { final Matcher matcher = iw.pattern.matcher(text); if (matcher.find()) { matchFound = true; String match = matcher.group().trim(); tokens.add(iw.info.getToken(match)); tokens.addAll(parse(text.substring(match.length()))); break; } } if (!matchFound) { throw new DateCalcException("Could not parse the expression: " + text); } } } return tokens; } | DateCalcExpressionParser { public Queue<Token> parse(String text) { final Queue<Token> tokens = new ArrayDeque<>(); if (text != null) { text = text.trim(); if (!text.isEmpty()) { boolean matchFound = false; for (InfoWrapper iw : infos) { final Matcher matcher = iw.pattern.matcher(text); if (matcher.find()) { matchFound = true; String match = matcher.group().trim(); tokens.add(iw.info.getToken(match)); tokens.addAll(parse(text.substring(match.length()))); break; } } if (!matchFound) { throw new DateCalcException("Could not parse the expression: " + text); } } } return tokens; } } | DateCalcExpressionParser { public Queue<Token> parse(String text) { final Queue<Token> tokens = new ArrayDeque<>(); if (text != null) { text = text.trim(); if (!text.isEmpty()) { boolean matchFound = false; for (InfoWrapper iw : infos) { final Matcher matcher = iw.pattern.matcher(text); if (matcher.find()) { matchFound = true; String match = matcher.group().trim(); tokens.add(iw.info.getToken(match)); tokens.addAll(parse(text.substring(match.length()))); break; } } if (!matchFound) { throw new DateCalcException("Could not parse the expression: " + text); } } } return tokens; } DateCalcExpressionParser(); } | DateCalcExpressionParser { public Queue<Token> parse(String text) { final Queue<Token> tokens = new ArrayDeque<>(); if (text != null) { text = text.trim(); if (!text.isEmpty()) { boolean matchFound = false; for (InfoWrapper iw : infos) { final Matcher matcher = iw.pattern.matcher(text); if (matcher.find()) { matchFound = true; String match = matcher.group().trim(); tokens.add(iw.info.getToken(match)); tokens.addAll(parse(text.substring(match.length()))); break; } } if (!matchFound) { throw new DateCalcException("Could not parse the expression: " + text); } } } return tokens; } DateCalcExpressionParser(); Queue<Token> parse(String text); } | DateCalcExpressionParser { public Queue<Token> parse(String text) { final Queue<Token> tokens = new ArrayDeque<>(); if (text != null) { text = text.trim(); if (!text.isEmpty()) { boolean matchFound = false; for (InfoWrapper iw : infos) { final Matcher matcher = iw.pattern.matcher(text); if (matcher.find()) { matchFound = true; String match = matcher.group().trim(); tokens.add(iw.info.getToken(match)); tokens.addAll(parse(text.substring(match.length()))); break; } } if (!matchFound) { throw new DateCalcException("Could not parse the expression: " + text); } } } return tokens; } DateCalcExpressionParser(); Queue<Token> parse(String text); } |
@Test public void invalidStringsShouldFail() { try { parser.parse("2016/12/25 this is nonsense"); Assert.fail("A DateCalcException should have been thrown (Unable to identify token)"); } catch (DateCalcException dce) { } } | public Queue<Token> parse(String text) { final Queue<Token> tokens = new ArrayDeque<>(); if (text != null) { text = text.trim(); if (!text.isEmpty()) { boolean matchFound = false; for (InfoWrapper iw : infos) { final Matcher matcher = iw.pattern.matcher(text); if (matcher.find()) { matchFound = true; String match = matcher.group().trim(); tokens.add(iw.info.getToken(match)); tokens.addAll(parse(text.substring(match.length()))); break; } } if (!matchFound) { throw new DateCalcException("Could not parse the expression: " + text); } } } return tokens; } | DateCalcExpressionParser { public Queue<Token> parse(String text) { final Queue<Token> tokens = new ArrayDeque<>(); if (text != null) { text = text.trim(); if (!text.isEmpty()) { boolean matchFound = false; for (InfoWrapper iw : infos) { final Matcher matcher = iw.pattern.matcher(text); if (matcher.find()) { matchFound = true; String match = matcher.group().trim(); tokens.add(iw.info.getToken(match)); tokens.addAll(parse(text.substring(match.length()))); break; } } if (!matchFound) { throw new DateCalcException("Could not parse the expression: " + text); } } } return tokens; } } | DateCalcExpressionParser { public Queue<Token> parse(String text) { final Queue<Token> tokens = new ArrayDeque<>(); if (text != null) { text = text.trim(); if (!text.isEmpty()) { boolean matchFound = false; for (InfoWrapper iw : infos) { final Matcher matcher = iw.pattern.matcher(text); if (matcher.find()) { matchFound = true; String match = matcher.group().trim(); tokens.add(iw.info.getToken(match)); tokens.addAll(parse(text.substring(match.length()))); break; } } if (!matchFound) { throw new DateCalcException("Could not parse the expression: " + text); } } } return tokens; } DateCalcExpressionParser(); } | DateCalcExpressionParser { public Queue<Token> parse(String text) { final Queue<Token> tokens = new ArrayDeque<>(); if (text != null) { text = text.trim(); if (!text.isEmpty()) { boolean matchFound = false; for (InfoWrapper iw : infos) { final Matcher matcher = iw.pattern.matcher(text); if (matcher.find()) { matchFound = true; String match = matcher.group().trim(); tokens.add(iw.info.getToken(match)); tokens.addAll(parse(text.substring(match.length()))); break; } } if (!matchFound) { throw new DateCalcException("Could not parse the expression: " + text); } } } return tokens; } DateCalcExpressionParser(); Queue<Token> parse(String text); } | DateCalcExpressionParser { public Queue<Token> parse(String text) { final Queue<Token> tokens = new ArrayDeque<>(); if (text != null) { text = text.trim(); if (!text.isEmpty()) { boolean matchFound = false; for (InfoWrapper iw : infos) { final Matcher matcher = iw.pattern.matcher(text); if (matcher.find()) { matchFound = true; String match = matcher.group().trim(); tokens.add(iw.info.getToken(match)); tokens.addAll(parse(text.substring(match.length()))); break; } } if (!matchFound) { throw new DateCalcException("Could not parse the expression: " + text); } } } return tokens; } DateCalcExpressionParser(); Queue<Token> parse(String text); } |
@Test public void testWithAm() { Queue<Token> words = parser.parse("12:37am"); Assert.assertEquals(words.size(), 1); Assert.assertTrue(words.poll() instanceof TimeToken); } | public Queue<Token> parse(String text) { final Queue<Token> tokens = new ArrayDeque<>(); if (text != null) { text = text.trim(); if (!text.isEmpty()) { boolean matchFound = false; for (InfoWrapper iw : infos) { final Matcher matcher = iw.pattern.matcher(text); if (matcher.find()) { matchFound = true; String match = matcher.group().trim(); tokens.add(iw.info.getToken(match)); tokens.addAll(parse(text.substring(match.length()))); break; } } if (!matchFound) { throw new DateCalcException("Could not parse the expression: " + text); } } } return tokens; } | DateCalcExpressionParser { public Queue<Token> parse(String text) { final Queue<Token> tokens = new ArrayDeque<>(); if (text != null) { text = text.trim(); if (!text.isEmpty()) { boolean matchFound = false; for (InfoWrapper iw : infos) { final Matcher matcher = iw.pattern.matcher(text); if (matcher.find()) { matchFound = true; String match = matcher.group().trim(); tokens.add(iw.info.getToken(match)); tokens.addAll(parse(text.substring(match.length()))); break; } } if (!matchFound) { throw new DateCalcException("Could not parse the expression: " + text); } } } return tokens; } } | DateCalcExpressionParser { public Queue<Token> parse(String text) { final Queue<Token> tokens = new ArrayDeque<>(); if (text != null) { text = text.trim(); if (!text.isEmpty()) { boolean matchFound = false; for (InfoWrapper iw : infos) { final Matcher matcher = iw.pattern.matcher(text); if (matcher.find()) { matchFound = true; String match = matcher.group().trim(); tokens.add(iw.info.getToken(match)); tokens.addAll(parse(text.substring(match.length()))); break; } } if (!matchFound) { throw new DateCalcException("Could not parse the expression: " + text); } } } return tokens; } DateCalcExpressionParser(); } | DateCalcExpressionParser { public Queue<Token> parse(String text) { final Queue<Token> tokens = new ArrayDeque<>(); if (text != null) { text = text.trim(); if (!text.isEmpty()) { boolean matchFound = false; for (InfoWrapper iw : infos) { final Matcher matcher = iw.pattern.matcher(text); if (matcher.find()) { matchFound = true; String match = matcher.group().trim(); tokens.add(iw.info.getToken(match)); tokens.addAll(parse(text.substring(match.length()))); break; } } if (!matchFound) { throw new DateCalcException("Could not parse the expression: " + text); } } } return tokens; } DateCalcExpressionParser(); Queue<Token> parse(String text); } | DateCalcExpressionParser { public Queue<Token> parse(String text) { final Queue<Token> tokens = new ArrayDeque<>(); if (text != null) { text = text.trim(); if (!text.isEmpty()) { boolean matchFound = false; for (InfoWrapper iw : infos) { final Matcher matcher = iw.pattern.matcher(text); if (matcher.find()) { matchFound = true; String match = matcher.group().trim(); tokens.add(iw.info.getToken(match)); tokens.addAll(parse(text.substring(match.length()))); break; } } if (!matchFound) { throw new DateCalcException("Could not parse the expression: " + text); } } } return tokens; } DateCalcExpressionParser(); Queue<Token> parse(String text); } |
@Test public void testTimeDiffWithAm() { Queue<Token> words = parser.parse("12:37am-5:00am"); Assert.assertEquals(words.size(), 3); Assert.assertTrue(words.poll() instanceof TimeToken); Assert.assertTrue(words.poll() instanceof OperatorToken); Assert.assertTrue(words.poll() instanceof TimeToken); } | public Queue<Token> parse(String text) { final Queue<Token> tokens = new ArrayDeque<>(); if (text != null) { text = text.trim(); if (!text.isEmpty()) { boolean matchFound = false; for (InfoWrapper iw : infos) { final Matcher matcher = iw.pattern.matcher(text); if (matcher.find()) { matchFound = true; String match = matcher.group().trim(); tokens.add(iw.info.getToken(match)); tokens.addAll(parse(text.substring(match.length()))); break; } } if (!matchFound) { throw new DateCalcException("Could not parse the expression: " + text); } } } return tokens; } | DateCalcExpressionParser { public Queue<Token> parse(String text) { final Queue<Token> tokens = new ArrayDeque<>(); if (text != null) { text = text.trim(); if (!text.isEmpty()) { boolean matchFound = false; for (InfoWrapper iw : infos) { final Matcher matcher = iw.pattern.matcher(text); if (matcher.find()) { matchFound = true; String match = matcher.group().trim(); tokens.add(iw.info.getToken(match)); tokens.addAll(parse(text.substring(match.length()))); break; } } if (!matchFound) { throw new DateCalcException("Could not parse the expression: " + text); } } } return tokens; } } | DateCalcExpressionParser { public Queue<Token> parse(String text) { final Queue<Token> tokens = new ArrayDeque<>(); if (text != null) { text = text.trim(); if (!text.isEmpty()) { boolean matchFound = false; for (InfoWrapper iw : infos) { final Matcher matcher = iw.pattern.matcher(text); if (matcher.find()) { matchFound = true; String match = matcher.group().trim(); tokens.add(iw.info.getToken(match)); tokens.addAll(parse(text.substring(match.length()))); break; } } if (!matchFound) { throw new DateCalcException("Could not parse the expression: " + text); } } } return tokens; } DateCalcExpressionParser(); } | DateCalcExpressionParser { public Queue<Token> parse(String text) { final Queue<Token> tokens = new ArrayDeque<>(); if (text != null) { text = text.trim(); if (!text.isEmpty()) { boolean matchFound = false; for (InfoWrapper iw : infos) { final Matcher matcher = iw.pattern.matcher(text); if (matcher.find()) { matchFound = true; String match = matcher.group().trim(); tokens.add(iw.info.getToken(match)); tokens.addAll(parse(text.substring(match.length()))); break; } } if (!matchFound) { throw new DateCalcException("Could not parse the expression: " + text); } } } return tokens; } DateCalcExpressionParser(); Queue<Token> parse(String text); } | DateCalcExpressionParser { public Queue<Token> parse(String text) { final Queue<Token> tokens = new ArrayDeque<>(); if (text != null) { text = text.trim(); if (!text.isEmpty()) { boolean matchFound = false; for (InfoWrapper iw : infos) { final Matcher matcher = iw.pattern.matcher(text); if (matcher.find()) { matchFound = true; String match = matcher.group().trim(); tokens.add(iw.info.getToken(match)); tokens.addAll(parse(text.substring(match.length()))); break; } } if (!matchFound) { throw new DateCalcException("Could not parse the expression: " + text); } } } return tokens; } DateCalcExpressionParser(); Queue<Token> parse(String text); } |
@Test(expectedExceptions = {DateCalcException.class}) public void shouldRejectBadTimes() { parser.parse("22:89"); } | public Queue<Token> parse(String text) { final Queue<Token> tokens = new ArrayDeque<>(); if (text != null) { text = text.trim(); if (!text.isEmpty()) { boolean matchFound = false; for (InfoWrapper iw : infos) { final Matcher matcher = iw.pattern.matcher(text); if (matcher.find()) { matchFound = true; String match = matcher.group().trim(); tokens.add(iw.info.getToken(match)); tokens.addAll(parse(text.substring(match.length()))); break; } } if (!matchFound) { throw new DateCalcException("Could not parse the expression: " + text); } } } return tokens; } | DateCalcExpressionParser { public Queue<Token> parse(String text) { final Queue<Token> tokens = new ArrayDeque<>(); if (text != null) { text = text.trim(); if (!text.isEmpty()) { boolean matchFound = false; for (InfoWrapper iw : infos) { final Matcher matcher = iw.pattern.matcher(text); if (matcher.find()) { matchFound = true; String match = matcher.group().trim(); tokens.add(iw.info.getToken(match)); tokens.addAll(parse(text.substring(match.length()))); break; } } if (!matchFound) { throw new DateCalcException("Could not parse the expression: " + text); } } } return tokens; } } | DateCalcExpressionParser { public Queue<Token> parse(String text) { final Queue<Token> tokens = new ArrayDeque<>(); if (text != null) { text = text.trim(); if (!text.isEmpty()) { boolean matchFound = false; for (InfoWrapper iw : infos) { final Matcher matcher = iw.pattern.matcher(text); if (matcher.find()) { matchFound = true; String match = matcher.group().trim(); tokens.add(iw.info.getToken(match)); tokens.addAll(parse(text.substring(match.length()))); break; } } if (!matchFound) { throw new DateCalcException("Could not parse the expression: " + text); } } } return tokens; } DateCalcExpressionParser(); } | DateCalcExpressionParser { public Queue<Token> parse(String text) { final Queue<Token> tokens = new ArrayDeque<>(); if (text != null) { text = text.trim(); if (!text.isEmpty()) { boolean matchFound = false; for (InfoWrapper iw : infos) { final Matcher matcher = iw.pattern.matcher(text); if (matcher.find()) { matchFound = true; String match = matcher.group().trim(); tokens.add(iw.info.getToken(match)); tokens.addAll(parse(text.substring(match.length()))); break; } } if (!matchFound) { throw new DateCalcException("Could not parse the expression: " + text); } } } return tokens; } DateCalcExpressionParser(); Queue<Token> parse(String text); } | DateCalcExpressionParser { public Queue<Token> parse(String text) { final Queue<Token> tokens = new ArrayDeque<>(); if (text != null) { text = text.trim(); if (!text.isEmpty()) { boolean matchFound = false; for (InfoWrapper iw : infos) { final Matcher matcher = iw.pattern.matcher(text); if (matcher.find()) { matchFound = true; String match = matcher.group().trim(); tokens.add(iw.info.getToken(match)); tokens.addAll(parse(text.substring(match.length()))); break; } } if (!matchFound) { throw new DateCalcException("Could not parse the expression: " + text); } } } return tokens; } DateCalcExpressionParser(); Queue<Token> parse(String text); } |
@Test public void paddedWithSpaces() { parser.parse(" now + 15 weeks "); } | public Queue<Token> parse(String text) { final Queue<Token> tokens = new ArrayDeque<>(); if (text != null) { text = text.trim(); if (!text.isEmpty()) { boolean matchFound = false; for (InfoWrapper iw : infos) { final Matcher matcher = iw.pattern.matcher(text); if (matcher.find()) { matchFound = true; String match = matcher.group().trim(); tokens.add(iw.info.getToken(match)); tokens.addAll(parse(text.substring(match.length()))); break; } } if (!matchFound) { throw new DateCalcException("Could not parse the expression: " + text); } } } return tokens; } | DateCalcExpressionParser { public Queue<Token> parse(String text) { final Queue<Token> tokens = new ArrayDeque<>(); if (text != null) { text = text.trim(); if (!text.isEmpty()) { boolean matchFound = false; for (InfoWrapper iw : infos) { final Matcher matcher = iw.pattern.matcher(text); if (matcher.find()) { matchFound = true; String match = matcher.group().trim(); tokens.add(iw.info.getToken(match)); tokens.addAll(parse(text.substring(match.length()))); break; } } if (!matchFound) { throw new DateCalcException("Could not parse the expression: " + text); } } } return tokens; } } | DateCalcExpressionParser { public Queue<Token> parse(String text) { final Queue<Token> tokens = new ArrayDeque<>(); if (text != null) { text = text.trim(); if (!text.isEmpty()) { boolean matchFound = false; for (InfoWrapper iw : infos) { final Matcher matcher = iw.pattern.matcher(text); if (matcher.find()) { matchFound = true; String match = matcher.group().trim(); tokens.add(iw.info.getToken(match)); tokens.addAll(parse(text.substring(match.length()))); break; } } if (!matchFound) { throw new DateCalcException("Could not parse the expression: " + text); } } } return tokens; } DateCalcExpressionParser(); } | DateCalcExpressionParser { public Queue<Token> parse(String text) { final Queue<Token> tokens = new ArrayDeque<>(); if (text != null) { text = text.trim(); if (!text.isEmpty()) { boolean matchFound = false; for (InfoWrapper iw : infos) { final Matcher matcher = iw.pattern.matcher(text); if (matcher.find()) { matchFound = true; String match = matcher.group().trim(); tokens.add(iw.info.getToken(match)); tokens.addAll(parse(text.substring(match.length()))); break; } } if (!matchFound) { throw new DateCalcException("Could not parse the expression: " + text); } } } return tokens; } DateCalcExpressionParser(); Queue<Token> parse(String text); } | DateCalcExpressionParser { public Queue<Token> parse(String text) { final Queue<Token> tokens = new ArrayDeque<>(); if (text != null) { text = text.trim(); if (!text.isEmpty()) { boolean matchFound = false; for (InfoWrapper iw : infos) { final Matcher matcher = iw.pattern.matcher(text); if (matcher.find()) { matchFound = true; String match = matcher.group().trim(); tokens.add(iw.info.getToken(match)); tokens.addAll(parse(text.substring(match.length()))); break; } } if (!matchFound) { throw new DateCalcException("Could not parse the expression: " + text); } } } return tokens; } DateCalcExpressionParser(); Queue<Token> parse(String text); } |
@Test public void testDateMath() { final String expression = "today + 2 weeks 3 days"; DateCalculatorResult result = dc.calculate(expression); Assert.assertNotNull(result.getDate().get(), "'" + expression + "' should have returned a result."); } | public DateCalculatorResult calculate(String text) { final DateCalcExpressionParser parser = new DateCalcExpressionParser(); final Queue<Token> tokens = parser.parse(text); try { if (!tokens.isEmpty()) { if (tokens.peek() instanceof DateToken) { return handleDateExpression(tokens); } else if (tokens.peek() instanceof TimeToken) { return handleTimeExpression(tokens); } } } catch (UnsupportedTemporalTypeException utte) { throw new DateCalcException(utte.getLocalizedMessage()); } throw new DateCalcException("An invalid expression was given: " + text); } | DateCalculator { public DateCalculatorResult calculate(String text) { final DateCalcExpressionParser parser = new DateCalcExpressionParser(); final Queue<Token> tokens = parser.parse(text); try { if (!tokens.isEmpty()) { if (tokens.peek() instanceof DateToken) { return handleDateExpression(tokens); } else if (tokens.peek() instanceof TimeToken) { return handleTimeExpression(tokens); } } } catch (UnsupportedTemporalTypeException utte) { throw new DateCalcException(utte.getLocalizedMessage()); } throw new DateCalcException("An invalid expression was given: " + text); } } | DateCalculator { public DateCalculatorResult calculate(String text) { final DateCalcExpressionParser parser = new DateCalcExpressionParser(); final Queue<Token> tokens = parser.parse(text); try { if (!tokens.isEmpty()) { if (tokens.peek() instanceof DateToken) { return handleDateExpression(tokens); } else if (tokens.peek() instanceof TimeToken) { return handleTimeExpression(tokens); } } } catch (UnsupportedTemporalTypeException utte) { throw new DateCalcException(utte.getLocalizedMessage()); } throw new DateCalcException("An invalid expression was given: " + text); } } | DateCalculator { public DateCalculatorResult calculate(String text) { final DateCalcExpressionParser parser = new DateCalcExpressionParser(); final Queue<Token> tokens = parser.parse(text); try { if (!tokens.isEmpty()) { if (tokens.peek() instanceof DateToken) { return handleDateExpression(tokens); } else if (tokens.peek() instanceof TimeToken) { return handleTimeExpression(tokens); } } } catch (UnsupportedTemporalTypeException utte) { throw new DateCalcException(utte.getLocalizedMessage()); } throw new DateCalcException("An invalid expression was given: " + text); } DateCalculatorResult calculate(String text); } | DateCalculator { public DateCalculatorResult calculate(String text) { final DateCalcExpressionParser parser = new DateCalcExpressionParser(); final Queue<Token> tokens = parser.parse(text); try { if (!tokens.isEmpty()) { if (tokens.peek() instanceof DateToken) { return handleDateExpression(tokens); } else if (tokens.peek() instanceof TimeToken) { return handleTimeExpression(tokens); } } } catch (UnsupportedTemporalTypeException utte) { throw new DateCalcException(utte.getLocalizedMessage()); } throw new DateCalcException("An invalid expression was given: " + text); } DateCalculatorResult calculate(String text); } |
@Test public void testDateDiff() { final String expression = "2016/07/04 - 1776/07/04"; DateCalculatorResult result = dc.calculate(expression); Assert.assertEquals(result.getPeriod().get(), Period.of(240,0,0), "'" + expression + "' should..."); } | public DateCalculatorResult calculate(String text) { final DateCalcExpressionParser parser = new DateCalcExpressionParser(); final Queue<Token> tokens = parser.parse(text); try { if (!tokens.isEmpty()) { if (tokens.peek() instanceof DateToken) { return handleDateExpression(tokens); } else if (tokens.peek() instanceof TimeToken) { return handleTimeExpression(tokens); } } } catch (UnsupportedTemporalTypeException utte) { throw new DateCalcException(utte.getLocalizedMessage()); } throw new DateCalcException("An invalid expression was given: " + text); } | DateCalculator { public DateCalculatorResult calculate(String text) { final DateCalcExpressionParser parser = new DateCalcExpressionParser(); final Queue<Token> tokens = parser.parse(text); try { if (!tokens.isEmpty()) { if (tokens.peek() instanceof DateToken) { return handleDateExpression(tokens); } else if (tokens.peek() instanceof TimeToken) { return handleTimeExpression(tokens); } } } catch (UnsupportedTemporalTypeException utte) { throw new DateCalcException(utte.getLocalizedMessage()); } throw new DateCalcException("An invalid expression was given: " + text); } } | DateCalculator { public DateCalculatorResult calculate(String text) { final DateCalcExpressionParser parser = new DateCalcExpressionParser(); final Queue<Token> tokens = parser.parse(text); try { if (!tokens.isEmpty()) { if (tokens.peek() instanceof DateToken) { return handleDateExpression(tokens); } else if (tokens.peek() instanceof TimeToken) { return handleTimeExpression(tokens); } } } catch (UnsupportedTemporalTypeException utte) { throw new DateCalcException(utte.getLocalizedMessage()); } throw new DateCalcException("An invalid expression was given: " + text); } } | DateCalculator { public DateCalculatorResult calculate(String text) { final DateCalcExpressionParser parser = new DateCalcExpressionParser(); final Queue<Token> tokens = parser.parse(text); try { if (!tokens.isEmpty()) { if (tokens.peek() instanceof DateToken) { return handleDateExpression(tokens); } else if (tokens.peek() instanceof TimeToken) { return handleTimeExpression(tokens); } } } catch (UnsupportedTemporalTypeException utte) { throw new DateCalcException(utte.getLocalizedMessage()); } throw new DateCalcException("An invalid expression was given: " + text); } DateCalculatorResult calculate(String text); } | DateCalculator { public DateCalculatorResult calculate(String text) { final DateCalcExpressionParser parser = new DateCalcExpressionParser(); final Queue<Token> tokens = parser.parse(text); try { if (!tokens.isEmpty()) { if (tokens.peek() instanceof DateToken) { return handleDateExpression(tokens); } else if (tokens.peek() instanceof TimeToken) { return handleTimeExpression(tokens); } } } catch (UnsupportedTemporalTypeException utte) { throw new DateCalcException(utte.getLocalizedMessage()); } throw new DateCalcException("An invalid expression was given: " + text); } DateCalculatorResult calculate(String text); } |
@Test public void timeMath() { final String expression = "12:37 + 42 m"; DateCalculatorResult result = dc.calculate(expression); Assert.assertEquals(result.getTime().get(), LocalTime.parse("13:19")); } | public DateCalculatorResult calculate(String text) { final DateCalcExpressionParser parser = new DateCalcExpressionParser(); final Queue<Token> tokens = parser.parse(text); try { if (!tokens.isEmpty()) { if (tokens.peek() instanceof DateToken) { return handleDateExpression(tokens); } else if (tokens.peek() instanceof TimeToken) { return handleTimeExpression(tokens); } } } catch (UnsupportedTemporalTypeException utte) { throw new DateCalcException(utte.getLocalizedMessage()); } throw new DateCalcException("An invalid expression was given: " + text); } | DateCalculator { public DateCalculatorResult calculate(String text) { final DateCalcExpressionParser parser = new DateCalcExpressionParser(); final Queue<Token> tokens = parser.parse(text); try { if (!tokens.isEmpty()) { if (tokens.peek() instanceof DateToken) { return handleDateExpression(tokens); } else if (tokens.peek() instanceof TimeToken) { return handleTimeExpression(tokens); } } } catch (UnsupportedTemporalTypeException utte) { throw new DateCalcException(utte.getLocalizedMessage()); } throw new DateCalcException("An invalid expression was given: " + text); } } | DateCalculator { public DateCalculatorResult calculate(String text) { final DateCalcExpressionParser parser = new DateCalcExpressionParser(); final Queue<Token> tokens = parser.parse(text); try { if (!tokens.isEmpty()) { if (tokens.peek() instanceof DateToken) { return handleDateExpression(tokens); } else if (tokens.peek() instanceof TimeToken) { return handleTimeExpression(tokens); } } } catch (UnsupportedTemporalTypeException utte) { throw new DateCalcException(utte.getLocalizedMessage()); } throw new DateCalcException("An invalid expression was given: " + text); } } | DateCalculator { public DateCalculatorResult calculate(String text) { final DateCalcExpressionParser parser = new DateCalcExpressionParser(); final Queue<Token> tokens = parser.parse(text); try { if (!tokens.isEmpty()) { if (tokens.peek() instanceof DateToken) { return handleDateExpression(tokens); } else if (tokens.peek() instanceof TimeToken) { return handleTimeExpression(tokens); } } } catch (UnsupportedTemporalTypeException utte) { throw new DateCalcException(utte.getLocalizedMessage()); } throw new DateCalcException("An invalid expression was given: " + text); } DateCalculatorResult calculate(String text); } | DateCalculator { public DateCalculatorResult calculate(String text) { final DateCalcExpressionParser parser = new DateCalcExpressionParser(); final Queue<Token> tokens = parser.parse(text); try { if (!tokens.isEmpty()) { if (tokens.peek() instanceof DateToken) { return handleDateExpression(tokens); } else if (tokens.peek() instanceof TimeToken) { return handleTimeExpression(tokens); } } } catch (UnsupportedTemporalTypeException utte) { throw new DateCalcException(utte.getLocalizedMessage()); } throw new DateCalcException("An invalid expression was given: " + text); } DateCalculatorResult calculate(String text); } |
@Test public void timeDiff() { final String expression = "12:37 - 7:15"; DateCalculatorResult result = dc.calculate(expression); Assert.assertEquals(result.getDuration().get().toHoursPart(), 5); Assert.assertEquals(result.getDuration().get().toMinutesPart(), 22); } | public DateCalculatorResult calculate(String text) { final DateCalcExpressionParser parser = new DateCalcExpressionParser(); final Queue<Token> tokens = parser.parse(text); try { if (!tokens.isEmpty()) { if (tokens.peek() instanceof DateToken) { return handleDateExpression(tokens); } else if (tokens.peek() instanceof TimeToken) { return handleTimeExpression(tokens); } } } catch (UnsupportedTemporalTypeException utte) { throw new DateCalcException(utte.getLocalizedMessage()); } throw new DateCalcException("An invalid expression was given: " + text); } | DateCalculator { public DateCalculatorResult calculate(String text) { final DateCalcExpressionParser parser = new DateCalcExpressionParser(); final Queue<Token> tokens = parser.parse(text); try { if (!tokens.isEmpty()) { if (tokens.peek() instanceof DateToken) { return handleDateExpression(tokens); } else if (tokens.peek() instanceof TimeToken) { return handleTimeExpression(tokens); } } } catch (UnsupportedTemporalTypeException utte) { throw new DateCalcException(utte.getLocalizedMessage()); } throw new DateCalcException("An invalid expression was given: " + text); } } | DateCalculator { public DateCalculatorResult calculate(String text) { final DateCalcExpressionParser parser = new DateCalcExpressionParser(); final Queue<Token> tokens = parser.parse(text); try { if (!tokens.isEmpty()) { if (tokens.peek() instanceof DateToken) { return handleDateExpression(tokens); } else if (tokens.peek() instanceof TimeToken) { return handleTimeExpression(tokens); } } } catch (UnsupportedTemporalTypeException utte) { throw new DateCalcException(utte.getLocalizedMessage()); } throw new DateCalcException("An invalid expression was given: " + text); } } | DateCalculator { public DateCalculatorResult calculate(String text) { final DateCalcExpressionParser parser = new DateCalcExpressionParser(); final Queue<Token> tokens = parser.parse(text); try { if (!tokens.isEmpty()) { if (tokens.peek() instanceof DateToken) { return handleDateExpression(tokens); } else if (tokens.peek() instanceof TimeToken) { return handleTimeExpression(tokens); } } } catch (UnsupportedTemporalTypeException utte) { throw new DateCalcException(utte.getLocalizedMessage()); } throw new DateCalcException("An invalid expression was given: " + text); } DateCalculatorResult calculate(String text); } | DateCalculator { public DateCalculatorResult calculate(String text) { final DateCalcExpressionParser parser = new DateCalcExpressionParser(); final Queue<Token> tokens = parser.parse(text); try { if (!tokens.isEmpty()) { if (tokens.peek() instanceof DateToken) { return handleDateExpression(tokens); } else if (tokens.peek() instanceof TimeToken) { return handleTimeExpression(tokens); } } } catch (UnsupportedTemporalTypeException utte) { throw new DateCalcException(utte.getLocalizedMessage()); } throw new DateCalcException("An invalid expression was given: " + text); } DateCalculatorResult calculate(String text); } |
@Test public void todayWithSpaces() { Queue<Token> words = parser.parse("today + 2 weeks"); Assert.assertTrue(words.poll() instanceof DateToken); Assert.assertTrue(words.poll() instanceof OperatorToken); Assert.assertTrue(words.poll() instanceof IntegerToken); Assert.assertTrue(words.poll() instanceof UnitOfMeasureToken); } | public Queue<Token> parse(String text) { final Queue<Token> tokens = new ArrayDeque<>(); if (text != null) { text = text.trim(); if (!text.isEmpty()) { boolean matchFound = false; for (InfoWrapper iw : infos) { final Matcher matcher = iw.pattern.matcher(text); if (matcher.find()) { matchFound = true; String match = matcher.group().trim(); tokens.add(iw.info.getToken(match)); tokens.addAll(parse(text.substring(match.length()))); break; } } if (!matchFound) { throw new DateCalcException("Could not parse the expression: " + text); } } } return tokens; } | DateCalcExpressionParser { public Queue<Token> parse(String text) { final Queue<Token> tokens = new ArrayDeque<>(); if (text != null) { text = text.trim(); if (!text.isEmpty()) { boolean matchFound = false; for (InfoWrapper iw : infos) { final Matcher matcher = iw.pattern.matcher(text); if (matcher.find()) { matchFound = true; String match = matcher.group().trim(); tokens.add(iw.info.getToken(match)); tokens.addAll(parse(text.substring(match.length()))); break; } } if (!matchFound) { throw new DateCalcException("Could not parse the expression: " + text); } } } return tokens; } } | DateCalcExpressionParser { public Queue<Token> parse(String text) { final Queue<Token> tokens = new ArrayDeque<>(); if (text != null) { text = text.trim(); if (!text.isEmpty()) { boolean matchFound = false; for (InfoWrapper iw : infos) { final Matcher matcher = iw.pattern.matcher(text); if (matcher.find()) { matchFound = true; String match = matcher.group().trim(); tokens.add(iw.info.getToken(match)); tokens.addAll(parse(text.substring(match.length()))); break; } } if (!matchFound) { throw new DateCalcException("Could not parse the expression: " + text); } } } return tokens; } DateCalcExpressionParser(); } | DateCalcExpressionParser { public Queue<Token> parse(String text) { final Queue<Token> tokens = new ArrayDeque<>(); if (text != null) { text = text.trim(); if (!text.isEmpty()) { boolean matchFound = false; for (InfoWrapper iw : infos) { final Matcher matcher = iw.pattern.matcher(text); if (matcher.find()) { matchFound = true; String match = matcher.group().trim(); tokens.add(iw.info.getToken(match)); tokens.addAll(parse(text.substring(match.length()))); break; } } if (!matchFound) { throw new DateCalcException("Could not parse the expression: " + text); } } } return tokens; } DateCalcExpressionParser(); Queue<Token> parse(String text); } | DateCalcExpressionParser { public Queue<Token> parse(String text) { final Queue<Token> tokens = new ArrayDeque<>(); if (text != null) { text = text.trim(); if (!text.isEmpty()) { boolean matchFound = false; for (InfoWrapper iw : infos) { final Matcher matcher = iw.pattern.matcher(text); if (matcher.find()) { matchFound = true; String match = matcher.group().trim(); tokens.add(iw.info.getToken(match)); tokens.addAll(parse(text.substring(match.length()))); break; } } if (!matchFound) { throw new DateCalcException("Could not parse the expression: " + text); } } } return tokens; } DateCalcExpressionParser(); Queue<Token> parse(String text); } |
@Test public void todayWithoutSpaces() { Queue<Token> words = parser.parse("today+2w"); Assert.assertTrue(words.poll() instanceof DateToken); Assert.assertTrue(words.poll() instanceof OperatorToken); Assert.assertTrue(words.poll() instanceof IntegerToken); Assert.assertTrue(words.poll() instanceof UnitOfMeasureToken); } | public Queue<Token> parse(String text) { final Queue<Token> tokens = new ArrayDeque<>(); if (text != null) { text = text.trim(); if (!text.isEmpty()) { boolean matchFound = false; for (InfoWrapper iw : infos) { final Matcher matcher = iw.pattern.matcher(text); if (matcher.find()) { matchFound = true; String match = matcher.group().trim(); tokens.add(iw.info.getToken(match)); tokens.addAll(parse(text.substring(match.length()))); break; } } if (!matchFound) { throw new DateCalcException("Could not parse the expression: " + text); } } } return tokens; } | DateCalcExpressionParser { public Queue<Token> parse(String text) { final Queue<Token> tokens = new ArrayDeque<>(); if (text != null) { text = text.trim(); if (!text.isEmpty()) { boolean matchFound = false; for (InfoWrapper iw : infos) { final Matcher matcher = iw.pattern.matcher(text); if (matcher.find()) { matchFound = true; String match = matcher.group().trim(); tokens.add(iw.info.getToken(match)); tokens.addAll(parse(text.substring(match.length()))); break; } } if (!matchFound) { throw new DateCalcException("Could not parse the expression: " + text); } } } return tokens; } } | DateCalcExpressionParser { public Queue<Token> parse(String text) { final Queue<Token> tokens = new ArrayDeque<>(); if (text != null) { text = text.trim(); if (!text.isEmpty()) { boolean matchFound = false; for (InfoWrapper iw : infos) { final Matcher matcher = iw.pattern.matcher(text); if (matcher.find()) { matchFound = true; String match = matcher.group().trim(); tokens.add(iw.info.getToken(match)); tokens.addAll(parse(text.substring(match.length()))); break; } } if (!matchFound) { throw new DateCalcException("Could not parse the expression: " + text); } } } return tokens; } DateCalcExpressionParser(); } | DateCalcExpressionParser { public Queue<Token> parse(String text) { final Queue<Token> tokens = new ArrayDeque<>(); if (text != null) { text = text.trim(); if (!text.isEmpty()) { boolean matchFound = false; for (InfoWrapper iw : infos) { final Matcher matcher = iw.pattern.matcher(text); if (matcher.find()) { matchFound = true; String match = matcher.group().trim(); tokens.add(iw.info.getToken(match)); tokens.addAll(parse(text.substring(match.length()))); break; } } if (!matchFound) { throw new DateCalcException("Could not parse the expression: " + text); } } } return tokens; } DateCalcExpressionParser(); Queue<Token> parse(String text); } | DateCalcExpressionParser { public Queue<Token> parse(String text) { final Queue<Token> tokens = new ArrayDeque<>(); if (text != null) { text = text.trim(); if (!text.isEmpty()) { boolean matchFound = false; for (InfoWrapper iw : infos) { final Matcher matcher = iw.pattern.matcher(text); if (matcher.find()) { matchFound = true; String match = matcher.group().trim(); tokens.add(iw.info.getToken(match)); tokens.addAll(parse(text.substring(match.length()))); break; } } if (!matchFound) { throw new DateCalcException("Could not parse the expression: " + text); } } } return tokens; } DateCalcExpressionParser(); Queue<Token> parse(String text); } |
@Test public void nowWithSpacesAndTime() { Queue<Token> words = parser.parse("now + 03:04"); Assert.assertTrue(words.poll() instanceof TimeToken); Assert.assertTrue(words.poll() instanceof OperatorToken); Assert.assertTrue(words.poll() instanceof TimeToken); } | public Queue<Token> parse(String text) { final Queue<Token> tokens = new ArrayDeque<>(); if (text != null) { text = text.trim(); if (!text.isEmpty()) { boolean matchFound = false; for (InfoWrapper iw : infos) { final Matcher matcher = iw.pattern.matcher(text); if (matcher.find()) { matchFound = true; String match = matcher.group().trim(); tokens.add(iw.info.getToken(match)); tokens.addAll(parse(text.substring(match.length()))); break; } } if (!matchFound) { throw new DateCalcException("Could not parse the expression: " + text); } } } return tokens; } | DateCalcExpressionParser { public Queue<Token> parse(String text) { final Queue<Token> tokens = new ArrayDeque<>(); if (text != null) { text = text.trim(); if (!text.isEmpty()) { boolean matchFound = false; for (InfoWrapper iw : infos) { final Matcher matcher = iw.pattern.matcher(text); if (matcher.find()) { matchFound = true; String match = matcher.group().trim(); tokens.add(iw.info.getToken(match)); tokens.addAll(parse(text.substring(match.length()))); break; } } if (!matchFound) { throw new DateCalcException("Could not parse the expression: " + text); } } } return tokens; } } | DateCalcExpressionParser { public Queue<Token> parse(String text) { final Queue<Token> tokens = new ArrayDeque<>(); if (text != null) { text = text.trim(); if (!text.isEmpty()) { boolean matchFound = false; for (InfoWrapper iw : infos) { final Matcher matcher = iw.pattern.matcher(text); if (matcher.find()) { matchFound = true; String match = matcher.group().trim(); tokens.add(iw.info.getToken(match)); tokens.addAll(parse(text.substring(match.length()))); break; } } if (!matchFound) { throw new DateCalcException("Could not parse the expression: " + text); } } } return tokens; } DateCalcExpressionParser(); } | DateCalcExpressionParser { public Queue<Token> parse(String text) { final Queue<Token> tokens = new ArrayDeque<>(); if (text != null) { text = text.trim(); if (!text.isEmpty()) { boolean matchFound = false; for (InfoWrapper iw : infos) { final Matcher matcher = iw.pattern.matcher(text); if (matcher.find()) { matchFound = true; String match = matcher.group().trim(); tokens.add(iw.info.getToken(match)); tokens.addAll(parse(text.substring(match.length()))); break; } } if (!matchFound) { throw new DateCalcException("Could not parse the expression: " + text); } } } return tokens; } DateCalcExpressionParser(); Queue<Token> parse(String text); } | DateCalcExpressionParser { public Queue<Token> parse(String text) { final Queue<Token> tokens = new ArrayDeque<>(); if (text != null) { text = text.trim(); if (!text.isEmpty()) { boolean matchFound = false; for (InfoWrapper iw : infos) { final Matcher matcher = iw.pattern.matcher(text); if (matcher.find()) { matchFound = true; String match = matcher.group().trim(); tokens.add(iw.info.getToken(match)); tokens.addAll(parse(text.substring(match.length()))); break; } } if (!matchFound) { throw new DateCalcException("Could not parse the expression: " + text); } } } return tokens; } DateCalcExpressionParser(); Queue<Token> parse(String text); } |
@Test public void nowWithSpacesAndUnitOfMeasure() { Queue<Token> tokens = parser.parse("now + 3h4m"); Assert.assertEquals(tokens.size(), 6); Assert.assertTrue(tokens.poll() instanceof TimeToken); Assert.assertTrue(tokens.poll() instanceof OperatorToken); Assert.assertTrue(tokens.poll() instanceof IntegerToken); Assert.assertTrue(tokens.poll() instanceof UnitOfMeasureToken); Assert.assertTrue(tokens.poll() instanceof IntegerToken); Assert.assertTrue(tokens.poll() instanceof UnitOfMeasureToken); } | public Queue<Token> parse(String text) { final Queue<Token> tokens = new ArrayDeque<>(); if (text != null) { text = text.trim(); if (!text.isEmpty()) { boolean matchFound = false; for (InfoWrapper iw : infos) { final Matcher matcher = iw.pattern.matcher(text); if (matcher.find()) { matchFound = true; String match = matcher.group().trim(); tokens.add(iw.info.getToken(match)); tokens.addAll(parse(text.substring(match.length()))); break; } } if (!matchFound) { throw new DateCalcException("Could not parse the expression: " + text); } } } return tokens; } | DateCalcExpressionParser { public Queue<Token> parse(String text) { final Queue<Token> tokens = new ArrayDeque<>(); if (text != null) { text = text.trim(); if (!text.isEmpty()) { boolean matchFound = false; for (InfoWrapper iw : infos) { final Matcher matcher = iw.pattern.matcher(text); if (matcher.find()) { matchFound = true; String match = matcher.group().trim(); tokens.add(iw.info.getToken(match)); tokens.addAll(parse(text.substring(match.length()))); break; } } if (!matchFound) { throw new DateCalcException("Could not parse the expression: " + text); } } } return tokens; } } | DateCalcExpressionParser { public Queue<Token> parse(String text) { final Queue<Token> tokens = new ArrayDeque<>(); if (text != null) { text = text.trim(); if (!text.isEmpty()) { boolean matchFound = false; for (InfoWrapper iw : infos) { final Matcher matcher = iw.pattern.matcher(text); if (matcher.find()) { matchFound = true; String match = matcher.group().trim(); tokens.add(iw.info.getToken(match)); tokens.addAll(parse(text.substring(match.length()))); break; } } if (!matchFound) { throw new DateCalcException("Could not parse the expression: " + text); } } } return tokens; } DateCalcExpressionParser(); } | DateCalcExpressionParser { public Queue<Token> parse(String text) { final Queue<Token> tokens = new ArrayDeque<>(); if (text != null) { text = text.trim(); if (!text.isEmpty()) { boolean matchFound = false; for (InfoWrapper iw : infos) { final Matcher matcher = iw.pattern.matcher(text); if (matcher.find()) { matchFound = true; String match = matcher.group().trim(); tokens.add(iw.info.getToken(match)); tokens.addAll(parse(text.substring(match.length()))); break; } } if (!matchFound) { throw new DateCalcException("Could not parse the expression: " + text); } } } return tokens; } DateCalcExpressionParser(); Queue<Token> parse(String text); } | DateCalcExpressionParser { public Queue<Token> parse(String text) { final Queue<Token> tokens = new ArrayDeque<>(); if (text != null) { text = text.trim(); if (!text.isEmpty()) { boolean matchFound = false; for (InfoWrapper iw : infos) { final Matcher matcher = iw.pattern.matcher(text); if (matcher.find()) { matchFound = true; String match = matcher.group().trim(); tokens.add(iw.info.getToken(match)); tokens.addAll(parse(text.substring(match.length()))); break; } } if (!matchFound) { throw new DateCalcException("Could not parse the expression: " + text); } } } return tokens; } DateCalcExpressionParser(); Queue<Token> parse(String text); } |
@Test public void booksAndAuthors() { Author author = new Author(); author.name = "Greg L. Turnquist"; author = authorRepo.save(author); Book book = new Book(); book.title = "Spring Boot"; book.addAuthor(author); bookRepo.save(book); bookRepo.deleteAll(); assertThat(authorRepo.count()).isEqualTo(1); } | public void addAuthor(Author author) { authors.add(createAuthorRef(author)); } | Book { public void addAuthor(Author author) { authors.add(createAuthorRef(author)); } } | Book { public void addAuthor(Author author) { authors.add(createAuthorRef(author)); } } | Book { public void addAuthor(Author author) { authors.add(createAuthorRef(author)); } void addAuthor(Author author); } | Book { public void addAuthor(Author author) { authors.add(createAuthorRef(author)); } void addAuthor(Author author); } |
@Test( expected = AssertionError.class ) public void testDecode_fail_type() throws Exception { Scope scope = CoreModule.getInstance().createScope(); Type type = UniversalType.INTEGER.ref().resolve( scope ); try( AbstractBerReader reader = mock( DefaultBerReader.class ) ) { Tag tag = ( (TagEncoding)type.getEncoding( EncodingInstructions.TAG ) ).toTag( false ); new EnumeratedBerDecoder().decode( new ReaderContext( reader, scope, type, tag, -1, false ) ); fail( "Must fail" ); } } | @Override public Value decode( @NotNull ReaderContext context ) throws IOException, Asn1Exception { assert context.getType().getFamily() == Family.ENUMERATED; return context.getType().optimize( context.getScope(), IntegerBerDecoder.readInteger( context.getReader(), context.getLength() ) ); } | EnumeratedBerDecoder implements BerDecoder { @Override public Value decode( @NotNull ReaderContext context ) throws IOException, Asn1Exception { assert context.getType().getFamily() == Family.ENUMERATED; return context.getType().optimize( context.getScope(), IntegerBerDecoder.readInteger( context.getReader(), context.getLength() ) ); } } | EnumeratedBerDecoder implements BerDecoder { @Override public Value decode( @NotNull ReaderContext context ) throws IOException, Asn1Exception { assert context.getType().getFamily() == Family.ENUMERATED; return context.getType().optimize( context.getScope(), IntegerBerDecoder.readInteger( context.getReader(), context.getLength() ) ); } } | EnumeratedBerDecoder implements BerDecoder { @Override public Value decode( @NotNull ReaderContext context ) throws IOException, Asn1Exception { assert context.getType().getFamily() == Family.ENUMERATED; return context.getType().optimize( context.getScope(), IntegerBerDecoder.readInteger( context.getReader(), context.getLength() ) ); } @Override Value decode( @NotNull ReaderContext context ); } | EnumeratedBerDecoder implements BerDecoder { @Override public Value decode( @NotNull ReaderContext context ) throws IOException, Asn1Exception { assert context.getType().getFamily() == Family.ENUMERATED; return context.getType().optimize( context.getScope(), IntegerBerDecoder.readInteger( context.getReader(), context.getLength() ) ); } @Override Value decode( @NotNull ReaderContext context ); } |
@Test( expected = ResolutionException.class ) public void testParserOptionalFail() throws Exception { ModuleImpl module = ModuleImpl.newDummy( new ModuleSet() ); ClassTypeImpl classType = new ClassTypeImpl(); classType.setSyntaxList( Arrays.asList( "&Type", "IDENTIFIED", "BY", "&id", "[", "CONSTRAINED", "BY", "&TypeConstraint", "]" ) ); classType.add( new ValueFieldType( "&id", UniversalType.OBJECT_IDENTIFIER.ref(), true, false ) ); classType.add( new TypeFieldType( "&Type", false, null ) ); classType.add( new TypeFieldType( "&TypeConstraint", false, null ) ); classType.validate( module.createScope() ); Ref<Value> ref = new AbstractSyntaxObjectRef( "{ My-Module.Type-External IDENTIFIED BY { rootOid 3 } CONSTRAINED BY type-Constraint}" ); Value value = ref.resolve( classType.getScope( module.createScope() ) ); Assert.assertNotNull( "No result", value ); } | @Override public Value resolve( Scope scope ) throws ResolutionException { Type type = scope.getTypeOrDie(); while( type != null && !( type instanceof ClassType ) ) type = type.hasSibling() ? type.getSibling() : null; if( type == null ) throw new ResolutionException( "Unable to find ClassType" ); Module module = scope.getModule(); ModuleResolver resolver = module.getModuleResolver(); assert resolver != null; ClassType classType = (ClassType)type; try { AbstractSyntaxParser parser = new AbstractSyntaxParser( module, classType ); Map<String, Ref<?>> result = parser.parse( abstractSyntax ); return new ObjectValue( result ); } catch( AbstractSyntaxParserException e ) { throw new ResolutionException( "Unable to unwrap abstract syntax: " + abstractSyntax, e ); } } | AbstractSyntaxObjectRef implements Ref<Value> { @Override public Value resolve( Scope scope ) throws ResolutionException { Type type = scope.getTypeOrDie(); while( type != null && !( type instanceof ClassType ) ) type = type.hasSibling() ? type.getSibling() : null; if( type == null ) throw new ResolutionException( "Unable to find ClassType" ); Module module = scope.getModule(); ModuleResolver resolver = module.getModuleResolver(); assert resolver != null; ClassType classType = (ClassType)type; try { AbstractSyntaxParser parser = new AbstractSyntaxParser( module, classType ); Map<String, Ref<?>> result = parser.parse( abstractSyntax ); return new ObjectValue( result ); } catch( AbstractSyntaxParserException e ) { throw new ResolutionException( "Unable to unwrap abstract syntax: " + abstractSyntax, e ); } } } | AbstractSyntaxObjectRef implements Ref<Value> { @Override public Value resolve( Scope scope ) throws ResolutionException { Type type = scope.getTypeOrDie(); while( type != null && !( type instanceof ClassType ) ) type = type.hasSibling() ? type.getSibling() : null; if( type == null ) throw new ResolutionException( "Unable to find ClassType" ); Module module = scope.getModule(); ModuleResolver resolver = module.getModuleResolver(); assert resolver != null; ClassType classType = (ClassType)type; try { AbstractSyntaxParser parser = new AbstractSyntaxParser( module, classType ); Map<String, Ref<?>> result = parser.parse( abstractSyntax ); return new ObjectValue( result ); } catch( AbstractSyntaxParserException e ) { throw new ResolutionException( "Unable to unwrap abstract syntax: " + abstractSyntax, e ); } } AbstractSyntaxObjectRef( String abstractSyntax ); } | AbstractSyntaxObjectRef implements Ref<Value> { @Override public Value resolve( Scope scope ) throws ResolutionException { Type type = scope.getTypeOrDie(); while( type != null && !( type instanceof ClassType ) ) type = type.hasSibling() ? type.getSibling() : null; if( type == null ) throw new ResolutionException( "Unable to find ClassType" ); Module module = scope.getModule(); ModuleResolver resolver = module.getModuleResolver(); assert resolver != null; ClassType classType = (ClassType)type; try { AbstractSyntaxParser parser = new AbstractSyntaxParser( module, classType ); Map<String, Ref<?>> result = parser.parse( abstractSyntax ); return new ObjectValue( result ); } catch( AbstractSyntaxParserException e ) { throw new ResolutionException( "Unable to unwrap abstract syntax: " + abstractSyntax, e ); } } AbstractSyntaxObjectRef( String abstractSyntax ); @Override Value resolve( Scope scope ); } | AbstractSyntaxObjectRef implements Ref<Value> { @Override public Value resolve( Scope scope ) throws ResolutionException { Type type = scope.getTypeOrDie(); while( type != null && !( type instanceof ClassType ) ) type = type.hasSibling() ? type.getSibling() : null; if( type == null ) throw new ResolutionException( "Unable to find ClassType" ); Module module = scope.getModule(); ModuleResolver resolver = module.getModuleResolver(); assert resolver != null; ClassType classType = (ClassType)type; try { AbstractSyntaxParser parser = new AbstractSyntaxParser( module, classType ); Map<String, Ref<?>> result = parser.parse( abstractSyntax ); return new ObjectValue( result ); } catch( AbstractSyntaxParserException e ) { throw new ResolutionException( "Unable to unwrap abstract syntax: " + abstractSyntax, e ); } } AbstractSyntaxObjectRef( String abstractSyntax ); @Override Value resolve( Scope scope ); } |
@Test( expected = ResolutionException.class ) public void testParserOptionalFailValue() throws Exception { ModuleImpl module = ModuleImpl.newDummy( new ModuleSet() ); ClassTypeImpl classType = new ClassTypeImpl(); classType.setSyntaxList( Arrays.asList( "&Type", "IDENTIFIED", "BY", "&id", "[", "CONSTRAINED", "BY", "&TypeConstraint", "]" ) ); classType.add( new ValueFieldType( "&id", UniversalType.OBJECT_IDENTIFIER.ref(), true, false ) ); classType.add( new TypeFieldType( "&Type", false, null ) ); classType.add( new TypeFieldType( "&TypeConstraint", false, null ) ); classType.validate( module.createScope() ); Ref<Value> ref = new AbstractSyntaxObjectRef( "{ My-Module.Type-External IDENTIFIED BY}" ); Value value = ref.resolve( classType.getScope( module.createScope() ) ); Assert.assertNotNull( "No result", value ); } | @Override public Value resolve( Scope scope ) throws ResolutionException { Type type = scope.getTypeOrDie(); while( type != null && !( type instanceof ClassType ) ) type = type.hasSibling() ? type.getSibling() : null; if( type == null ) throw new ResolutionException( "Unable to find ClassType" ); Module module = scope.getModule(); ModuleResolver resolver = module.getModuleResolver(); assert resolver != null; ClassType classType = (ClassType)type; try { AbstractSyntaxParser parser = new AbstractSyntaxParser( module, classType ); Map<String, Ref<?>> result = parser.parse( abstractSyntax ); return new ObjectValue( result ); } catch( AbstractSyntaxParserException e ) { throw new ResolutionException( "Unable to unwrap abstract syntax: " + abstractSyntax, e ); } } | AbstractSyntaxObjectRef implements Ref<Value> { @Override public Value resolve( Scope scope ) throws ResolutionException { Type type = scope.getTypeOrDie(); while( type != null && !( type instanceof ClassType ) ) type = type.hasSibling() ? type.getSibling() : null; if( type == null ) throw new ResolutionException( "Unable to find ClassType" ); Module module = scope.getModule(); ModuleResolver resolver = module.getModuleResolver(); assert resolver != null; ClassType classType = (ClassType)type; try { AbstractSyntaxParser parser = new AbstractSyntaxParser( module, classType ); Map<String, Ref<?>> result = parser.parse( abstractSyntax ); return new ObjectValue( result ); } catch( AbstractSyntaxParserException e ) { throw new ResolutionException( "Unable to unwrap abstract syntax: " + abstractSyntax, e ); } } } | AbstractSyntaxObjectRef implements Ref<Value> { @Override public Value resolve( Scope scope ) throws ResolutionException { Type type = scope.getTypeOrDie(); while( type != null && !( type instanceof ClassType ) ) type = type.hasSibling() ? type.getSibling() : null; if( type == null ) throw new ResolutionException( "Unable to find ClassType" ); Module module = scope.getModule(); ModuleResolver resolver = module.getModuleResolver(); assert resolver != null; ClassType classType = (ClassType)type; try { AbstractSyntaxParser parser = new AbstractSyntaxParser( module, classType ); Map<String, Ref<?>> result = parser.parse( abstractSyntax ); return new ObjectValue( result ); } catch( AbstractSyntaxParserException e ) { throw new ResolutionException( "Unable to unwrap abstract syntax: " + abstractSyntax, e ); } } AbstractSyntaxObjectRef( String abstractSyntax ); } | AbstractSyntaxObjectRef implements Ref<Value> { @Override public Value resolve( Scope scope ) throws ResolutionException { Type type = scope.getTypeOrDie(); while( type != null && !( type instanceof ClassType ) ) type = type.hasSibling() ? type.getSibling() : null; if( type == null ) throw new ResolutionException( "Unable to find ClassType" ); Module module = scope.getModule(); ModuleResolver resolver = module.getModuleResolver(); assert resolver != null; ClassType classType = (ClassType)type; try { AbstractSyntaxParser parser = new AbstractSyntaxParser( module, classType ); Map<String, Ref<?>> result = parser.parse( abstractSyntax ); return new ObjectValue( result ); } catch( AbstractSyntaxParserException e ) { throw new ResolutionException( "Unable to unwrap abstract syntax: " + abstractSyntax, e ); } } AbstractSyntaxObjectRef( String abstractSyntax ); @Override Value resolve( Scope scope ); } | AbstractSyntaxObjectRef implements Ref<Value> { @Override public Value resolve( Scope scope ) throws ResolutionException { Type type = scope.getTypeOrDie(); while( type != null && !( type instanceof ClassType ) ) type = type.hasSibling() ? type.getSibling() : null; if( type == null ) throw new ResolutionException( "Unable to find ClassType" ); Module module = scope.getModule(); ModuleResolver resolver = module.getModuleResolver(); assert resolver != null; ClassType classType = (ClassType)type; try { AbstractSyntaxParser parser = new AbstractSyntaxParser( module, classType ); Map<String, Ref<?>> result = parser.parse( abstractSyntax ); return new ObjectValue( result ); } catch( AbstractSyntaxParserException e ) { throw new ResolutionException( "Unable to unwrap abstract syntax: " + abstractSyntax, e ); } } AbstractSyntaxObjectRef( String abstractSyntax ); @Override Value resolve( Scope scope ); } |
@Test public void doTest() throws Exception { Asn1Factory factory = new DefaultAsn1Factory(); Module module = factory.types().dummyModule(); DefinedType type = factory.types().define( "MyInt", factory.types().builtin( "INTEGER" ), null ); module.validate(); ConstraintTemplate e = factory.constraints().elements( constraint, except ); boolean actual = ConstraintTestUtils.checkConstraint( e, factory.values().integer( 1 ), type, module.createScope() ); Assert.assertEquals( title + ": failed", expectedResult, actual ); } | public Elements( @NotNull Constraint unions, @Nullable Constraint exclusion ) { this.unions = unions; this.exclusion = exclusion; } | Elements implements Constraint { public Elements( @NotNull Constraint unions, @Nullable Constraint exclusion ) { this.unions = unions; this.exclusion = exclusion; } } | Elements implements Constraint { public Elements( @NotNull Constraint unions, @Nullable Constraint exclusion ) { this.unions = unions; this.exclusion = exclusion; } Elements( @NotNull Constraint unions, @Nullable Constraint exclusion ); } | Elements implements Constraint { public Elements( @NotNull Constraint unions, @Nullable Constraint exclusion ) { this.unions = unions; this.exclusion = exclusion; } Elements( @NotNull Constraint unions, @Nullable Constraint exclusion ); @Override void check( Scope scope, Ref<Value> valueRef ); @NotNull @Override Constraint copyForType( @NotNull Scope scope, @NotNull Type type ); @NotNull @Override Value getMinimumValue( @NotNull Scope scope ); @NotNull @Override Value getMaximumValue( @NotNull Scope scope ); @Override String toString(); @Override void setScopeOptions( Scope scope ); @Override void assertConstraintTypes( Collection<ConstraintType> allowedTypes ); @Override void collectValues( @NotNull Collection<Value> values, @NotNull Collection<Kind> requiredKinds ); } | Elements implements Constraint { public Elements( @NotNull Constraint unions, @Nullable Constraint exclusion ) { this.unions = unions; this.exclusion = exclusion; } Elements( @NotNull Constraint unions, @Nullable Constraint exclusion ); @Override void check( Scope scope, Ref<Value> valueRef ); @NotNull @Override Constraint copyForType( @NotNull Scope scope, @NotNull Type type ); @NotNull @Override Value getMinimumValue( @NotNull Scope scope ); @NotNull @Override Value getMaximumValue( @NotNull Scope scope ); @Override String toString(); @Override void setScopeOptions( Scope scope ); @Override void assertConstraintTypes( Collection<ConstraintType> allowedTypes ); @Override void collectValues( @NotNull Collection<Value> values, @NotNull Collection<Kind> requiredKinds ); } |
@Test public void doTest() { Asn1Factory factory = new DefaultAsn1Factory(); Module module = factory.types().dummyModule(); DefinedType type = factory.types().define( "MyInt", factory.types().builtin( "INTEGER" ), null ); ConstraintTemplate specs = unions == null ? factory.constraints().elementSetSpec( exclusion ) : factory.constraints().elementSetSpec( unions ); boolean actual = ConstraintTestUtils.checkConstraint( specs, factory.values().integer( 1 ), type, module.createScope() ); Assert.assertEquals( title + ": failed", expectedResult, actual ); } | public ElementSetSpec( List<Constraint> unions ) { this.unions = new ArrayList<>( unions ); } | ElementSetSpec implements Constraint { public ElementSetSpec( List<Constraint> unions ) { this.unions = new ArrayList<>( unions ); } } | ElementSetSpec implements Constraint { public ElementSetSpec( List<Constraint> unions ) { this.unions = new ArrayList<>( unions ); } ElementSetSpec( List<Constraint> unions ); } | ElementSetSpec implements Constraint { public ElementSetSpec( List<Constraint> unions ) { this.unions = new ArrayList<>( unions ); } ElementSetSpec( List<Constraint> unions ); @Override void check( Scope scope, Ref<Value> valueRef ); @NotNull @Override Value getMinimumValue( @NotNull Scope scope ); @NotNull @Override Value getMaximumValue( @NotNull Scope scope ); @Override String toString(); @NotNull @Override Constraint copyForType( @NotNull Scope scope, @NotNull Type type ); @Override void setScopeOptions( Scope scope ); @Override void assertConstraintTypes( Collection<ConstraintType> allowedTypes ); @Override void collectValues( @NotNull Collection<Value> values, @NotNull Collection<Kind> requiredKinds ); } | ElementSetSpec implements Constraint { public ElementSetSpec( List<Constraint> unions ) { this.unions = new ArrayList<>( unions ); } ElementSetSpec( List<Constraint> unions ); @Override void check( Scope scope, Ref<Value> valueRef ); @NotNull @Override Value getMinimumValue( @NotNull Scope scope ); @NotNull @Override Value getMaximumValue( @NotNull Scope scope ); @Override String toString(); @NotNull @Override Constraint copyForType( @NotNull Scope scope, @NotNull Type type ); @Override void setScopeOptions( Scope scope ); @Override void assertConstraintTypes( Collection<ConstraintType> allowedTypes ); @Override void collectValues( @NotNull Collection<Value> values, @NotNull Collection<Kind> requiredKinds ); } |
@Test public void testUTCParse() throws Exception { Instant now = Instant.now(); LocalDateTime ldt = LocalDateTime.ofInstant( now, ZoneId.of( "GMT" ) ); now = ldt.withNano( 0 ).toInstant( ZoneOffset.UTC ); DateTimeFormatter formatter = DateTimeFormatter.ofPattern( "yyMMddHHmmss" ).withZone( ZoneId.of( "GMT" ) ); String result = formatter.format( now ) + 'Z'; Instant instant = TimeUtils.parseUTCTime( result ); Assert.assertEquals( "Values are not equal", now, instant ); } | public static Instant parseUTCTime( String value ) { if( !UTCParser.isValid( value ) ) throw new IllegalArgumentException( "Not an UTCTime string: " + value ); return new UTCParser( value ).asInstant(); } | TimeUtils { public static Instant parseUTCTime( String value ) { if( !UTCParser.isValid( value ) ) throw new IllegalArgumentException( "Not an UTCTime string: " + value ); return new UTCParser( value ).asInstant(); } } | TimeUtils { public static Instant parseUTCTime( String value ) { if( !UTCParser.isValid( value ) ) throw new IllegalArgumentException( "Not an UTCTime string: " + value ); return new UTCParser( value ).asInstant(); } private TimeUtils(); } | TimeUtils { public static Instant parseUTCTime( String value ) { if( !UTCParser.isValid( value ) ) throw new IllegalArgumentException( "Not an UTCTime string: " + value ); return new UTCParser( value ).asInstant(); } private TimeUtils(); @NotNull static String formatInstant( TemporalAccessor instant, String format, boolean optimize ); static boolean isUTCTimeValue( CharSequence value ); static boolean isGeneralizedTimeValue( CharSequence value ); static Instant parseGeneralizedTime( String value ); static Instant parseUTCTime( String value ); } | TimeUtils { public static Instant parseUTCTime( String value ) { if( !UTCParser.isValid( value ) ) throw new IllegalArgumentException( "Not an UTCTime string: " + value ); return new UTCParser( value ).asInstant(); } private TimeUtils(); @NotNull static String formatInstant( TemporalAccessor instant, String format, boolean optimize ); static boolean isUTCTimeValue( CharSequence value ); static boolean isGeneralizedTimeValue( CharSequence value ); static Instant parseGeneralizedTime( String value ); static Instant parseUTCTime( String value ); static final String UTC_TIME_FORMAT; static final String GENERALIZED_TIME_FORMAT; @SuppressWarnings( "ConstantConditions" )
@NotNull
static final Charset CHARSET; } |
@Test public void testUTCParseMinutes() throws Exception { Instant now = Instant.now(); LocalDateTime ldt = LocalDateTime.ofInstant( now, ZoneId.of( "GMT" ) ); now = ldt.withSecond( 0 ).withNano( 0 ).toInstant( ZoneOffset.UTC ); DateTimeFormatter formatter = DateTimeFormatter.ofPattern( "yyMMddHHmm" ).withZone( ZoneId.of( "GMT" ) ); String result = formatter.format( now ) + 'Z'; Instant instant = TimeUtils.parseUTCTime( result ); Assert.assertEquals( "Values are not equal", now, instant ); } | public static Instant parseUTCTime( String value ) { if( !UTCParser.isValid( value ) ) throw new IllegalArgumentException( "Not an UTCTime string: " + value ); return new UTCParser( value ).asInstant(); } | TimeUtils { public static Instant parseUTCTime( String value ) { if( !UTCParser.isValid( value ) ) throw new IllegalArgumentException( "Not an UTCTime string: " + value ); return new UTCParser( value ).asInstant(); } } | TimeUtils { public static Instant parseUTCTime( String value ) { if( !UTCParser.isValid( value ) ) throw new IllegalArgumentException( "Not an UTCTime string: " + value ); return new UTCParser( value ).asInstant(); } private TimeUtils(); } | TimeUtils { public static Instant parseUTCTime( String value ) { if( !UTCParser.isValid( value ) ) throw new IllegalArgumentException( "Not an UTCTime string: " + value ); return new UTCParser( value ).asInstant(); } private TimeUtils(); @NotNull static String formatInstant( TemporalAccessor instant, String format, boolean optimize ); static boolean isUTCTimeValue( CharSequence value ); static boolean isGeneralizedTimeValue( CharSequence value ); static Instant parseGeneralizedTime( String value ); static Instant parseUTCTime( String value ); } | TimeUtils { public static Instant parseUTCTime( String value ) { if( !UTCParser.isValid( value ) ) throw new IllegalArgumentException( "Not an UTCTime string: " + value ); return new UTCParser( value ).asInstant(); } private TimeUtils(); @NotNull static String formatInstant( TemporalAccessor instant, String format, boolean optimize ); static boolean isUTCTimeValue( CharSequence value ); static boolean isGeneralizedTimeValue( CharSequence value ); static Instant parseGeneralizedTime( String value ); static Instant parseUTCTime( String value ); static final String UTC_TIME_FORMAT; static final String GENERALIZED_TIME_FORMAT; @SuppressWarnings( "ConstantConditions" )
@NotNull
static final Charset CHARSET; } |
@Test public void testUTCParseCustomTz() throws Exception { Instant now = Instant.now(); LocalDateTime ldt = LocalDateTime.ofInstant( now, ZoneId.of( "GMT" ) ); now = ldt.withNano( 0 ).toInstant( ZoneOffset.ofHours( 4 ) ); DateTimeFormatter formatter = DateTimeFormatter.ofPattern( "yyMMddHHmmssZ" ).withZone( ZoneId.systemDefault() ); String result = formatter.format( now ); Instant instant = TimeUtils.parseUTCTime( result ); Assert.assertEquals( "Values are not equal", now, instant ); } | public static Instant parseUTCTime( String value ) { if( !UTCParser.isValid( value ) ) throw new IllegalArgumentException( "Not an UTCTime string: " + value ); return new UTCParser( value ).asInstant(); } | TimeUtils { public static Instant parseUTCTime( String value ) { if( !UTCParser.isValid( value ) ) throw new IllegalArgumentException( "Not an UTCTime string: " + value ); return new UTCParser( value ).asInstant(); } } | TimeUtils { public static Instant parseUTCTime( String value ) { if( !UTCParser.isValid( value ) ) throw new IllegalArgumentException( "Not an UTCTime string: " + value ); return new UTCParser( value ).asInstant(); } private TimeUtils(); } | TimeUtils { public static Instant parseUTCTime( String value ) { if( !UTCParser.isValid( value ) ) throw new IllegalArgumentException( "Not an UTCTime string: " + value ); return new UTCParser( value ).asInstant(); } private TimeUtils(); @NotNull static String formatInstant( TemporalAccessor instant, String format, boolean optimize ); static boolean isUTCTimeValue( CharSequence value ); static boolean isGeneralizedTimeValue( CharSequence value ); static Instant parseGeneralizedTime( String value ); static Instant parseUTCTime( String value ); } | TimeUtils { public static Instant parseUTCTime( String value ) { if( !UTCParser.isValid( value ) ) throw new IllegalArgumentException( "Not an UTCTime string: " + value ); return new UTCParser( value ).asInstant(); } private TimeUtils(); @NotNull static String formatInstant( TemporalAccessor instant, String format, boolean optimize ); static boolean isUTCTimeValue( CharSequence value ); static boolean isGeneralizedTimeValue( CharSequence value ); static Instant parseGeneralizedTime( String value ); static Instant parseUTCTime( String value ); static final String UTC_TIME_FORMAT; static final String GENERALIZED_TIME_FORMAT; @SuppressWarnings( "ConstantConditions" )
@NotNull
static final Charset CHARSET; } |
@Test public void testUTCParseMinutesCustomTz() throws Exception { Instant now = Instant.now(); LocalDateTime ldt = LocalDateTime.ofInstant( now, ZoneId.of( "GMT" ) ); now = ldt.withSecond( 0 ).withNano( 0 ).toInstant( ZoneOffset.ofHours( 4 ) ); DateTimeFormatter formatter = DateTimeFormatter.ofPattern( "yyMMddHHmmZ" ).withZone( ZoneId.systemDefault() ); String result = formatter.format( now ); Instant instant = TimeUtils.parseUTCTime( result ); Assert.assertEquals( "Values are not equal", now, instant ); } | public static Instant parseUTCTime( String value ) { if( !UTCParser.isValid( value ) ) throw new IllegalArgumentException( "Not an UTCTime string: " + value ); return new UTCParser( value ).asInstant(); } | TimeUtils { public static Instant parseUTCTime( String value ) { if( !UTCParser.isValid( value ) ) throw new IllegalArgumentException( "Not an UTCTime string: " + value ); return new UTCParser( value ).asInstant(); } } | TimeUtils { public static Instant parseUTCTime( String value ) { if( !UTCParser.isValid( value ) ) throw new IllegalArgumentException( "Not an UTCTime string: " + value ); return new UTCParser( value ).asInstant(); } private TimeUtils(); } | TimeUtils { public static Instant parseUTCTime( String value ) { if( !UTCParser.isValid( value ) ) throw new IllegalArgumentException( "Not an UTCTime string: " + value ); return new UTCParser( value ).asInstant(); } private TimeUtils(); @NotNull static String formatInstant( TemporalAccessor instant, String format, boolean optimize ); static boolean isUTCTimeValue( CharSequence value ); static boolean isGeneralizedTimeValue( CharSequence value ); static Instant parseGeneralizedTime( String value ); static Instant parseUTCTime( String value ); } | TimeUtils { public static Instant parseUTCTime( String value ) { if( !UTCParser.isValid( value ) ) throw new IllegalArgumentException( "Not an UTCTime string: " + value ); return new UTCParser( value ).asInstant(); } private TimeUtils(); @NotNull static String formatInstant( TemporalAccessor instant, String format, boolean optimize ); static boolean isUTCTimeValue( CharSequence value ); static boolean isGeneralizedTimeValue( CharSequence value ); static Instant parseGeneralizedTime( String value ); static Instant parseUTCTime( String value ); static final String UTC_TIME_FORMAT; static final String GENERALIZED_TIME_FORMAT; @SuppressWarnings( "ConstantConditions" )
@NotNull
static final Charset CHARSET; } |
@Test public void testGeneralizedParse() throws Exception { Instant now = Instant.now(); DateTimeFormatter formatter = DateTimeFormatter.ofPattern( "yyyyMMddHHmmss.SSS" ).withZone( ZoneId.of( "GMT" ) ); String result = formatter.format( now ) + 'Z'; Instant instant = TimeUtils.parseGeneralizedTime( result ); Assert.assertEquals( "Values are not equal", now, instant ); } | public static Instant parseGeneralizedTime( String value ) { if( !GeneralizedParser.isValid( value ) ) throw new IllegalArgumentException( "Not an GeneralizedTime string: " + value ); return new GeneralizedParser( value ).asInstant(); } | TimeUtils { public static Instant parseGeneralizedTime( String value ) { if( !GeneralizedParser.isValid( value ) ) throw new IllegalArgumentException( "Not an GeneralizedTime string: " + value ); return new GeneralizedParser( value ).asInstant(); } } | TimeUtils { public static Instant parseGeneralizedTime( String value ) { if( !GeneralizedParser.isValid( value ) ) throw new IllegalArgumentException( "Not an GeneralizedTime string: " + value ); return new GeneralizedParser( value ).asInstant(); } private TimeUtils(); } | TimeUtils { public static Instant parseGeneralizedTime( String value ) { if( !GeneralizedParser.isValid( value ) ) throw new IllegalArgumentException( "Not an GeneralizedTime string: " + value ); return new GeneralizedParser( value ).asInstant(); } private TimeUtils(); @NotNull static String formatInstant( TemporalAccessor instant, String format, boolean optimize ); static boolean isUTCTimeValue( CharSequence value ); static boolean isGeneralizedTimeValue( CharSequence value ); static Instant parseGeneralizedTime( String value ); static Instant parseUTCTime( String value ); } | TimeUtils { public static Instant parseGeneralizedTime( String value ) { if( !GeneralizedParser.isValid( value ) ) throw new IllegalArgumentException( "Not an GeneralizedTime string: " + value ); return new GeneralizedParser( value ).asInstant(); } private TimeUtils(); @NotNull static String formatInstant( TemporalAccessor instant, String format, boolean optimize ); static boolean isUTCTimeValue( CharSequence value ); static boolean isGeneralizedTimeValue( CharSequence value ); static Instant parseGeneralizedTime( String value ); static Instant parseUTCTime( String value ); static final String UTC_TIME_FORMAT; static final String GENERALIZED_TIME_FORMAT; @SuppressWarnings( "ConstantConditions" )
@NotNull
static final Charset CHARSET; } |
@Test public void testGeneralizedParseNoZ() throws Exception { Instant now = Instant.now(); DateTimeFormatter formatter = DateTimeFormatter.ofPattern( "yyyyMMddHHmmss.SSS" ).withZone( ZoneId.of( "GMT" ) ); String result = formatter.format( now ); Instant instant = TimeUtils.parseGeneralizedTime( result ); Assert.assertEquals( "Values are not equal", now, instant ); } | public static Instant parseGeneralizedTime( String value ) { if( !GeneralizedParser.isValid( value ) ) throw new IllegalArgumentException( "Not an GeneralizedTime string: " + value ); return new GeneralizedParser( value ).asInstant(); } | TimeUtils { public static Instant parseGeneralizedTime( String value ) { if( !GeneralizedParser.isValid( value ) ) throw new IllegalArgumentException( "Not an GeneralizedTime string: " + value ); return new GeneralizedParser( value ).asInstant(); } } | TimeUtils { public static Instant parseGeneralizedTime( String value ) { if( !GeneralizedParser.isValid( value ) ) throw new IllegalArgumentException( "Not an GeneralizedTime string: " + value ); return new GeneralizedParser( value ).asInstant(); } private TimeUtils(); } | TimeUtils { public static Instant parseGeneralizedTime( String value ) { if( !GeneralizedParser.isValid( value ) ) throw new IllegalArgumentException( "Not an GeneralizedTime string: " + value ); return new GeneralizedParser( value ).asInstant(); } private TimeUtils(); @NotNull static String formatInstant( TemporalAccessor instant, String format, boolean optimize ); static boolean isUTCTimeValue( CharSequence value ); static boolean isGeneralizedTimeValue( CharSequence value ); static Instant parseGeneralizedTime( String value ); static Instant parseUTCTime( String value ); } | TimeUtils { public static Instant parseGeneralizedTime( String value ) { if( !GeneralizedParser.isValid( value ) ) throw new IllegalArgumentException( "Not an GeneralizedTime string: " + value ); return new GeneralizedParser( value ).asInstant(); } private TimeUtils(); @NotNull static String formatInstant( TemporalAccessor instant, String format, boolean optimize ); static boolean isUTCTimeValue( CharSequence value ); static boolean isGeneralizedTimeValue( CharSequence value ); static Instant parseGeneralizedTime( String value ); static Instant parseUTCTime( String value ); static final String UTC_TIME_FORMAT; static final String GENERALIZED_TIME_FORMAT; @SuppressWarnings( "ConstantConditions" )
@NotNull
static final Charset CHARSET; } |
@Test( expected = AssertionError.class ) public void testDecode_fail_length() throws Exception { Scope scope = CoreModule.getInstance().createScope(); Type type = UniversalType.NULL.ref().resolve( scope ); try( AbstractBerReader reader = mock( DefaultBerReader.class ) ) { Tag tag = ( (TagEncoding)type.getEncoding( EncodingInstructions.TAG ) ).toTag( false ); new NullBerDecoder().decode( new ReaderContext( reader, scope, type, tag, 1, false ) ); fail( "Must fail" ); } } | @Override public Value decode( @NotNull ReaderContext context ) { assert context.getType().getFamily() == Family.NULL; assert context.getLength() == 0; return NullValue.INSTANCE; } | NullBerDecoder implements BerDecoder { @Override public Value decode( @NotNull ReaderContext context ) { assert context.getType().getFamily() == Family.NULL; assert context.getLength() == 0; return NullValue.INSTANCE; } } | NullBerDecoder implements BerDecoder { @Override public Value decode( @NotNull ReaderContext context ) { assert context.getType().getFamily() == Family.NULL; assert context.getLength() == 0; return NullValue.INSTANCE; } } | NullBerDecoder implements BerDecoder { @Override public Value decode( @NotNull ReaderContext context ) { assert context.getType().getFamily() == Family.NULL; assert context.getLength() == 0; return NullValue.INSTANCE; } @Override Value decode( @NotNull ReaderContext context ); } | NullBerDecoder implements BerDecoder { @Override public Value decode( @NotNull ReaderContext context ) { assert context.getType().getFamily() == Family.NULL; assert context.getLength() == 0; return NullValue.INSTANCE; } @Override Value decode( @NotNull ReaderContext context ); } |
@Test public void testGeneralizedParseNoFracture() throws Exception { Instant now = Instant.now(); LocalDateTime ldt = LocalDateTime.ofInstant( now, ZoneId.of( "GMT" ) ); now = ldt.withNano( 0 ).toInstant( ZoneOffset.UTC ); DateTimeFormatter formatter = DateTimeFormatter.ofPattern( "yyyyMMddHHmmss" ).withZone( ZoneId.of( "GMT" ) ); String result = formatter.format( now ) + 'Z'; Instant instant = TimeUtils.parseGeneralizedTime( result ); Assert.assertEquals( "Values are not equal", now, instant ); } | public static Instant parseGeneralizedTime( String value ) { if( !GeneralizedParser.isValid( value ) ) throw new IllegalArgumentException( "Not an GeneralizedTime string: " + value ); return new GeneralizedParser( value ).asInstant(); } | TimeUtils { public static Instant parseGeneralizedTime( String value ) { if( !GeneralizedParser.isValid( value ) ) throw new IllegalArgumentException( "Not an GeneralizedTime string: " + value ); return new GeneralizedParser( value ).asInstant(); } } | TimeUtils { public static Instant parseGeneralizedTime( String value ) { if( !GeneralizedParser.isValid( value ) ) throw new IllegalArgumentException( "Not an GeneralizedTime string: " + value ); return new GeneralizedParser( value ).asInstant(); } private TimeUtils(); } | TimeUtils { public static Instant parseGeneralizedTime( String value ) { if( !GeneralizedParser.isValid( value ) ) throw new IllegalArgumentException( "Not an GeneralizedTime string: " + value ); return new GeneralizedParser( value ).asInstant(); } private TimeUtils(); @NotNull static String formatInstant( TemporalAccessor instant, String format, boolean optimize ); static boolean isUTCTimeValue( CharSequence value ); static boolean isGeneralizedTimeValue( CharSequence value ); static Instant parseGeneralizedTime( String value ); static Instant parseUTCTime( String value ); } | TimeUtils { public static Instant parseGeneralizedTime( String value ) { if( !GeneralizedParser.isValid( value ) ) throw new IllegalArgumentException( "Not an GeneralizedTime string: " + value ); return new GeneralizedParser( value ).asInstant(); } private TimeUtils(); @NotNull static String formatInstant( TemporalAccessor instant, String format, boolean optimize ); static boolean isUTCTimeValue( CharSequence value ); static boolean isGeneralizedTimeValue( CharSequence value ); static Instant parseGeneralizedTime( String value ); static Instant parseUTCTime( String value ); static final String UTC_TIME_FORMAT; static final String GENERALIZED_TIME_FORMAT; @SuppressWarnings( "ConstantConditions" )
@NotNull
static final Charset CHARSET; } |
@Test public void testGeneralizedParseNoFractureNoSeconds() throws Exception { Instant now = Instant.now(); LocalDateTime ldt = LocalDateTime.ofInstant( now, ZoneId.of( "GMT" ) ); now = ldt.withSecond( 0 ).withNano( 0 ).toInstant( ZoneOffset.UTC ); DateTimeFormatter formatter = DateTimeFormatter.ofPattern( "yyyyMMddHHmm" ).withZone( ZoneId.of( "GMT" ) ); String result = formatter.format( now ) + 'Z'; Instant instant = TimeUtils.parseGeneralizedTime( result ); Assert.assertEquals( "Values are not equal", now, instant ); } | public static Instant parseGeneralizedTime( String value ) { if( !GeneralizedParser.isValid( value ) ) throw new IllegalArgumentException( "Not an GeneralizedTime string: " + value ); return new GeneralizedParser( value ).asInstant(); } | TimeUtils { public static Instant parseGeneralizedTime( String value ) { if( !GeneralizedParser.isValid( value ) ) throw new IllegalArgumentException( "Not an GeneralizedTime string: " + value ); return new GeneralizedParser( value ).asInstant(); } } | TimeUtils { public static Instant parseGeneralizedTime( String value ) { if( !GeneralizedParser.isValid( value ) ) throw new IllegalArgumentException( "Not an GeneralizedTime string: " + value ); return new GeneralizedParser( value ).asInstant(); } private TimeUtils(); } | TimeUtils { public static Instant parseGeneralizedTime( String value ) { if( !GeneralizedParser.isValid( value ) ) throw new IllegalArgumentException( "Not an GeneralizedTime string: " + value ); return new GeneralizedParser( value ).asInstant(); } private TimeUtils(); @NotNull static String formatInstant( TemporalAccessor instant, String format, boolean optimize ); static boolean isUTCTimeValue( CharSequence value ); static boolean isGeneralizedTimeValue( CharSequence value ); static Instant parseGeneralizedTime( String value ); static Instant parseUTCTime( String value ); } | TimeUtils { public static Instant parseGeneralizedTime( String value ) { if( !GeneralizedParser.isValid( value ) ) throw new IllegalArgumentException( "Not an GeneralizedTime string: " + value ); return new GeneralizedParser( value ).asInstant(); } private TimeUtils(); @NotNull static String formatInstant( TemporalAccessor instant, String format, boolean optimize ); static boolean isUTCTimeValue( CharSequence value ); static boolean isGeneralizedTimeValue( CharSequence value ); static Instant parseGeneralizedTime( String value ); static Instant parseUTCTime( String value ); static final String UTC_TIME_FORMAT; static final String GENERALIZED_TIME_FORMAT; @SuppressWarnings( "ConstantConditions" )
@NotNull
static final Charset CHARSET; } |
@Test public void testGeneralizedParseNoFractureNoZ() throws Exception { Instant now = Instant.now(); LocalDateTime ldt = LocalDateTime.ofInstant( now, ZoneId.of( "GMT" ) ); now = ldt.withNano( 0 ).toInstant( ZoneOffset.UTC ); DateTimeFormatter formatter = DateTimeFormatter.ofPattern( "yyyyMMddHHmmss" ).withZone( ZoneId.of( "GMT" ) ); String result = formatter.format( now ); Instant instant = TimeUtils.parseGeneralizedTime( result ); Assert.assertEquals( "Values are not equal", now, instant ); } | public static Instant parseGeneralizedTime( String value ) { if( !GeneralizedParser.isValid( value ) ) throw new IllegalArgumentException( "Not an GeneralizedTime string: " + value ); return new GeneralizedParser( value ).asInstant(); } | TimeUtils { public static Instant parseGeneralizedTime( String value ) { if( !GeneralizedParser.isValid( value ) ) throw new IllegalArgumentException( "Not an GeneralizedTime string: " + value ); return new GeneralizedParser( value ).asInstant(); } } | TimeUtils { public static Instant parseGeneralizedTime( String value ) { if( !GeneralizedParser.isValid( value ) ) throw new IllegalArgumentException( "Not an GeneralizedTime string: " + value ); return new GeneralizedParser( value ).asInstant(); } private TimeUtils(); } | TimeUtils { public static Instant parseGeneralizedTime( String value ) { if( !GeneralizedParser.isValid( value ) ) throw new IllegalArgumentException( "Not an GeneralizedTime string: " + value ); return new GeneralizedParser( value ).asInstant(); } private TimeUtils(); @NotNull static String formatInstant( TemporalAccessor instant, String format, boolean optimize ); static boolean isUTCTimeValue( CharSequence value ); static boolean isGeneralizedTimeValue( CharSequence value ); static Instant parseGeneralizedTime( String value ); static Instant parseUTCTime( String value ); } | TimeUtils { public static Instant parseGeneralizedTime( String value ) { if( !GeneralizedParser.isValid( value ) ) throw new IllegalArgumentException( "Not an GeneralizedTime string: " + value ); return new GeneralizedParser( value ).asInstant(); } private TimeUtils(); @NotNull static String formatInstant( TemporalAccessor instant, String format, boolean optimize ); static boolean isUTCTimeValue( CharSequence value ); static boolean isGeneralizedTimeValue( CharSequence value ); static Instant parseGeneralizedTime( String value ); static Instant parseUTCTime( String value ); static final String UTC_TIME_FORMAT; static final String GENERALIZED_TIME_FORMAT; @SuppressWarnings( "ConstantConditions" )
@NotNull
static final Charset CHARSET; } |
@Test public void testGeneralizedParseNoMinutesWithFracture() throws Exception { Instant now = Instant.now(); LocalDateTime ldt = LocalDateTime.ofInstant( now, ZoneId.of( "GMT" ) ); ldt = ldt.withMinute( 59 ).withSecond( 52 ).withNano( 800000000 ); now = ldt.toInstant( ZoneOffset.UTC ); DateTimeFormatter formatter = DateTimeFormatter.ofPattern( "yyyyMMddHH" ).withZone( ZoneId.of( "GMT" ) ); String result = formatter.format( now ) + ".998Z"; Instant instant = TimeUtils.parseGeneralizedTime( result ); Assert.assertEquals( "Values are not equal", now, instant ); } | public static Instant parseGeneralizedTime( String value ) { if( !GeneralizedParser.isValid( value ) ) throw new IllegalArgumentException( "Not an GeneralizedTime string: " + value ); return new GeneralizedParser( value ).asInstant(); } | TimeUtils { public static Instant parseGeneralizedTime( String value ) { if( !GeneralizedParser.isValid( value ) ) throw new IllegalArgumentException( "Not an GeneralizedTime string: " + value ); return new GeneralizedParser( value ).asInstant(); } } | TimeUtils { public static Instant parseGeneralizedTime( String value ) { if( !GeneralizedParser.isValid( value ) ) throw new IllegalArgumentException( "Not an GeneralizedTime string: " + value ); return new GeneralizedParser( value ).asInstant(); } private TimeUtils(); } | TimeUtils { public static Instant parseGeneralizedTime( String value ) { if( !GeneralizedParser.isValid( value ) ) throw new IllegalArgumentException( "Not an GeneralizedTime string: " + value ); return new GeneralizedParser( value ).asInstant(); } private TimeUtils(); @NotNull static String formatInstant( TemporalAccessor instant, String format, boolean optimize ); static boolean isUTCTimeValue( CharSequence value ); static boolean isGeneralizedTimeValue( CharSequence value ); static Instant parseGeneralizedTime( String value ); static Instant parseUTCTime( String value ); } | TimeUtils { public static Instant parseGeneralizedTime( String value ) { if( !GeneralizedParser.isValid( value ) ) throw new IllegalArgumentException( "Not an GeneralizedTime string: " + value ); return new GeneralizedParser( value ).asInstant(); } private TimeUtils(); @NotNull static String formatInstant( TemporalAccessor instant, String format, boolean optimize ); static boolean isUTCTimeValue( CharSequence value ); static boolean isGeneralizedTimeValue( CharSequence value ); static Instant parseGeneralizedTime( String value ); static Instant parseUTCTime( String value ); static final String UTC_TIME_FORMAT; static final String GENERALIZED_TIME_FORMAT; @SuppressWarnings( "ConstantConditions" )
@NotNull
static final Charset CHARSET; } |
@Test public void testGeneralizedParseCustomTz() throws Exception { Instant now = Instant.now(); LocalDateTime ldt = LocalDateTime.ofInstant( now, ZoneId.of( "GMT" ) ); now = ldt.withNano( 0 ).toInstant( ZoneOffset.UTC ); DateTimeFormatter formatter = DateTimeFormatter.ofPattern( "yyyyMMddHHmmssZ" ).withZone( ZoneId.systemDefault() ); String result = formatter.format( now ); Instant instant = TimeUtils.parseGeneralizedTime( result ); Assert.assertEquals( "Values are not equal", now, instant ); } | public static Instant parseGeneralizedTime( String value ) { if( !GeneralizedParser.isValid( value ) ) throw new IllegalArgumentException( "Not an GeneralizedTime string: " + value ); return new GeneralizedParser( value ).asInstant(); } | TimeUtils { public static Instant parseGeneralizedTime( String value ) { if( !GeneralizedParser.isValid( value ) ) throw new IllegalArgumentException( "Not an GeneralizedTime string: " + value ); return new GeneralizedParser( value ).asInstant(); } } | TimeUtils { public static Instant parseGeneralizedTime( String value ) { if( !GeneralizedParser.isValid( value ) ) throw new IllegalArgumentException( "Not an GeneralizedTime string: " + value ); return new GeneralizedParser( value ).asInstant(); } private TimeUtils(); } | TimeUtils { public static Instant parseGeneralizedTime( String value ) { if( !GeneralizedParser.isValid( value ) ) throw new IllegalArgumentException( "Not an GeneralizedTime string: " + value ); return new GeneralizedParser( value ).asInstant(); } private TimeUtils(); @NotNull static String formatInstant( TemporalAccessor instant, String format, boolean optimize ); static boolean isUTCTimeValue( CharSequence value ); static boolean isGeneralizedTimeValue( CharSequence value ); static Instant parseGeneralizedTime( String value ); static Instant parseUTCTime( String value ); } | TimeUtils { public static Instant parseGeneralizedTime( String value ) { if( !GeneralizedParser.isValid( value ) ) throw new IllegalArgumentException( "Not an GeneralizedTime string: " + value ); return new GeneralizedParser( value ).asInstant(); } private TimeUtils(); @NotNull static String formatInstant( TemporalAccessor instant, String format, boolean optimize ); static boolean isUTCTimeValue( CharSequence value ); static boolean isGeneralizedTimeValue( CharSequence value ); static Instant parseGeneralizedTime( String value ); static Instant parseUTCTime( String value ); static final String UTC_TIME_FORMAT; static final String GENERALIZED_TIME_FORMAT; @SuppressWarnings( "ConstantConditions" )
@NotNull
static final Charset CHARSET; } |
@Test public void testFormatInstant000() { Instant now = Instant.now(); LocalDateTime ldt = LocalDateTime.ofInstant( now, ZoneId.of( "GMT" ) ); ldt = ldt.withYear( 2000 ).withMonth( 1 ).withDayOfMonth( 1 ).withHour( 1 ).withMinute( 0 ).withSecond( 0 ).withNano( 0 ); now = ldt.toInstant( ZoneOffset.UTC ); String result = TimeUtils.formatInstant( now, TimeUtils.GENERALIZED_TIME_FORMAT, true ); Assert.assertEquals( "Values are not equal", "200001010100Z", result ); } | @NotNull public static String formatInstant( TemporalAccessor instant, String format, boolean optimize ) { DateTimeFormatter formatter = DateTimeFormatter.ofPattern( format ) .withZone( ZoneId.of( "GMT" ) ); String result = formatter.format( instant ); if( result.indexOf( '.' ) > 0 ) { if( result.endsWith( ".000" ) ) result = result.substring( 0, result.length() - 4 ); else if( result.endsWith( "00" ) ) result = result.substring( 0, result.length() - 2 ); else if( result.endsWith( "0" ) ) result = result.substring( 0, result.length() - 1 ); } if( optimize && result.endsWith( "00" ) ) result = result.substring( 0, result.length() - 2 ); result += "Z"; return result; } | TimeUtils { @NotNull public static String formatInstant( TemporalAccessor instant, String format, boolean optimize ) { DateTimeFormatter formatter = DateTimeFormatter.ofPattern( format ) .withZone( ZoneId.of( "GMT" ) ); String result = formatter.format( instant ); if( result.indexOf( '.' ) > 0 ) { if( result.endsWith( ".000" ) ) result = result.substring( 0, result.length() - 4 ); else if( result.endsWith( "00" ) ) result = result.substring( 0, result.length() - 2 ); else if( result.endsWith( "0" ) ) result = result.substring( 0, result.length() - 1 ); } if( optimize && result.endsWith( "00" ) ) result = result.substring( 0, result.length() - 2 ); result += "Z"; return result; } } | TimeUtils { @NotNull public static String formatInstant( TemporalAccessor instant, String format, boolean optimize ) { DateTimeFormatter formatter = DateTimeFormatter.ofPattern( format ) .withZone( ZoneId.of( "GMT" ) ); String result = formatter.format( instant ); if( result.indexOf( '.' ) > 0 ) { if( result.endsWith( ".000" ) ) result = result.substring( 0, result.length() - 4 ); else if( result.endsWith( "00" ) ) result = result.substring( 0, result.length() - 2 ); else if( result.endsWith( "0" ) ) result = result.substring( 0, result.length() - 1 ); } if( optimize && result.endsWith( "00" ) ) result = result.substring( 0, result.length() - 2 ); result += "Z"; return result; } private TimeUtils(); } | TimeUtils { @NotNull public static String formatInstant( TemporalAccessor instant, String format, boolean optimize ) { DateTimeFormatter formatter = DateTimeFormatter.ofPattern( format ) .withZone( ZoneId.of( "GMT" ) ); String result = formatter.format( instant ); if( result.indexOf( '.' ) > 0 ) { if( result.endsWith( ".000" ) ) result = result.substring( 0, result.length() - 4 ); else if( result.endsWith( "00" ) ) result = result.substring( 0, result.length() - 2 ); else if( result.endsWith( "0" ) ) result = result.substring( 0, result.length() - 1 ); } if( optimize && result.endsWith( "00" ) ) result = result.substring( 0, result.length() - 2 ); result += "Z"; return result; } private TimeUtils(); @NotNull static String formatInstant( TemporalAccessor instant, String format, boolean optimize ); static boolean isUTCTimeValue( CharSequence value ); static boolean isGeneralizedTimeValue( CharSequence value ); static Instant parseGeneralizedTime( String value ); static Instant parseUTCTime( String value ); } | TimeUtils { @NotNull public static String formatInstant( TemporalAccessor instant, String format, boolean optimize ) { DateTimeFormatter formatter = DateTimeFormatter.ofPattern( format ) .withZone( ZoneId.of( "GMT" ) ); String result = formatter.format( instant ); if( result.indexOf( '.' ) > 0 ) { if( result.endsWith( ".000" ) ) result = result.substring( 0, result.length() - 4 ); else if( result.endsWith( "00" ) ) result = result.substring( 0, result.length() - 2 ); else if( result.endsWith( "0" ) ) result = result.substring( 0, result.length() - 1 ); } if( optimize && result.endsWith( "00" ) ) result = result.substring( 0, result.length() - 2 ); result += "Z"; return result; } private TimeUtils(); @NotNull static String formatInstant( TemporalAccessor instant, String format, boolean optimize ); static boolean isUTCTimeValue( CharSequence value ); static boolean isGeneralizedTimeValue( CharSequence value ); static Instant parseGeneralizedTime( String value ); static Instant parseUTCTime( String value ); static final String UTC_TIME_FORMAT; static final String GENERALIZED_TIME_FORMAT; @SuppressWarnings( "ConstantConditions" )
@NotNull
static final Charset CHARSET; } |
@Test public void testFormatInstant00() { Instant now = Instant.now(); LocalDateTime ldt = LocalDateTime.ofInstant( now, ZoneId.of( "GMT" ) ); ldt = ldt.withYear( 2000 ).withMonth( 1 ).withDayOfMonth( 1 ).withHour( 1 ).withMinute( 0 ).withSecond( 0 ) .withNano( 880000000 ); now = ldt.toInstant( ZoneOffset.UTC ); String result = TimeUtils.formatInstant( now, TimeUtils.GENERALIZED_TIME_FORMAT, true ); Assert.assertEquals( "Values are not equal", "20000101010000.88Z", result ); } | @NotNull public static String formatInstant( TemporalAccessor instant, String format, boolean optimize ) { DateTimeFormatter formatter = DateTimeFormatter.ofPattern( format ) .withZone( ZoneId.of( "GMT" ) ); String result = formatter.format( instant ); if( result.indexOf( '.' ) > 0 ) { if( result.endsWith( ".000" ) ) result = result.substring( 0, result.length() - 4 ); else if( result.endsWith( "00" ) ) result = result.substring( 0, result.length() - 2 ); else if( result.endsWith( "0" ) ) result = result.substring( 0, result.length() - 1 ); } if( optimize && result.endsWith( "00" ) ) result = result.substring( 0, result.length() - 2 ); result += "Z"; return result; } | TimeUtils { @NotNull public static String formatInstant( TemporalAccessor instant, String format, boolean optimize ) { DateTimeFormatter formatter = DateTimeFormatter.ofPattern( format ) .withZone( ZoneId.of( "GMT" ) ); String result = formatter.format( instant ); if( result.indexOf( '.' ) > 0 ) { if( result.endsWith( ".000" ) ) result = result.substring( 0, result.length() - 4 ); else if( result.endsWith( "00" ) ) result = result.substring( 0, result.length() - 2 ); else if( result.endsWith( "0" ) ) result = result.substring( 0, result.length() - 1 ); } if( optimize && result.endsWith( "00" ) ) result = result.substring( 0, result.length() - 2 ); result += "Z"; return result; } } | TimeUtils { @NotNull public static String formatInstant( TemporalAccessor instant, String format, boolean optimize ) { DateTimeFormatter formatter = DateTimeFormatter.ofPattern( format ) .withZone( ZoneId.of( "GMT" ) ); String result = formatter.format( instant ); if( result.indexOf( '.' ) > 0 ) { if( result.endsWith( ".000" ) ) result = result.substring( 0, result.length() - 4 ); else if( result.endsWith( "00" ) ) result = result.substring( 0, result.length() - 2 ); else if( result.endsWith( "0" ) ) result = result.substring( 0, result.length() - 1 ); } if( optimize && result.endsWith( "00" ) ) result = result.substring( 0, result.length() - 2 ); result += "Z"; return result; } private TimeUtils(); } | TimeUtils { @NotNull public static String formatInstant( TemporalAccessor instant, String format, boolean optimize ) { DateTimeFormatter formatter = DateTimeFormatter.ofPattern( format ) .withZone( ZoneId.of( "GMT" ) ); String result = formatter.format( instant ); if( result.indexOf( '.' ) > 0 ) { if( result.endsWith( ".000" ) ) result = result.substring( 0, result.length() - 4 ); else if( result.endsWith( "00" ) ) result = result.substring( 0, result.length() - 2 ); else if( result.endsWith( "0" ) ) result = result.substring( 0, result.length() - 1 ); } if( optimize && result.endsWith( "00" ) ) result = result.substring( 0, result.length() - 2 ); result += "Z"; return result; } private TimeUtils(); @NotNull static String formatInstant( TemporalAccessor instant, String format, boolean optimize ); static boolean isUTCTimeValue( CharSequence value ); static boolean isGeneralizedTimeValue( CharSequence value ); static Instant parseGeneralizedTime( String value ); static Instant parseUTCTime( String value ); } | TimeUtils { @NotNull public static String formatInstant( TemporalAccessor instant, String format, boolean optimize ) { DateTimeFormatter formatter = DateTimeFormatter.ofPattern( format ) .withZone( ZoneId.of( "GMT" ) ); String result = formatter.format( instant ); if( result.indexOf( '.' ) > 0 ) { if( result.endsWith( ".000" ) ) result = result.substring( 0, result.length() - 4 ); else if( result.endsWith( "00" ) ) result = result.substring( 0, result.length() - 2 ); else if( result.endsWith( "0" ) ) result = result.substring( 0, result.length() - 1 ); } if( optimize && result.endsWith( "00" ) ) result = result.substring( 0, result.length() - 2 ); result += "Z"; return result; } private TimeUtils(); @NotNull static String formatInstant( TemporalAccessor instant, String format, boolean optimize ); static boolean isUTCTimeValue( CharSequence value ); static boolean isGeneralizedTimeValue( CharSequence value ); static Instant parseGeneralizedTime( String value ); static Instant parseUTCTime( String value ); static final String UTC_TIME_FORMAT; static final String GENERALIZED_TIME_FORMAT; @SuppressWarnings( "ConstantConditions" )
@NotNull
static final Charset CHARSET; } |
@Test public void testFormatInstant0() { Instant now = Instant.now(); LocalDateTime ldt = LocalDateTime.ofInstant( now, ZoneId.of( "GMT" ) ); ldt = ldt.withYear( 2000 ).withMonth( 1 ).withDayOfMonth( 1 ).withHour( 1 ).withMinute( 0 ).withSecond( 0 ) .withNano( 800000000 ); now = ldt.toInstant( ZoneOffset.UTC ); String result = TimeUtils.formatInstant( now, TimeUtils.GENERALIZED_TIME_FORMAT, true ); Assert.assertEquals( "Values are not equal", "20000101010000.8Z", result ); } | @NotNull public static String formatInstant( TemporalAccessor instant, String format, boolean optimize ) { DateTimeFormatter formatter = DateTimeFormatter.ofPattern( format ) .withZone( ZoneId.of( "GMT" ) ); String result = formatter.format( instant ); if( result.indexOf( '.' ) > 0 ) { if( result.endsWith( ".000" ) ) result = result.substring( 0, result.length() - 4 ); else if( result.endsWith( "00" ) ) result = result.substring( 0, result.length() - 2 ); else if( result.endsWith( "0" ) ) result = result.substring( 0, result.length() - 1 ); } if( optimize && result.endsWith( "00" ) ) result = result.substring( 0, result.length() - 2 ); result += "Z"; return result; } | TimeUtils { @NotNull public static String formatInstant( TemporalAccessor instant, String format, boolean optimize ) { DateTimeFormatter formatter = DateTimeFormatter.ofPattern( format ) .withZone( ZoneId.of( "GMT" ) ); String result = formatter.format( instant ); if( result.indexOf( '.' ) > 0 ) { if( result.endsWith( ".000" ) ) result = result.substring( 0, result.length() - 4 ); else if( result.endsWith( "00" ) ) result = result.substring( 0, result.length() - 2 ); else if( result.endsWith( "0" ) ) result = result.substring( 0, result.length() - 1 ); } if( optimize && result.endsWith( "00" ) ) result = result.substring( 0, result.length() - 2 ); result += "Z"; return result; } } | TimeUtils { @NotNull public static String formatInstant( TemporalAccessor instant, String format, boolean optimize ) { DateTimeFormatter formatter = DateTimeFormatter.ofPattern( format ) .withZone( ZoneId.of( "GMT" ) ); String result = formatter.format( instant ); if( result.indexOf( '.' ) > 0 ) { if( result.endsWith( ".000" ) ) result = result.substring( 0, result.length() - 4 ); else if( result.endsWith( "00" ) ) result = result.substring( 0, result.length() - 2 ); else if( result.endsWith( "0" ) ) result = result.substring( 0, result.length() - 1 ); } if( optimize && result.endsWith( "00" ) ) result = result.substring( 0, result.length() - 2 ); result += "Z"; return result; } private TimeUtils(); } | TimeUtils { @NotNull public static String formatInstant( TemporalAccessor instant, String format, boolean optimize ) { DateTimeFormatter formatter = DateTimeFormatter.ofPattern( format ) .withZone( ZoneId.of( "GMT" ) ); String result = formatter.format( instant ); if( result.indexOf( '.' ) > 0 ) { if( result.endsWith( ".000" ) ) result = result.substring( 0, result.length() - 4 ); else if( result.endsWith( "00" ) ) result = result.substring( 0, result.length() - 2 ); else if( result.endsWith( "0" ) ) result = result.substring( 0, result.length() - 1 ); } if( optimize && result.endsWith( "00" ) ) result = result.substring( 0, result.length() - 2 ); result += "Z"; return result; } private TimeUtils(); @NotNull static String formatInstant( TemporalAccessor instant, String format, boolean optimize ); static boolean isUTCTimeValue( CharSequence value ); static boolean isGeneralizedTimeValue( CharSequence value ); static Instant parseGeneralizedTime( String value ); static Instant parseUTCTime( String value ); } | TimeUtils { @NotNull public static String formatInstant( TemporalAccessor instant, String format, boolean optimize ) { DateTimeFormatter formatter = DateTimeFormatter.ofPattern( format ) .withZone( ZoneId.of( "GMT" ) ); String result = formatter.format( instant ); if( result.indexOf( '.' ) > 0 ) { if( result.endsWith( ".000" ) ) result = result.substring( 0, result.length() - 4 ); else if( result.endsWith( "00" ) ) result = result.substring( 0, result.length() - 2 ); else if( result.endsWith( "0" ) ) result = result.substring( 0, result.length() - 1 ); } if( optimize && result.endsWith( "00" ) ) result = result.substring( 0, result.length() - 2 ); result += "Z"; return result; } private TimeUtils(); @NotNull static String formatInstant( TemporalAccessor instant, String format, boolean optimize ); static boolean isUTCTimeValue( CharSequence value ); static boolean isGeneralizedTimeValue( CharSequence value ); static Instant parseGeneralizedTime( String value ); static Instant parseUTCTime( String value ); static final String UTC_TIME_FORMAT; static final String GENERALIZED_TIME_FORMAT; @SuppressWarnings( "ConstantConditions" )
@NotNull
static final Charset CHARSET; } |
@Test public void testValues() throws Exception { assertEquals( "Not equal", "1.E-1", NRxUtils.toCanonicalNR3( "0.01E1" ) ); assertEquals( "Not equal", "+0.E1", NRxUtils.toCanonicalNR3( "0.00000E1" ) ); assertEquals( "Not equal", "12312.E+0", NRxUtils.toCanonicalNR3( "12312" ) ); assertEquals( "Not equal", "12312123121231212312123121212.E-1231212312123121231212316", NRxUtils.toCanonicalNR3( "1231212312123121231212312.1212E-1231212312123121231212312" ) ); } | public static String toCanonicalNR3( String value ) { if( "-Infinity".equals( value ) || "Infinity".equals( value ) || "NaN".equals( value ) ) return value; if( !FORMAT_PATTERN.matcher( value ).matches() ) throw new IllegalArgumentException(); value = value.toUpperCase(); String mantisStr; String exponentStr; int expIndex = value.indexOf( 'E' ); if( expIndex == -1 ) { mantisStr = value; exponentStr = "0"; } else { mantisStr = value.substring( 0, expIndex ).trim(); exponentStr = value.substring( expIndex + 1 ).trim(); } int scale; String actualMantis; int dotIndex = mantisStr.indexOf( '.' ); if( dotIndex == -1 ) { scale = 0; actualMantis = mantisStr; } else { scale = mantisStr.length() - dotIndex - 1; String fracture = mantisStr.substring( dotIndex + 1 ); if( isAllZeros( fracture ) ) { scale -= fracture.length(); fracture = ""; } actualMantis = mantisStr.substring( 0, dotIndex ) + fracture; } return formatInt( actualMantis ) + ".E" + formatExponent( scale, exponentStr ); } | NRxUtils { public static String toCanonicalNR3( String value ) { if( "-Infinity".equals( value ) || "Infinity".equals( value ) || "NaN".equals( value ) ) return value; if( !FORMAT_PATTERN.matcher( value ).matches() ) throw new IllegalArgumentException(); value = value.toUpperCase(); String mantisStr; String exponentStr; int expIndex = value.indexOf( 'E' ); if( expIndex == -1 ) { mantisStr = value; exponentStr = "0"; } else { mantisStr = value.substring( 0, expIndex ).trim(); exponentStr = value.substring( expIndex + 1 ).trim(); } int scale; String actualMantis; int dotIndex = mantisStr.indexOf( '.' ); if( dotIndex == -1 ) { scale = 0; actualMantis = mantisStr; } else { scale = mantisStr.length() - dotIndex - 1; String fracture = mantisStr.substring( dotIndex + 1 ); if( isAllZeros( fracture ) ) { scale -= fracture.length(); fracture = ""; } actualMantis = mantisStr.substring( 0, dotIndex ) + fracture; } return formatInt( actualMantis ) + ".E" + formatExponent( scale, exponentStr ); } } | NRxUtils { public static String toCanonicalNR3( String value ) { if( "-Infinity".equals( value ) || "Infinity".equals( value ) || "NaN".equals( value ) ) return value; if( !FORMAT_PATTERN.matcher( value ).matches() ) throw new IllegalArgumentException(); value = value.toUpperCase(); String mantisStr; String exponentStr; int expIndex = value.indexOf( 'E' ); if( expIndex == -1 ) { mantisStr = value; exponentStr = "0"; } else { mantisStr = value.substring( 0, expIndex ).trim(); exponentStr = value.substring( expIndex + 1 ).trim(); } int scale; String actualMantis; int dotIndex = mantisStr.indexOf( '.' ); if( dotIndex == -1 ) { scale = 0; actualMantis = mantisStr; } else { scale = mantisStr.length() - dotIndex - 1; String fracture = mantisStr.substring( dotIndex + 1 ); if( isAllZeros( fracture ) ) { scale -= fracture.length(); fracture = ""; } actualMantis = mantisStr.substring( 0, dotIndex ) + fracture; } return formatInt( actualMantis ) + ".E" + formatExponent( scale, exponentStr ); } private NRxUtils(); } | NRxUtils { public static String toCanonicalNR3( String value ) { if( "-Infinity".equals( value ) || "Infinity".equals( value ) || "NaN".equals( value ) ) return value; if( !FORMAT_PATTERN.matcher( value ).matches() ) throw new IllegalArgumentException(); value = value.toUpperCase(); String mantisStr; String exponentStr; int expIndex = value.indexOf( 'E' ); if( expIndex == -1 ) { mantisStr = value; exponentStr = "0"; } else { mantisStr = value.substring( 0, expIndex ).trim(); exponentStr = value.substring( expIndex + 1 ).trim(); } int scale; String actualMantis; int dotIndex = mantisStr.indexOf( '.' ); if( dotIndex == -1 ) { scale = 0; actualMantis = mantisStr; } else { scale = mantisStr.length() - dotIndex - 1; String fracture = mantisStr.substring( dotIndex + 1 ); if( isAllZeros( fracture ) ) { scale -= fracture.length(); fracture = ""; } actualMantis = mantisStr.substring( 0, dotIndex ) + fracture; } return formatInt( actualMantis ) + ".E" + formatExponent( scale, exponentStr ); } private NRxUtils(); static String toCanonicalNR3( String value ); } | NRxUtils { public static String toCanonicalNR3( String value ) { if( "-Infinity".equals( value ) || "Infinity".equals( value ) || "NaN".equals( value ) ) return value; if( !FORMAT_PATTERN.matcher( value ).matches() ) throw new IllegalArgumentException(); value = value.toUpperCase(); String mantisStr; String exponentStr; int expIndex = value.indexOf( 'E' ); if( expIndex == -1 ) { mantisStr = value; exponentStr = "0"; } else { mantisStr = value.substring( 0, expIndex ).trim(); exponentStr = value.substring( expIndex + 1 ).trim(); } int scale; String actualMantis; int dotIndex = mantisStr.indexOf( '.' ); if( dotIndex == -1 ) { scale = 0; actualMantis = mantisStr; } else { scale = mantisStr.length() - dotIndex - 1; String fracture = mantisStr.substring( dotIndex + 1 ); if( isAllZeros( fracture ) ) { scale -= fracture.length(); fracture = ""; } actualMantis = mantisStr.substring( 0, dotIndex ) + fracture; } return formatInt( actualMantis ) + ".E" + formatExponent( scale, exponentStr ); } private NRxUtils(); static String toCanonicalNR3( String value ); } |
@Test( expected = IllegalArgumentException.class ) public void testNotTypeRef() { RefUtils.assertTypeRef( "a" ); } | public static void assertTypeRef( String name ) { if( !isTypeRef( name ) ) throw new IllegalArgumentException( "Not a type reference: " + name ); } | RefUtils { public static void assertTypeRef( String name ) { if( !isTypeRef( name ) ) throw new IllegalArgumentException( "Not a type reference: " + name ); } } | RefUtils { public static void assertTypeRef( String name ) { if( !isTypeRef( name ) ) throw new IllegalArgumentException( "Not a type reference: " + name ); } private RefUtils(); } | RefUtils { public static void assertTypeRef( String name ) { if( !isTypeRef( name ) ) throw new IllegalArgumentException( "Not a type reference: " + name ); } private RefUtils(); static void assertTypeRef( String name ); static boolean isSameAsDefaultValue( Scope scope, ComponentType component, Value resolve ); static boolean isTypeRef( CharSequence name ); static void assertValueRef( String name ); static boolean isValueRef( CharSequence name ); static boolean isIriValue( CharSequence value ); static void assertIriValue( String value ); static void resolutionValidate( Scope scope, Validation validation ); static Value toBasicValue( Scope scope, Ref<Value> ref ); static boolean isValueRef( @Nullable Ref<?> ref ); static boolean isTypeRef( @Nullable Ref<?> ref ); } | RefUtils { public static void assertTypeRef( String name ) { if( !isTypeRef( name ) ) throw new IllegalArgumentException( "Not a type reference: " + name ); } private RefUtils(); static void assertTypeRef( String name ); static boolean isSameAsDefaultValue( Scope scope, ComponentType component, Value resolve ); static boolean isTypeRef( CharSequence name ); static void assertValueRef( String name ); static boolean isValueRef( CharSequence name ); static boolean isIriValue( CharSequence value ); static void assertIriValue( String value ); static void resolutionValidate( Scope scope, Validation validation ); static Value toBasicValue( Scope scope, Ref<Value> ref ); static boolean isValueRef( @Nullable Ref<?> ref ); static boolean isTypeRef( @Nullable Ref<?> ref ); } |
@Test public void writeHugeReal() throws Exception { Asn1Factory factory = new DefaultAsn1Factory(); Module module = factory.types().dummyModule(); Scope scope = module.createScope(); ConstraintTemplate constraintTemplate = factory.constraints().valueRange( new RealValueFloat( 0.0f ), false, null, false ); Type tagged = factory.types().constrained( constraintTemplate, UniversalType.REAL.ref() ); Type defined = factory.types().define( "MyReal", tagged, null ); module.validate(); Value expected = new RealValueBig( new BigDecimal( BigInteger.valueOf( 34645 ).pow( 16663 ) ) ); byte[] result = InputUtils.writeValue( scope, defined, expected ); try( ByteArrayInputStream is = new ByteArrayInputStream( result ); AbstractBerReader reader = new DefaultBerReader( is, new CoreValueFactory() ) ) { Value value = reader.read( scope, defined ); Assert.assertEquals( "Values are not equal", expected, value ); } } | @SuppressWarnings( "NumericCastThatLosesPrecision" ) @Override public byte read() throws IOException { int read = is.read(); if( read != -1 ) position++; return (byte)read; } | DefaultBerReader extends AbstractBerReader { @SuppressWarnings( "NumericCastThatLosesPrecision" ) @Override public byte read() throws IOException { int read = is.read(); if( read != -1 ) position++; return (byte)read; } } | DefaultBerReader extends AbstractBerReader { @SuppressWarnings( "NumericCastThatLosesPrecision" ) @Override public byte read() throws IOException { int read = is.read(); if( read != -1 ) position++; return (byte)read; } DefaultBerReader( InputStream is, ValueFactory valueFactory ); } | DefaultBerReader extends AbstractBerReader { @SuppressWarnings( "NumericCastThatLosesPrecision" ) @Override public byte read() throws IOException { int read = is.read(); if( read != -1 ) position++; return (byte)read; } DefaultBerReader( InputStream is, ValueFactory valueFactory ); @Override int position(); @Override void skip( int amount ); @Override void skipToEoc(); @SuppressWarnings( "NumericCastThatLosesPrecision" ) @Override byte read(); @Override int read( byte[] buffer ); @Override void close(); } | DefaultBerReader extends AbstractBerReader { @SuppressWarnings( "NumericCastThatLosesPrecision" ) @Override public byte read() throws IOException { int read = is.read(); if( read != -1 ) position++; return (byte)read; } DefaultBerReader( InputStream is, ValueFactory valueFactory ); @Override int position(); @Override void skip( int amount ); @Override void skipToEoc(); @SuppressWarnings( "NumericCastThatLosesPrecision" ) @Override byte read(); @Override int read( byte[] buffer ); @Override void close(); } |
@Test( expected = IllegalArgumentException.class ) public void testNotValueRef() { RefUtils.assertValueRef( "A" ); } | public static void assertValueRef( String name ) { if( !isValueRef( name ) ) throw new IllegalArgumentException( "Not a value reference: " + name ); } | RefUtils { public static void assertValueRef( String name ) { if( !isValueRef( name ) ) throw new IllegalArgumentException( "Not a value reference: " + name ); } } | RefUtils { public static void assertValueRef( String name ) { if( !isValueRef( name ) ) throw new IllegalArgumentException( "Not a value reference: " + name ); } private RefUtils(); } | RefUtils { public static void assertValueRef( String name ) { if( !isValueRef( name ) ) throw new IllegalArgumentException( "Not a value reference: " + name ); } private RefUtils(); static void assertTypeRef( String name ); static boolean isSameAsDefaultValue( Scope scope, ComponentType component, Value resolve ); static boolean isTypeRef( CharSequence name ); static void assertValueRef( String name ); static boolean isValueRef( CharSequence name ); static boolean isIriValue( CharSequence value ); static void assertIriValue( String value ); static void resolutionValidate( Scope scope, Validation validation ); static Value toBasicValue( Scope scope, Ref<Value> ref ); static boolean isValueRef( @Nullable Ref<?> ref ); static boolean isTypeRef( @Nullable Ref<?> ref ); } | RefUtils { public static void assertValueRef( String name ) { if( !isValueRef( name ) ) throw new IllegalArgumentException( "Not a value reference: " + name ); } private RefUtils(); static void assertTypeRef( String name ); static boolean isSameAsDefaultValue( Scope scope, ComponentType component, Value resolve ); static boolean isTypeRef( CharSequence name ); static void assertValueRef( String name ); static boolean isValueRef( CharSequence name ); static boolean isIriValue( CharSequence value ); static void assertIriValue( String value ); static void resolutionValidate( Scope scope, Validation validation ); static Value toBasicValue( Scope scope, Ref<Value> ref ); static boolean isValueRef( @Nullable Ref<?> ref ); static boolean isTypeRef( @Nullable Ref<?> ref ); } |
@Test public void testSameAsDefault() throws Exception { MyIntegerValue value = new MyIntegerValue(); assertTrue( "Must be true", RefUtils.isSameAsDefaultValue( new MyScope(), new MyAbstractComponentType( value ), value ) ); } | public static boolean isSameAsDefaultValue( Scope scope, ComponentType component, Value resolve ) throws ResolutionException { if( component.getDefaultValue() == null ) return false; resolve = toBasicValue( scope, resolve ); Value value = toBasicValue( scope, component.getDefaultValue() ); return resolve.isEqualTo( value ); } | RefUtils { public static boolean isSameAsDefaultValue( Scope scope, ComponentType component, Value resolve ) throws ResolutionException { if( component.getDefaultValue() == null ) return false; resolve = toBasicValue( scope, resolve ); Value value = toBasicValue( scope, component.getDefaultValue() ); return resolve.isEqualTo( value ); } } | RefUtils { public static boolean isSameAsDefaultValue( Scope scope, ComponentType component, Value resolve ) throws ResolutionException { if( component.getDefaultValue() == null ) return false; resolve = toBasicValue( scope, resolve ); Value value = toBasicValue( scope, component.getDefaultValue() ); return resolve.isEqualTo( value ); } private RefUtils(); } | RefUtils { public static boolean isSameAsDefaultValue( Scope scope, ComponentType component, Value resolve ) throws ResolutionException { if( component.getDefaultValue() == null ) return false; resolve = toBasicValue( scope, resolve ); Value value = toBasicValue( scope, component.getDefaultValue() ); return resolve.isEqualTo( value ); } private RefUtils(); static void assertTypeRef( String name ); static boolean isSameAsDefaultValue( Scope scope, ComponentType component, Value resolve ); static boolean isTypeRef( CharSequence name ); static void assertValueRef( String name ); static boolean isValueRef( CharSequence name ); static boolean isIriValue( CharSequence value ); static void assertIriValue( String value ); static void resolutionValidate( Scope scope, Validation validation ); static Value toBasicValue( Scope scope, Ref<Value> ref ); static boolean isValueRef( @Nullable Ref<?> ref ); static boolean isTypeRef( @Nullable Ref<?> ref ); } | RefUtils { public static boolean isSameAsDefaultValue( Scope scope, ComponentType component, Value resolve ) throws ResolutionException { if( component.getDefaultValue() == null ) return false; resolve = toBasicValue( scope, resolve ); Value value = toBasicValue( scope, component.getDefaultValue() ); return resolve.isEqualTo( value ); } private RefUtils(); static void assertTypeRef( String name ); static boolean isSameAsDefaultValue( Scope scope, ComponentType component, Value resolve ); static boolean isTypeRef( CharSequence name ); static void assertValueRef( String name ); static boolean isValueRef( CharSequence name ); static boolean isIriValue( CharSequence value ); static void assertIriValue( String value ); static void resolutionValidate( Scope scope, Validation validation ); static Value toBasicValue( Scope scope, Ref<Value> ref ); static boolean isValueRef( @Nullable Ref<?> ref ); static boolean isTypeRef( @Nullable Ref<?> ref ); } |
@Test public void testConversion() throws Exception { assertEquals( "Is not equal", "0A", HexUtils.toHexString( new byte[]{0x0A} ) ); assertEquals( "Is not equal", "0A0A", HexUtils.toHexString( new byte[]{0x0A, 0x0A} ) ); assertEquals( "Is not equal", "", HexUtils.toHexString( new byte[]{} ) ); } | @SuppressWarnings( "MagicNumber" ) public static String toHexString( byte[] array ) { if( ArrayUtils.isEmpty( array ) ) return ""; StringBuilder sb = new StringBuilder(); for( byte value : array ) { if( ( value & 0xF0 ) == 0 ) sb.append( '0' ); sb.append( Integer.toHexString( value & 0xFF ).toUpperCase() ); } return sb.toString(); } | HexUtils { @SuppressWarnings( "MagicNumber" ) public static String toHexString( byte[] array ) { if( ArrayUtils.isEmpty( array ) ) return ""; StringBuilder sb = new StringBuilder(); for( byte value : array ) { if( ( value & 0xF0 ) == 0 ) sb.append( '0' ); sb.append( Integer.toHexString( value & 0xFF ).toUpperCase() ); } return sb.toString(); } } | HexUtils { @SuppressWarnings( "MagicNumber" ) public static String toHexString( byte[] array ) { if( ArrayUtils.isEmpty( array ) ) return ""; StringBuilder sb = new StringBuilder(); for( byte value : array ) { if( ( value & 0xF0 ) == 0 ) sb.append( '0' ); sb.append( Integer.toHexString( value & 0xFF ).toUpperCase() ); } return sb.toString(); } private HexUtils(); } | HexUtils { @SuppressWarnings( "MagicNumber" ) public static String toHexString( byte[] array ) { if( ArrayUtils.isEmpty( array ) ) return ""; StringBuilder sb = new StringBuilder(); for( byte value : array ) { if( ( value & 0xF0 ) == 0 ) sb.append( '0' ); sb.append( Integer.toHexString( value & 0xFF ).toUpperCase() ); } return sb.toString(); } private HexUtils(); @SuppressWarnings( "MagicNumber" ) static String toHexString( byte[] array ); } | HexUtils { @SuppressWarnings( "MagicNumber" ) public static String toHexString( byte[] array ) { if( ArrayUtils.isEmpty( array ) ) return ""; StringBuilder sb = new StringBuilder(); for( byte value : array ) { if( ( value & 0xF0 ) == 0 ) sb.append( '0' ); sb.append( Integer.toHexString( value & 0xFF ).toUpperCase() ); } return sb.toString(); } private HexUtils(); @SuppressWarnings( "MagicNumber" ) static String toHexString( byte[] array ); } |
@Test public void testConversion() throws Exception { IntegerValue value = new MyIntegerValue(); MyScope scope = new MyScope(); MyNamedValue namedValue = new MyNamedValue( (IntegerValue)RefUtils.toBasicValue( scope, value ) ); String result = CollectionUtils.convertToBString( Collections.singletonList( namedValue ), 4 ); assertEquals( "Is not equals", "'0100'B", result ); assertEquals( "Must be equal", value, RefUtils.toBasicValue( scope, namedValue ) ); } | @NotNull public static String convertToBString( Iterable<? extends Ref<Value>> valueList, int desiredSize ) { Collection<Long> values = new HashSet<>(); Long maxValue = 0L; for( Ref<Value> valueRef : valueList ) { NamedValue value = (NamedValue)valueRef; if( value.getReferenceKind() != Kind.INTEGER || !value.toIntegerValue().isLong() ) throw new IllegalStateException(); Long longValue = value.toIntegerValue().asLong(); values.add( longValue ); maxValue = Math.max( maxValue, longValue ); } if( desiredSize > -1 ) { if( maxValue > ( desiredSize - 1 ) ) throw new IllegalArgumentException( "Unable to truncate data. Desired size is smaller than expected: current = " + ( maxValue + 1 ) + " desired = " + desiredSize ); maxValue = (long)desiredSize - 1; } StringBuilder sb = new StringBuilder(); sb.append( '\'' ); for( long value = 0; value <= maxValue; value++ ) sb.append( values.contains( value ) ? '1' : '0' ); sb.append( "'B" ); return sb.toString(); } | CollectionUtils { @NotNull public static String convertToBString( Iterable<? extends Ref<Value>> valueList, int desiredSize ) { Collection<Long> values = new HashSet<>(); Long maxValue = 0L; for( Ref<Value> valueRef : valueList ) { NamedValue value = (NamedValue)valueRef; if( value.getReferenceKind() != Kind.INTEGER || !value.toIntegerValue().isLong() ) throw new IllegalStateException(); Long longValue = value.toIntegerValue().asLong(); values.add( longValue ); maxValue = Math.max( maxValue, longValue ); } if( desiredSize > -1 ) { if( maxValue > ( desiredSize - 1 ) ) throw new IllegalArgumentException( "Unable to truncate data. Desired size is smaller than expected: current = " + ( maxValue + 1 ) + " desired = " + desiredSize ); maxValue = (long)desiredSize - 1; } StringBuilder sb = new StringBuilder(); sb.append( '\'' ); for( long value = 0; value <= maxValue; value++ ) sb.append( values.contains( value ) ? '1' : '0' ); sb.append( "'B" ); return sb.toString(); } } | CollectionUtils { @NotNull public static String convertToBString( Iterable<? extends Ref<Value>> valueList, int desiredSize ) { Collection<Long> values = new HashSet<>(); Long maxValue = 0L; for( Ref<Value> valueRef : valueList ) { NamedValue value = (NamedValue)valueRef; if( value.getReferenceKind() != Kind.INTEGER || !value.toIntegerValue().isLong() ) throw new IllegalStateException(); Long longValue = value.toIntegerValue().asLong(); values.add( longValue ); maxValue = Math.max( maxValue, longValue ); } if( desiredSize > -1 ) { if( maxValue > ( desiredSize - 1 ) ) throw new IllegalArgumentException( "Unable to truncate data. Desired size is smaller than expected: current = " + ( maxValue + 1 ) + " desired = " + desiredSize ); maxValue = (long)desiredSize - 1; } StringBuilder sb = new StringBuilder(); sb.append( '\'' ); for( long value = 0; value <= maxValue; value++ ) sb.append( values.contains( value ) ? '1' : '0' ); sb.append( "'B" ); return sb.toString(); } private CollectionUtils(); } | CollectionUtils { @NotNull public static String convertToBString( Iterable<? extends Ref<Value>> valueList, int desiredSize ) { Collection<Long> values = new HashSet<>(); Long maxValue = 0L; for( Ref<Value> valueRef : valueList ) { NamedValue value = (NamedValue)valueRef; if( value.getReferenceKind() != Kind.INTEGER || !value.toIntegerValue().isLong() ) throw new IllegalStateException(); Long longValue = value.toIntegerValue().asLong(); values.add( longValue ); maxValue = Math.max( maxValue, longValue ); } if( desiredSize > -1 ) { if( maxValue > ( desiredSize - 1 ) ) throw new IllegalArgumentException( "Unable to truncate data. Desired size is smaller than expected: current = " + ( maxValue + 1 ) + " desired = " + desiredSize ); maxValue = (long)desiredSize - 1; } StringBuilder sb = new StringBuilder(); sb.append( '\'' ); for( long value = 0; value <= maxValue; value++ ) sb.append( values.contains( value ) ? '1' : '0' ); sb.append( "'B" ); return sb.toString(); } private CollectionUtils(); @NotNull static String convertToBString( Iterable<? extends Ref<Value>> valueList, int desiredSize ); } | CollectionUtils { @NotNull public static String convertToBString( Iterable<? extends Ref<Value>> valueList, int desiredSize ) { Collection<Long> values = new HashSet<>(); Long maxValue = 0L; for( Ref<Value> valueRef : valueList ) { NamedValue value = (NamedValue)valueRef; if( value.getReferenceKind() != Kind.INTEGER || !value.toIntegerValue().isLong() ) throw new IllegalStateException(); Long longValue = value.toIntegerValue().asLong(); values.add( longValue ); maxValue = Math.max( maxValue, longValue ); } if( desiredSize > -1 ) { if( maxValue > ( desiredSize - 1 ) ) throw new IllegalArgumentException( "Unable to truncate data. Desired size is smaller than expected: current = " + ( maxValue + 1 ) + " desired = " + desiredSize ); maxValue = (long)desiredSize - 1; } StringBuilder sb = new StringBuilder(); sb.append( '\'' ); for( long value = 0; value <= maxValue; value++ ) sb.append( values.contains( value ) ? '1' : '0' ); sb.append( "'B" ); return sb.toString(); } private CollectionUtils(); @NotNull static String convertToBString( Iterable<? extends Ref<Value>> valueList, int desiredSize ); } |
@Test( expected = IllegalStateException.class ) public void testIllegalRef() throws Exception { TemplateParameter parameter = new TemplateParameter( 0, scope -> { throw new UnsupportedOperationException(); }, null ); parameter.getName(); fail( "Must fail" ); } | public String getName() { if( reference instanceof TypeNameRef ) return ( (TypeNameRef)reference ).getName(); if( reference instanceof ValueNameRef ) return ( (ValueNameRef)reference ).getName(); throw new IllegalStateException(); } | TemplateParameter implements Comparable<TemplateParameter> { public String getName() { if( reference instanceof TypeNameRef ) return ( (TypeNameRef)reference ).getName(); if( reference instanceof ValueNameRef ) return ( (ValueNameRef)reference ).getName(); throw new IllegalStateException(); } } | TemplateParameter implements Comparable<TemplateParameter> { public String getName() { if( reference instanceof TypeNameRef ) return ( (TypeNameRef)reference ).getName(); if( reference instanceof ValueNameRef ) return ( (ValueNameRef)reference ).getName(); throw new IllegalStateException(); } TemplateParameter( int index, @NotNull Ref<?> reference, @Nullable Ref<Type> governor ); } | TemplateParameter implements Comparable<TemplateParameter> { public String getName() { if( reference instanceof TypeNameRef ) return ( (TypeNameRef)reference ).getName(); if( reference instanceof ValueNameRef ) return ( (ValueNameRef)reference ).getName(); throw new IllegalStateException(); } TemplateParameter( int index, @NotNull Ref<?> reference, @Nullable Ref<Type> governor ); int getIndex(); String getName(); @SuppressWarnings( "unchecked" ) Ref<T> getReference(); @Nullable Ref<Type> getGovernor(); boolean isTypeRef(); boolean isValueRef(); @SuppressWarnings( "unchecked" ) @Override boolean equals( Object obj ); @Override int hashCode(); @Override String toString(); @Override int compareTo( @NotNull TemplateParameter o ); } | TemplateParameter implements Comparable<TemplateParameter> { public String getName() { if( reference instanceof TypeNameRef ) return ( (TypeNameRef)reference ).getName(); if( reference instanceof ValueNameRef ) return ( (ValueNameRef)reference ).getName(); throw new IllegalStateException(); } TemplateParameter( int index, @NotNull Ref<?> reference, @Nullable Ref<Type> governor ); int getIndex(); String getName(); @SuppressWarnings( "unchecked" ) Ref<T> getReference(); @Nullable Ref<Type> getGovernor(); boolean isTypeRef(); boolean isValueRef(); @SuppressWarnings( "unchecked" ) @Override boolean equals( Object obj ); @Override int hashCode(); @Override String toString(); @Override int compareTo( @NotNull TemplateParameter o ); } |
@Test public void testTemplate() throws Exception { Template template = new Template(); assertEquals( "Parameter count must be 0", 0, template.getParameterCount() ); template.addParameter( new TemplateParameter( 0, new TypeNameRef( "A" ), null ) ); assertEquals( "Parameter count must be 1", 1, template.getParameterCount() ); assertNotNull( "Must not be null", template.getParameter( 0 ) ); assertNotNull( "Must not be null", template.getParameter( "A" ) ); assertFalse( "Must not be instance", template.isInstance() ); } | public Template() { this( false ); } | Template { public Template() { this( false ); } } | Template { public Template() { this( false ); } Template(); Template( boolean instance ); } | Template { public Template() { this( false ); } Template(); Template( boolean instance ); void addParameter( TemplateParameter parameter ); @Nullable TemplateParameter getParameter( @NotNull String name ); @NotNull TemplateParameter getParameter( int index ); int getParameterCount(); boolean isInstance(); } | Template { public Template() { this( false ); } Template(); Template( boolean instance ); void addParameter( TemplateParameter parameter ); @Nullable TemplateParameter getParameter( @NotNull String name ); @NotNull TemplateParameter getParameter( int index ); int getParameterCount(); boolean isInstance(); } |
@Test( expected = IllegalArgumentException.class ) public void testIllegalIndexGet() throws Exception { Template template = new Template(); template.getParameter( 1 ); fail( "Must fail" ); } | @Nullable public TemplateParameter getParameter( @NotNull String name ) { return parameterMap.get( name ); } | Template { @Nullable public TemplateParameter getParameter( @NotNull String name ) { return parameterMap.get( name ); } } | Template { @Nullable public TemplateParameter getParameter( @NotNull String name ) { return parameterMap.get( name ); } Template(); Template( boolean instance ); } | Template { @Nullable public TemplateParameter getParameter( @NotNull String name ) { return parameterMap.get( name ); } Template(); Template( boolean instance ); void addParameter( TemplateParameter parameter ); @Nullable TemplateParameter getParameter( @NotNull String name ); @NotNull TemplateParameter getParameter( int index ); int getParameterCount(); boolean isInstance(); } | Template { @Nullable public TemplateParameter getParameter( @NotNull String name ) { return parameterMap.get( name ); } Template(); Template( boolean instance ); void addParameter( TemplateParameter parameter ); @Nullable TemplateParameter getParameter( @NotNull String name ); @NotNull TemplateParameter getParameter( int index ); int getParameterCount(); boolean isInstance(); } |
@Test( expected = IllegalArgumentException.class ) public void testDuplicateFail() throws Exception { mapperFactory.mapType( Values.class, null ); fail( "Must fail" ); } | @SuppressWarnings( "unchecked" ) @Override public TypeMapper mapType( Type type, TypeMetadata metadata ) { if( !isSupportedFor( type ) ) throw new IllegalArgumentException( "Only enum types allowed" ); return mapEnum( (Class<Enum<?>>)type ); } | EnumTypeMapperFactory implements TypeMapperFactory { @SuppressWarnings( "unchecked" ) @Override public TypeMapper mapType( Type type, TypeMetadata metadata ) { if( !isSupportedFor( type ) ) throw new IllegalArgumentException( "Only enum types allowed" ); return mapEnum( (Class<Enum<?>>)type ); } } | EnumTypeMapperFactory implements TypeMapperFactory { @SuppressWarnings( "unchecked" ) @Override public TypeMapper mapType( Type type, TypeMetadata metadata ) { if( !isSupportedFor( type ) ) throw new IllegalArgumentException( "Only enum types allowed" ); return mapEnum( (Class<Enum<?>>)type ); } EnumTypeMapperFactory( TypeMapperContext context, Asn1Factory factory ); } | EnumTypeMapperFactory implements TypeMapperFactory { @SuppressWarnings( "unchecked" ) @Override public TypeMapper mapType( Type type, TypeMetadata metadata ) { if( !isSupportedFor( type ) ) throw new IllegalArgumentException( "Only enum types allowed" ); return mapEnum( (Class<Enum<?>>)type ); } EnumTypeMapperFactory( TypeMapperContext context, Asn1Factory factory ); @Override int getPriority(); @Override boolean isSupportedFor( Type type ); @SuppressWarnings( "unchecked" ) @Override TypeMapper mapType( Type type, TypeMetadata metadata ); } | EnumTypeMapperFactory implements TypeMapperFactory { @SuppressWarnings( "unchecked" ) @Override public TypeMapper mapType( Type type, TypeMetadata metadata ) { if( !isSupportedFor( type ) ) throw new IllegalArgumentException( "Only enum types allowed" ); return mapEnum( (Class<Enum<?>>)type ); } EnumTypeMapperFactory( TypeMapperContext context, Asn1Factory factory ); @Override int getPriority(); @Override boolean isSupportedFor( Type type ); @SuppressWarnings( "unchecked" ) @Override TypeMapper mapType( Type type, TypeMetadata metadata ); } |
@Test( expected = IllegalArgumentException.class ) public void testUnsupportedType() throws Exception { mapperFactory.mapType( Integer.class, null ); fail( "Must fail!" ); } | @SuppressWarnings( "unchecked" ) @Override public TypeMapper mapType( Type type, TypeMetadata metadata ) { if( !isSupportedFor( type ) ) throw new IllegalArgumentException( "Only enum types allowed" ); return mapEnum( (Class<Enum<?>>)type ); } | EnumTypeMapperFactory implements TypeMapperFactory { @SuppressWarnings( "unchecked" ) @Override public TypeMapper mapType( Type type, TypeMetadata metadata ) { if( !isSupportedFor( type ) ) throw new IllegalArgumentException( "Only enum types allowed" ); return mapEnum( (Class<Enum<?>>)type ); } } | EnumTypeMapperFactory implements TypeMapperFactory { @SuppressWarnings( "unchecked" ) @Override public TypeMapper mapType( Type type, TypeMetadata metadata ) { if( !isSupportedFor( type ) ) throw new IllegalArgumentException( "Only enum types allowed" ); return mapEnum( (Class<Enum<?>>)type ); } EnumTypeMapperFactory( TypeMapperContext context, Asn1Factory factory ); } | EnumTypeMapperFactory implements TypeMapperFactory { @SuppressWarnings( "unchecked" ) @Override public TypeMapper mapType( Type type, TypeMetadata metadata ) { if( !isSupportedFor( type ) ) throw new IllegalArgumentException( "Only enum types allowed" ); return mapEnum( (Class<Enum<?>>)type ); } EnumTypeMapperFactory( TypeMapperContext context, Asn1Factory factory ); @Override int getPriority(); @Override boolean isSupportedFor( Type type ); @SuppressWarnings( "unchecked" ) @Override TypeMapper mapType( Type type, TypeMetadata metadata ); } | EnumTypeMapperFactory implements TypeMapperFactory { @SuppressWarnings( "unchecked" ) @Override public TypeMapper mapType( Type type, TypeMetadata metadata ) { if( !isSupportedFor( type ) ) throw new IllegalArgumentException( "Only enum types allowed" ); return mapEnum( (Class<Enum<?>>)type ); } EnumTypeMapperFactory( TypeMapperContext context, Asn1Factory factory ); @Override int getPriority(); @Override boolean isSupportedFor( Type type ); @SuppressWarnings( "unchecked" ) @Override TypeMapper mapType( Type type, TypeMetadata metadata ); } |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.