src_fm_fc_ms_ff stringlengths 43 86.8k | target stringlengths 20 276k |
|---|---|
ImageRecord implements Comparable<ImageRecord> { @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; ImageRecord other = (ImageRecord) obj; if (pHash != other.pHash) return false; if (path == null) { if (other.path !=... | @Test public void testEquals() throws Exception { EqualsVerifier.forClass(ImageRecord.class).suppress(Warning.NONFINAL_FIELDS).verify(); } |
ImageRecord implements Comparable<ImageRecord> { @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("ImageRecord"); sb.append("{"); sb.append("path:"); sb.append(path); sb.append(","); sb.append("hash:"); sb.append(pHash); sb.append("}"); return sb.toString(); } @Deprecated ImageRec... | @Test public void testToString() throws Exception { assertThat(imageRecord.toString(), is(EXPECTED_TO_STRING)); } |
BadFileRecord { public String getPath() { return path; } @Deprecated BadFileRecord(); BadFileRecord(Path path); String getPath(); } | @Test public void testGetPath() throws Exception { assertThat(badFileRecord.getPath(), is("bad")); } |
RepositoryException extends Exception { public final String getMessage() { return message; } RepositoryException(String message, Throwable cause); RepositoryException(String message); final String getMessage(); final Throwable getCause(); } | @Test public void testRepositoryExceptionStringThrowableMessage() throws Exception { cut = new RepositoryException(TEST_MESSAGE, testException); assertThat(cut.getMessage(), is(TEST_MESSAGE)); }
@Test public void testRepositoryExceptionStringMessage() throws Exception { cut = new RepositoryException(TEST_MESSAGE); asse... |
RepositoryException extends Exception { public final Throwable getCause() { return cause; } RepositoryException(String message, Throwable cause); RepositoryException(String message); final String getMessage(); final Throwable getCause(); } | @Test public void testRepositoryExceptionStringThrowableCause() throws Exception { cut = new RepositoryException(TEST_MESSAGE, testException); assertThat(cut.getCause(), is(testException)); }
@Test public void testRepositoryExceptionStringCause() throws Exception { cut = new RepositoryException(TEST_MESSAGE); assertTha... |
OrmliteRepositoryFactory implements RepositoryFactory { @Override public FilterRepository buildFilterRepository() throws RepositoryException { return new OrmliteFilterRepository(filterRecordDao, thumbnailDao); } @Inject OrmliteRepositoryFactory(Database database); @Override FilterRepository buildFilterRepository(); @O... | @Test public void testBuildFilterRepository() throws Exception { FilterRepository fr = cut.buildFilterRepository(); fr.store(new FilterRecord(0, new Tag(TEST_STRING))); } |
OrmliteRepositoryFactory implements RepositoryFactory { @Override public ImageRepository buildImageRepository() throws RepositoryException { return new OrmliteImageRepository(imageRecordDao, ignoreDao); } @Inject OrmliteRepositoryFactory(Database database); @Override FilterRepository buildFilterRepository(); @Override... | @Test public void testBuildImageRepository() throws Exception { ImageRepository ir = cut.buildImageRepository(); ir.store(new ImageRecord(TEST_STRING, 0)); } |
OrmliteRepositoryFactory implements RepositoryFactory { @Override public TagRepository buildTagRepository() throws RepositoryException { return new OrmliteTagRepository(tagDao); } @Inject OrmliteRepositoryFactory(Database database); @Override FilterRepository buildFilterRepository(); @Override ImageRepository buildIma... | @Test public void testBuildTagRepository() throws Exception { TagRepository tr = cut.buildTagRepository(); tr.store(new Tag(TEST_STRING)); } |
OrmliteRepositoryFactory implements RepositoryFactory { @Override public PendingHashImageRepository buildPendingHashImageRepository() throws RepositoryException { return new OrmlitePendingHashImage(pendingDao); } @Inject OrmliteRepositoryFactory(Database database); @Override FilterRepository buildFilterRepository(); @... | @Test public void testBuildPendingImageRepository() throws Exception { PendingHashImageRepository phir = cut.buildPendingHashImageRepository(); phir.store(new PendingHashImage(TEST_STRING, 0, 0)); } |
OrmliteRepositoryFactory implements RepositoryFactory { @Override public IgnoreRepository buildIgnoreRepository() throws RepositoryException { return new OrmliteIgnoreRepository(ignoreDao); } @Inject OrmliteRepositoryFactory(Database database); @Override FilterRepository buildFilterRepository(); @Override ImageReposit... | @Test public void testBuildIgnoreRepository() throws Exception { IgnoreRepository ir = cut.buildIgnoreRepository(); ir.store(new IgnoreRecord(new ImageRecord(TEST_STRING, 0))); } |
OrmlitePendingHashImage implements PendingHashImageRepository { @Override public synchronized boolean store(PendingHashImage image) throws RepositoryException { try { if (pendingDao.queryForMatchingArgs(image).isEmpty()) { pendingDao.create(image); return true; } else { return false; } } catch (SQLException e) { throw ... | @Test public void testStoreQueryDatabase() throws Exception { cut.store(newEntry); assertThat(dao.queryForMatchingArgs(newEntry), hasSize(1)); }
@Test public void testStoreReturnValue() throws Exception { assertThat(cut.store(newEntry), is(true)); }
@Test public void testStoreDuplicate() throws Exception { assertThat(c... |
ExtendedAttribute implements ExtendedAttributeQuery { public static boolean supportsExtendedAttributes(Path path) { try { return Files.getFileStore(path).supportsFileAttributeView(UserDefinedFileAttributeView.class); } catch (IOException e) { LOGGER.debug("Failed to check extended attributes via FileStore ({}) for {}, ... | @Test public void testSupportsExtendedAttributes() throws Exception { assertThat(ExtendedAttribute.supportsExtendedAttributes(tempFile), is(true)); }
@Test public void testSupportsExtendedAttributesNoFile() throws Exception { assertThat(ExtendedAttribute.supportsExtendedAttributes(Jimfs.newFileSystem().getPath("noEAsup... |
OrmlitePendingHashImage implements PendingHashImageRepository { @Override public boolean exists(PendingHashImage image) throws RepositoryException { try { if (pendingDao.refresh(image) == 0) { return !pendingDao.queryForMatching(image).isEmpty(); } else { return true; } } catch (SQLException e) { throw new RepositoryEx... | @Test public void testExistsById() throws Exception { assertThat(cut.exists(existingEntry), is(true)); }
@Test public void testExistsByPath() throws Exception { assertThat(cut.exists(new PendingHashImage(EXISTING_PATH, UUID_EXISTING)), is(true)); }
@Test public void testExistsNotFound() throws Exception { assertThat(cu... |
OrmlitePendingHashImage implements PendingHashImageRepository { @Override public List<PendingHashImage> getAll() throws RepositoryException { try { return pendingDao.queryForAll(); } catch (SQLException e) { throw new RepositoryException("Failed to query for all entries", e); } } OrmlitePendingHashImage(Dao<PendingHash... | @Test public void testGetAll() throws Exception { dao.create(newEntry); assertThat(cut.getAll(), containsInAnyOrder(newEntry, existingEntry)); } |
OrmlitePendingHashImage implements PendingHashImageRepository { @Override public PendingHashImage getByUUID(long most, long least) throws RepositoryException { try { synchronized (uuidQuery) { mostParam.setValue(most); leastParam.setValue(least); return pendingDao.queryForFirst(uuidQuery); } } catch (SQLException e) { ... | @Test public void testGetByUuidNonExisting() throws Exception { assertThat(cut.getByUUID(UUID_NEW.getMostSignificantBits(), UUID_NEW.getLeastSignificantBits()), is(nullValue())); }
@Test public void testGetByUuidExisting() throws Exception { assertThat(cut.getByUUID(UUID_EXISTING.getMostSignificantBits(), UUID_EXISTING... |
OrmlitePendingHashImage implements PendingHashImageRepository { @Override public void remove(PendingHashImage image) throws RepositoryException { try { pendingDao.delete(image); } catch (SQLException e) { throw new RepositoryException("Failed to remove entry", e); } } OrmlitePendingHashImage(Dao<PendingHashImage, Integ... | @Test public void testRemove() throws Exception { assertThat(dao.queryForSameId(existingEntry), is(notNullValue())); cut.remove(existingEntry); assertThat(dao.queryForSameId(existingEntry), is(nullValue())); } |
OrmliteImageRepository implements ImageRepository { @Override public void store(ImageRecord image) throws RepositoryException { try { imageDao.createOrUpdate(image); } catch (SQLException e) { throw new RepositoryException("Failed to store image", e); } } OrmliteImageRepository(Dao<ImageRecord, String> imageDao, Dao<Ig... | @Test public void testStore() throws Exception { cut.store(imageNew); assertThat(imageDao.queryForId(pathNew), is(imageNew)); } |
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, T... | @Test public void getPeer_one() throws Exception{ SeedPeers seedPeers = new SeedPeers(NetworkParameters.prodNet()); assertThat(seedPeers.getPeer(), notNullValue()); }
@Test public void getPeer_all() throws Exception{ SeedPeers seedPeers = new SeedPeers(NetworkParameters.prodNet()); for(int i = 0; i < SeedPeers.seedAddr... |
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 toSt... | @Test public void testBad_Amount() throws LitecoinURIParseException { try { testObject = new LitecoinURI(NetworkParameters.prodNet(), LitecoinURI.LITECOIN_SCHEME + ":" + PRODNET_GOOD_ADDRESS + "?amount="); fail("Expecting LitecoinURIParseException"); } catch (LitecoinURIParseException e) { assertTrue(e.getMessage().con... |
WalletProtobufSerializer { public Protos.Wallet walletToProto(Wallet wallet) { Protos.Wallet.Builder walletBuilder = Protos.Wallet.newBuilder(); walletBuilder.setNetworkIdentifier(wallet.getNetworkParameters().getId()); if (wallet.getDescription() != null) { walletBuilder.setDescription(wallet.getDescription()); } for ... | @Test public void oneTx() throws Exception { BigInteger v1 = Utils.toNanoCoins(1, 0); Transaction t1 = createFakeTx(params, v1, myAddress); t1.getConfidence().markBroadcastBy(new PeerAddress(InetAddress.getByName("1.2.3.4"))); t1.getConfidence().markBroadcastBy(new PeerAddress(InetAddress.getByName("5.6.7.8"))); t1.get... |
Wallet implements Serializable, BlockChainListener { public Transaction createSend(Address address, BigInteger nanocoins) { SendRequest req = SendRequest.to(address, nanocoins); if (completeTx(req)) { return req.tx; } else { return null; } } Wallet(NetworkParameters params); Wallet(NetworkParameters params, KeyCrypter... | @Test public void balances() throws Exception { BigInteger nanos = Utils.toNanoCoins(1, 0); Transaction tx1 = sendMoneyToWallet(nanos, AbstractBlockChain.NewBlockType.BEST_CHAIN); assertEquals(nanos, tx1.getValueSentToMe(wallet, true)); Transaction send1 = wallet.createSend(new ECKey().toAddress(params), toNanoCoins(0,... |
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... | @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... |
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(... | @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+... |
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 S... | @Test public void testIp() throws Exception { byte[] bytes = Hex.decode("41043e96222332ea7848323c08116dddafbfa917b8e37f0bdf63841628267148588a09a43540942d58d49717ad3fabfe14978cf4f0a8b84d2435dad16e9aa4d7f935ac"); Script s = new Script(params, bytes, 0, bytes.length); assertTrue(s.isSentToRawPubKey()); } |
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 Linke... | @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.r... |
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); stati... | @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("3f2ebb6c8d... |
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[] ha... | @Test public void getNetwork() throws Exception { NetworkParameters params = Address.getParametersFromAddress("LQz2pJYaeqntA9BFB8rDX5AL2TTKGd5AuN"); assertEquals(NetworkParameters.prodNet().getId(), params.getId()); params = Address.getParametersFromAddress("n4eA2nbYqErp7H6jebchxAN59DmNpksexv"); assertEquals(NetworkPar... |
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.s... | @Test public void testDecode() throws Exception { NetworkParameters params = NetworkParameters.unitTests(); VersionMessage ver = new VersionMessage(params, Hex.decode("71110100000000000000000048e5e95000000000000000000000000000000000000000000000ffff7f000001479d000000000000000000000000000000000000ffff7f000001479d00000000... |
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[]... | @Test public void testWork() throws Exception { BigInteger work = params.genesisBlock.getWork(); assertEquals(BigInteger.valueOf(536879104L), work); } |
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 he... | @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()); } |
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); BigIntege... | @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... |
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(); InetSoc... | @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)); } |
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, boo... | @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.to... |
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, AbstractBlock... | @Test public void testAddEventListener() throws Exception { control.replay(); connect(); PeerEventListener listener = new AbstractPeerEventListener(); peer.addEventListener(listener); assertTrue(peer.removeEventListener(listener)); assertFalse(peer.removeEventListener(listener)); } |
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(N... | @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.startBlockChainD... |
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, AbstractBlockCh... | @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(Invento... |
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, Vers... | @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()); GetDataMess... |
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 { r... | @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);... |
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(NetworkParameter... | @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... |
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 createCli... | @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);... |
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 { add... | @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[]{"... |
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(NetworkPara... | @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 AbstractPeerEven... |
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,... | @Test public void testHeaders1() throws Exception { LitecoinSerializer bs = new LitecoinSerializer(NetworkParameters.prodNet()); ByteArrayInputStream bais = new ByteArrayInputStream(Hex.decode("fbc0b6db686561" + "646572730000000000520000005d4fab8101010000006fe28c0ab6f1b372c1a6a246ae6" + "3f74f931e8365e15a089c68d6190000... |
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(B... | @Test public void verifyMessage() throws Exception { String message = "hello"; String sigBase64 = "HxNZdo6ggZ41hd3mM3gfJRqOQPZYcO8z8qdX2BwmpbF11CaOQV+QiZGGQxaYOncKoNW61oRuSMMF8udfK54XqI8="; Address expectedAddress = new Address(NetworkParameters.prodNet(), "LNmLhahYB2gb3Hf3ZJsGaTyhG3HPDEPXfn"); ECKey key = ECKey.signed... |
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 = en... | @Test public void testEncryptionIsReversible() throws Exception { ECKey originalUnencryptedKey = new ECKey(); EncryptedPrivateKey encryptedPrivateKey = keyCrypter.encrypt(originalUnencryptedKey.getPrivKeyBytes(), keyCrypter.deriveKey(PASSWORD1)); ECKey encryptedKey = new ECKey(encryptedPrivateKey, originalUnencryptedKe... |
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(); E... | @Test public void testToString() throws Exception { ECKey key = new ECKey(BigInteger.TEN); assertEquals("pub:04a0434d9e47f3c86235477c7b1ae6ae5d3442d49b1943c2b752a68e2a47e247c7893aba425419bc27a3b6c7e693a24c696f794c2ed877a1593cbee53b037368d7", key.toString()); assertEquals("pub:04a0434d9e47f3c86235477c7b1ae6ae5d3442d49b1... |
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 ... | @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) { } assertE... |
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, ... | @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.val... |
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 t... | @Test public void testReverseBytes() { Assert.assertArrayEquals(new byte[] {1,2,3,4,5}, Utils.reverseBytes(new byte[] {5,4,3,2,1})); } |
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.arr... | @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.reverseDwor... |
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... | @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"), ... |
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... | @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()); } |
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... | @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'='LQz2pJYaeqntA9BFB8rDX5AL2TT... |
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 getRecipients() { dao.getRecipients(); } |
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... | @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); }
@Test public void nowWithoutSpacesAndUnitOfMeasure() { Que... |
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 deleteRecipient() { Recipient recip = new Recipient("SMS", "test2@example.com"); dao.saveRecipient(recip); Assert.assertEquals(1, dao.getRecipients().size()); dao.deleteRecipient(recip); Assert.assertEquals(0, dao.getRecipients().size()); } |
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.pe... | @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."); }
@Test public void testDateDiff() { final String expression = "2016/07/04 -... |
Book { public void addAuthor(Author author) { authors.add(createAuthorRef(author)); } void addAuthor(Author author); } | @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); } |
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.g... | @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( Enc... |
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( "Una... | @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", "&TypeCon... |
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 Constr... | @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( constra... |
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 V... | @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 ) : fa... |
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, bo... | @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... |
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( TemporalAcc... | @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.ass... |
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( 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( Enco... |
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( ... | @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 ... |
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... | @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", "12312123121... |
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... | @Test( expected = IllegalArgumentException.class ) public void testNotTypeRef() { RefUtils.assertTypeRef( "a" ); } |
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 v... | @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 ... |
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 ); sta... | @Test( expected = IllegalArgumentException.class ) public void testNotValueRef() { RefUtils.assertValueRef( "A" ); } |
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.isE... | @Test public void testSameAsDefault() throws Exception { MyIntegerValue value = new MyIntegerValue(); assertTrue( "Must be true", RefUtils.isSameAsDefaultValue( new MyScope(), new MyAbstractComponentType( value ), value ) ); } |
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() ); ... | @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[]{} ) ); } |
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 ||... | @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 ... |
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 ind... | @Test( expected = IllegalStateException.class ) public void testIllegalRef() throws Exception { TemplateParameter parameter = new TemplateParameter( 0, scope -> { throw new UnsupportedOperationException(); }, null ); parameter.getName(); fail( "Must fail" ); } |
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 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.getParameterCoun... |
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( ... | @Test( expected = IllegalArgumentException.class ) public void testIllegalIndexGet() throws Exception { Template template = new Template(); template.getParameter( 1 ); fail( "Must fail" ); } |
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( ... | @Test( expected = IllegalArgumentException.class ) public void testDuplicateFail() throws Exception { mapperFactory.mapType( Values.class, null ); fail( "Must fail" ); }
@Test( expected = IllegalArgumentException.class ) public void testUnsupportedType() throws Exception { mapperFactory.mapType( Integer.class, null ); ... |
Introspector { @NotNull public JavaType introspect( Type type ) { if( typeMap.containsKey( type.getTypeName() ) ) return typeMap.get( type.getTypeName() ); if( type instanceof Class<?> ) return forClass( (Class<?>)type ); if( type instanceof ParameterizedType ) return forParameterized( (ParameterizedType)type ); if( ty... | @Test public void testIntrospection() throws Exception { Introspector introspector = new Introspector(); JavaType type = introspector.introspect( Element.class ); int k = 0; } |
RealTypeMapper implements TypeMapper { @NotNull @Override public Value toAsn1( @NotNull ValueFactory factory, @NotNull Object value ) { if( isFloat() && isAssignableToFloat( value ) ) return factory.real( (Float)value ); if( isDouble() && isAssignableToDouble( value ) ) return factory.real( (Double)value ); if( isBigDe... | @Test( expected = IllegalArgumentException.class ) public void toAsn1Fails() throws Exception { TypeMapper mapper = new RealTypeMapper( double.class, REAL ); mapper.toAsn1( FACTORY, true ); fail( "Must fail" ); } |
RealTypeMapper implements TypeMapper { @NotNull @Override public Object toJava( @NotNull Value value ) { if( value.getKind() != Kind.REAL ) throw new IllegalArgumentException( "Unable to handle value of kind: " + value.getKind() ); RealValue rv = value.toRealValue(); if( isFloat() ) return rv.asFloat(); if( isDouble() ... | @Test( expected = IllegalArgumentException.class ) public void toJavaFails() throws Exception { TypeMapper mapper = new RealTypeMapper( double.class, REAL ); mapper.toJava( BooleanValue.TRUE ); fail( "Must fail" ); } |
StringTypeMapper implements TypeMapper { @NotNull @Override public Value toAsn1( @NotNull ValueFactory factory, @NotNull Object value ) { if( !javaType.isAssignableFrom( value.getClass() ) ) throw new IllegalArgumentException( "Unable to convert value: " + value ); return factory.cString( (String)value ); } StringTypeM... | @Test( expected = IllegalArgumentException.class ) public void toAsn1Fails() throws Exception { TypeMapper mapper = new StringTypeMapper( String.class, UTF8_STRING ); mapper.toAsn1( FACTORY, 1L ); fail( "Must fail" ); } |
StringTypeMapper implements TypeMapper { @NotNull @Override public Object toJava( @NotNull Value value ) { if( value.getKind() != Kind.C_STRING ) throw new IllegalArgumentException( "Unable to convert value of kind: " + value.getKind() ); return value.toStringValue().asString(); } StringTypeMapper( Class<?> javaType, N... | @Test( expected = IllegalArgumentException.class ) public void toJavaFails() throws Exception { TypeMapper mapper = new StringTypeMapper( String.class, UTF8_STRING ); mapper.toJava( BooleanValue.TRUE ); fail( "Must fail" ); } |
IntegerTypeMapper implements TypeMapper { @NotNull @Override public Value toAsn1( @NotNull ValueFactory factory, @NotNull Object value ) { if( isByte() && isAssignableToByte( value ) ) return factory.integer( (Byte)value ); if( isShort() && isAssignableToShort( value ) ) return factory.integer( (Short)value ); if( isIn... | @Test( expected = IllegalArgumentException.class ) public void toAsn1Fails() throws Exception { TypeMapper mapper = new IntegerTypeMapper( Long.class, INTEGER ); mapper.toAsn1( FACTORY, true ); fail( "Must fail" ); } |
IntegerTypeMapper implements TypeMapper { @NotNull @Override public Object toJava( @NotNull Value value ) { if( value.getKind() != Kind.INTEGER ) throw new IllegalArgumentException( "Unable to convert to integer value of kind: " + value.getKind() ); IntegerValue iv = value.toIntegerValue(); if( isByte() ) return (byte)... | @Test( expected = IllegalArgumentException.class ) public void toJavaFails() throws Exception { TypeMapper mapper = new IntegerTypeMapper( Long.class, INTEGER ); mapper.toJava( BooleanValue.TRUE ); fail( "Must fail" ); } |
ByteArrayTypeMapper implements TypeMapper { @NotNull @Override public Value toAsn1( @NotNull ValueFactory factory, @NotNull Object value ) { if( !byte[].class.isAssignableFrom( value.getClass() ) ) throw new IllegalArgumentException( "Unable to convert value: " + value ); byte[] array = (byte[])value; return factory.by... | @Test( expected = IllegalArgumentException.class ) public void toAsn1Fails() throws Exception { TypeMapper mapper = new ByteArrayTypeMapper( byte[].class, OCTET_STRING ); mapper.toAsn1( FACTORY, 1L ); fail( "Must fail" ); } |
BitStringBerDecoder implements BerDecoder { @Override public Value decode( @NotNull ReaderContext context ) throws IOException, Asn1Exception { assert context.getType().getFamily() == Family.BIT_STRING; assert !context.getTag().isConstructed(); if( context.getLength() == 0 ) return context.getValueFactory().emptyByteAr... | @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( Enc... |
ByteArrayTypeMapper implements TypeMapper { @NotNull @Override public Object toJava( @NotNull Value value ) { if( value.getKind() != Kind.BYTE_ARRAY ) throw new IllegalArgumentException( "Unable to handle value of kind: " + value.getKind() ); return value.toByteArrayValue().asByteArray(); } ByteArrayTypeMapper( Class<?... | @Test( expected = IllegalArgumentException.class ) public void toJavaFails() throws Exception { TypeMapper mapper = new ByteArrayTypeMapper( byte[].class, OCTET_STRING ); mapper.toJava( BooleanValue.TRUE ); fail( "Must fail" ); } |
DateTypeMapper implements TypeMapper { @NotNull @Override public Value toAsn1( @NotNull ValueFactory factory, @NotNull Object value ) { if( !javaType.isAssignableFrom( value.getClass() ) ) throw new IllegalArgumentException( "Unable to convert value: " + value ); if( isDate() ) return factory.timeValue( ( (Date)value )... | @Test( expected = IllegalArgumentException.class ) public void toAsn1Fails() throws Exception { TypeMapper mapper = new DateTypeMapper( Instant.class, G_TIME ); mapper.toAsn1( FACTORY, 1L ); fail( "Must fail" ); } |
DateTypeMapper implements TypeMapper { @NotNull @Override public Object toJava( @NotNull Value value ) { if( value.getKind() != Kind.TIME ) throw new IllegalArgumentException( "Unable to convert values of kind: " + value.getKind() ); Instant instant = value.toDateValue().asInstant(); if( isInstant() ) return instant; i... | @Test( expected = IllegalArgumentException.class ) public void toJavaFails() throws Exception { TypeMapper mapper = new DateTypeMapper( Instant.class, G_TIME ); mapper.toJava( BooleanValue.TRUE ); fail( "Must fail" ); } |
BooleanTypeMapper implements TypeMapper { @NotNull @Override public Value toAsn1( @NotNull ValueFactory factory, @NotNull Object value ) { if( !isBooleanClass( value ) ) throw new IllegalArgumentException( "Unable to convert value: " + value ); if( Boolean.TRUE.equals( value ) ) return BooleanValue.TRUE; if( Boolean.FA... | @Test public void toAsn1() throws Exception { BooleanTypeMapper mapper = new BooleanTypeMapper( boolean.class, BOOLEAN ); assertEquals( "Not equals", BooleanValue.TRUE, mapper.toAsn1( FACTORY, true ) ); assertEquals( "Not equals", BooleanValue.FALSE, mapper.toAsn1( FACTORY, false ) ); }
@Test( expected = IllegalArgumen... |
BooleanTypeMapper implements TypeMapper { @NotNull @Override public Object toJava( @NotNull Value value ) { if( value.getKind() != Kind.BOOLEAN ) throw new IllegalArgumentException( "Unable to handle value of kind: " + value.getKind() ); if( Objects.equals( value, BooleanValue.TRUE ) ) return Boolean.TRUE; if( Objects.... | @Test public void toJava() throws Exception { BooleanTypeMapper mapper = new BooleanTypeMapper( boolean.class, BOOLEAN ); assertEquals( "Not equals", Boolean.TRUE, mapper.toJava( BooleanValue.TRUE ) ); assertEquals( "Not equals", Boolean.FALSE, mapper.toJava( BooleanValue.FALSE ) ); }
@Test( expected = IllegalArgumentE... |
GeneralizedTimeBerEncoder implements BerEncoder { @Override public void encode( @NotNull WriterContext context ) throws IOException, Asn1Exception { assert context.getType().getFamily() == Family.GENERALIZED_TIME; assert context.getValue().getKind() == Kind.TIME; Instant instant = context.getValue().toDateValue().asIns... | @Test public void testWrite_Der() throws Exception { Scope scope = CoreModule.getInstance().createScope(); Type type = UniversalType.GENERALIZED_TIME.ref().resolve( scope ); Value value = new DateValueImpl( TimeUtils.parseGeneralizedTime( TIME_VALUE ) ); try( AbstractBerWriter writer = mock( AbstractBerWriter.class ) )... |
StringBerEncoder implements BerEncoder { @Override public void encode( @NotNull WriterContext context ) throws IOException, Asn1Exception { assert context.getType().getFamily() == Family.RESTRICTED_STRING; assert context.getValue().getKind() == Kind.C_STRING; Type type = context.getType(); while( !( type instanceof Str... | @Test public void testEncode_0() throws Exception { Scope scope = CoreModule.getInstance().createScope(); Type type = UniversalType.UTF8_STRING.ref().resolve( scope ); Value value = new StringValueImpl( "A" ); try( AbstractBerWriter writer = mock( AbstractBerWriter.class ) ) { new StringBerEncoder().encode( new WriterC... |
ObjectIDBerDecoder implements BerDecoder { @Override public Value decode( @NotNull ReaderContext context ) throws IOException, Asn1Exception { assert context.getType().getFamily() == Family.OID; assert context.getLength() > 0; List<Ref<Value>> list = new ArrayList<>(); int length = context.getLength(); while( length > ... | @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( Enc... |
SequenceOfBerEncoder implements BerEncoder { @Override public void encode( @NotNull WriterContext context ) throws IOException, Asn1Exception { assert context.getType().getFamily() == Family.SEQUENCE_OF; assert context.getValue().getKind() == Kind.COLLECTION || context.getValue().getKind() == Kind.NAMED_COLLECTION; if(... | @Test public void testWriteSequenceOf_Buffered() throws Exception { Scope scope = CoreModule.getInstance().createScope(); SequenceOfType type = new SequenceOfType(); type.setComponent( "a", UniversalType.INTEGER.ref() ); type.validate( scope ); ComponentType component = type.getComponentType(); Assert.assertNotNull( "N... |
BitStringBerEncoder implements BerEncoder { @Override public void encode( @NotNull WriterContext context ) throws IOException { assert context.getType().getFamily() == Family.BIT_STRING; assert context.getValue().getKind() == Kind.BYTE_ARRAY; ByteArrayValue arrayValue = context.getValue().toByteArrayValue(); boolean ha... | @Test public void testWrite_0101_Der() throws Exception { Scope scope = CoreModule.getInstance().createScope(); Type type = UniversalType.BIT_STRING.ref().resolve( scope ); Value value = CoreUtils.byteArrayFromBitString( VALUE_0101B ); try( AbstractBerWriter writer = mock( AbstractBerWriter.class ) ) { when( writer.get... |
BooleanBerDecoder implements BerDecoder { @Override public Value decode( @NotNull ReaderContext context ) throws IOException { assert context.getType().getFamily() == Family.BOOLEAN; assert context.getLength() == 1; byte content = context.read(); return content == BerUtils.BOOLEAN_FALSE ? BooleanValue.FALSE : BooleanVa... | @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( Enc... |
BooleanBerEncoder implements BerEncoder { @Override public void encode( @NotNull WriterContext context ) throws IOException { assert context.getType().getFamily() == Family.BOOLEAN; assert context.getValue().getKind() == Kind.BOOLEAN; context.writeHeader( TAG, 1 ); boolean value = context.getValue().toBooleanValue().as... | @Test public void testEncode_true() throws Exception { Scope scope = CoreModule.getInstance().createScope(); Type type = UniversalType.BOOLEAN.ref().resolve( scope ); Value value = BooleanValue.TRUE; try( AbstractBerWriter writer = mock( AbstractBerWriter.class ) ) { new BooleanBerEncoder().encode( new WriterContext( w... |
SetOfBerEncoder implements BerEncoder { @Override public void encode( @NotNull WriterContext context ) throws IOException, Asn1Exception { assert context.getType().getFamily() == Family.SET_OF; assert context.getValue().getKind() == Kind.COLLECTION || context.getValue().getKind() == Kind.NAMED_COLLECTION; if( !context.... | @Test public void testWriteSetOf_Buffered() throws Exception { Scope scope = CoreModule.getInstance().createScope(); SetOfType type = new SetOfType(); type.setComponent( "a", UniversalType.INTEGER.ref() ); type.validate( scope ); ComponentType component = type.getComponentType(); Assert.assertNotNull( "No component a",... |
OctetStringBerEncoder implements BerEncoder { @Override public void encode( @NotNull WriterContext context ) throws IOException { assert context.getType().getFamily() == Family.OCTET_STRING; assert context.getValue().getKind() == Kind.BYTE_ARRAY; byte[] bytes = context.getValue().toByteArrayValue().asByteArray(); int l... | @Test public void testEncode_Empty() throws Exception { Scope scope = CoreModule.getInstance().createScope(); Type type = UniversalType.OCTET_STRING.ref().resolve( scope ); Value value = CoreUtils.byteArrayFromHexString( "''H" ); try( AbstractBerWriter writer = mock( AbstractBerWriter.class ) ) { new OctetStringBerEnco... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.