method2testcases
stringlengths
118
3.08k
### Question: Safe58 { public static byte[] decode(String input) { return decode(input,false); } static String encode(byte[] input); static byte[] decode(String input); static byte[] decode(String input, boolean strict); }### Answer: @Test public void decode() { byte[] ok = Safe58.decode("Helloworld"); assertArrayEquals(ok,Safe58.decode("HellOwOr1d")); assertArrayEquals(ok,Safe58.decode("He1IOw0r1d")); assertArrayEquals(ok,Safe58.decode("He!|Ow0r|d")); }
### Question: KeyInfo { public AbstractKey unpackKey(byte[] data) throws EncryptionError { switch (algorythm) { case RSAPublic: return new PublicKey(data, this); case RSAPrivate: return new PrivateKey(data, this); case AES256: return new SymmetricKey(data, this); } throw new EncryptionError("can't unpack key: " + this); } KeyInfo(Algorythm algorythm, byte[] tag, int keyLength); KeyInfo(Algorythm algorythm, byte[] tag); KeyInfo(PRF PRF, int rounds, byte[] salt, byte[] tag); KeyInfo(byte[] packedInfo); byte[] getSalt(); boolean matchType(KeyInfo otherInfo); boolean matchType(AbstractKey otherKey); boolean matchTag(KeyInfo keyInfo); void setTag(byte[] tag); String getBase64Tag(); boolean isPassword(); byte[] getTag(); int getRounds(); Algorythm getAlgorythm(); PRF getPRF(); int getKeyLength(); byte[] pack(); SymmetricKey derivePassword(String password); AbstractKey unpackKey(byte[] data); @Override String toString(); }### Answer: @Test public void unpackKey() throws Exception { AbstractKey k1 = TestKeys.privateKey(3).getPublicKey(); AbstractKey kx = AbstractKey.fromBinder(k1.toBinder()); assertEquals(k1, kx); k1 = SymmetricKey.fromPassword("helluva", 4096); kx = AbstractKey.fromBinder(k1.toBinder()); assertEquals(k1, kx); k1 = TestKeys.privateKey(2); kx = AbstractKey.fromBinder(k1.toBinder()); assertEquals(k1, kx); }
### Question: Syntex1 extends Digest { @Override public int getLength() { return 36; } @Override int getLength(); }### Answer: @Test public void testBasics() throws Exception { Syntex1 s = new Syntex1(); s.update("Hello world"); byte[] d1 = s.digest(); assertEquals(36, s.getLength()); byte[] d2 = new Syntex1().digest("Fello world"); assertEquals(36, d2.length); byte[] d3 = new Syntex1().digest("Hello world"); assertArrayEquals(d1, d3); assertThat( d3, equalTo(d1)); assertThat( d2, not(equalTo(d1))); InputStream in = new ByteArrayInputStream("Hello world".getBytes()); assertThat(d1, equalTo( new Syntex1().digest(in))); }
### Question: PrivateKey extends AbstractKey { public byte[] pack() { @NonNull final Map<String, Object> params = privateKey.toHash(); return Boss.dumpToArray(new Object[]{ TYPE_PRIVATE, params.get("e"), params.get("p"), params.get("q") }); } PrivateKey(byte[] packedBinaryKey, KeyInfo info); PrivateKey(byte[] packedBinaryKey); PrivateKey(int bitStrength); PrivateKey(); @Override boolean canSign(); @Override boolean isPrivate(); @Override byte[] decrypt(final byte[] encrypted); PublicKey getPublicKey(); byte[] pack(); @Override byte[] sign(InputStream input, HashType hashType); @Override KeyInfo info(); @Override boolean equals(Object obj); @Override int hashCode(); @Override byte[] fingerprint(); static PrivateKey fromPath(Path path); @Override Digest updateDigestWithKeyComponents(Digest digest); byte[] packWithPassword(String password); byte[] packWithPassword(String password, int rounds); static PrivateKey unpackWithPassword(byte[] packedBinary, String password); }### Answer: @Test public void serializationTest() throws Exception { byte[] packedPublicKey = Do.decodeBase64(publicKey64); PublicKey publicKey = new PublicKey(packedPublicKey); byte[] packedPublicKey2 = publicKey.pack(); assertArrayEquals(packedPublicKey, packedPublicKey2); byte[] packedPrivateKey = Do.decodeBase64(TestKeys.binaryKeys[3]); PrivateKey privateKey = new PrivateKey(packedPrivateKey); byte[] packedPrivateKey2 = privateKey.pack(); assertArrayEquals(packedPrivateKey, packedPrivateKey2); }
### Question: SymmetricKey extends AbstractKey implements Serializable, Hashable { public byte[] etaEncrypt(byte[] data) throws EncryptionError { ByteArrayOutputStream bos = new ByteArrayOutputStream(); try { final EtaEncryptingStream s = etaEncryptStream(bos); s.write(data); s.end(); return bos.toByteArray(); } catch (IOException e) { throw new RuntimeException("unexpected IOError", e); } } SymmetricKey(); SymmetricKey(byte[] key); SymmetricKey(byte[] key, KeyInfo keyInfo); static SymmetricKey fromPassword(String password, int rounds); static SymmetricKey fromPassword(String password, int rounds, byte[] salt); void setKey(byte[] key); byte[] getKey(); int getBitStrength(); int getSize(); @Override Map<String, Object> toHash(); @Override void updateFromHash(Map<String, Object> hash); byte[] encrypt(byte[] plaintext); byte[] decrypt(byte[] ciphertext); OutputStream encryptStream(OutputStream outputStream); InputStream decryptStream(InputStream inputStream); EtaEncryptingStream etaEncryptStream(OutputStream out); EtaDecryptingStream etaDecryptStream(InputStream in); byte[] etaEncrypt(byte[] data); byte[] etaSign(byte[] data); byte[] etaDecrypt(byte[] data); static byte[] xor(byte[] src, int value); @Override byte[] pack(); @Override boolean equals(Object obj); @Override int hashCode(); }### Answer: @Test public void etaEncrypt() throws Exception { SymmetricKey k = new SymmetricKey(); byte[] plainText = "Hello, world!".getBytes(); byte[] cipherText = k.etaEncrypt(plainText); assertEquals(16 + 32 + plainText.length, cipherText.length); byte[] decryptedText = k.etaDecrypt(cipherText); assertArrayEquals(plainText, decryptedText); exception.expect(SymmetricKey.AuthenticationFailed.class); cipherText[19] += 1; k.etaDecrypt(cipherText); }
### Question: SymmetricKey extends AbstractKey implements Serializable, Hashable { public static byte[] xor(byte[] src, int value) { byte[] result = new byte[src.length]; for (int i = 0; i < src.length; i++) result[i] = (byte) ((src[i] ^ value) & 0xFF); return result; } SymmetricKey(); SymmetricKey(byte[] key); SymmetricKey(byte[] key, KeyInfo keyInfo); static SymmetricKey fromPassword(String password, int rounds); static SymmetricKey fromPassword(String password, int rounds, byte[] salt); void setKey(byte[] key); byte[] getKey(); int getBitStrength(); int getSize(); @Override Map<String, Object> toHash(); @Override void updateFromHash(Map<String, Object> hash); byte[] encrypt(byte[] plaintext); byte[] decrypt(byte[] ciphertext); OutputStream encryptStream(OutputStream outputStream); InputStream decryptStream(InputStream inputStream); EtaEncryptingStream etaEncryptStream(OutputStream out); EtaDecryptingStream etaDecryptStream(InputStream in); byte[] etaEncrypt(byte[] data); byte[] etaSign(byte[] data); byte[] etaDecrypt(byte[] data); static byte[] xor(byte[] src, int value); @Override byte[] pack(); @Override boolean equals(Object obj); @Override int hashCode(); }### Answer: @Test public void xor() throws Exception { byte[] test = new byte[]{0, 0x55, (byte) 0xFF}; byte[] src = new byte[]{0, 0x55, (byte) 0xFF}; test = SymmetricKey.xor(test, 0); assertArrayEquals(test, src); test = SymmetricKey.xor(test, 0xFF); assertArrayEquals(new byte[]{(byte) 0xFF, (byte) 0xAA, 0}, test); test = SymmetricKey.xor(src, 0x11); assertArrayEquals(new byte[]{0x11, (byte) 0x44, (byte) 0xEE}, test); }
### Question: Decimal extends Number implements Comparable<Number> { public Decimal[] divideAndRemainder(BigDecimal divisor) { BigDecimal[] result = value.divideAndRemainder(divisor); return new Decimal[]{new Decimal(result[0]), new Decimal(result[1])}; } Decimal(); Decimal(String stringValue); Decimal(long longValue); Decimal(BigDecimal bigDecimalValue); @Override int intValue(); @Override long longValue(); @Override float floatValue(); @Override double doubleValue(); Decimal divide(BigDecimal divisor); Decimal divide(Decimal divisor); Decimal getIntegral(); Decimal getFraction(); Decimal add(Decimal augend); Decimal subtract(Decimal subtrahend); Decimal multiply(Decimal muliplicand); Decimal remainder(Decimal divisor); Decimal add(BigDecimal augend); Decimal subtract(BigDecimal subtrahend); Decimal multiply(BigDecimal muliplicand); Decimal remainder(BigDecimal divisor); Decimal[] divideAndRemainder(BigDecimal divisor); Decimal[] divideAndRemainder(Decimal divisor); Decimal abs(); Decimal negate(); int signum(); int compareTo(Number val); @Override boolean equals(Object x); @Override int hashCode(); @Override String toString(); String toEngineeringString(); String toPlainString(); BigInteger toBigInteger(); Decimal ulp(); static final int SCALE; static final Decimal ZERO; static final Decimal ONE; static final Decimal TWO; }### Answer: @Test public void divideAndRemainder() throws Exception { Decimal x = new Decimal("1000000000000"); Decimal[] dr = x.divideAndRemainder(new Decimal(3)); assertEquals("333333333333", dr[0].toString()); assertEquals(1, dr[1].intValue()); }
### Question: Decimal extends Number implements Comparable<Number> { public Decimal ulp() { return new Decimal(value.ulp()); } Decimal(); Decimal(String stringValue); Decimal(long longValue); Decimal(BigDecimal bigDecimalValue); @Override int intValue(); @Override long longValue(); @Override float floatValue(); @Override double doubleValue(); Decimal divide(BigDecimal divisor); Decimal divide(Decimal divisor); Decimal getIntegral(); Decimal getFraction(); Decimal add(Decimal augend); Decimal subtract(Decimal subtrahend); Decimal multiply(Decimal muliplicand); Decimal remainder(Decimal divisor); Decimal add(BigDecimal augend); Decimal subtract(BigDecimal subtrahend); Decimal multiply(BigDecimal muliplicand); Decimal remainder(BigDecimal divisor); Decimal[] divideAndRemainder(BigDecimal divisor); Decimal[] divideAndRemainder(Decimal divisor); Decimal abs(); Decimal negate(); int signum(); int compareTo(Number val); @Override boolean equals(Object x); @Override int hashCode(); @Override String toString(); String toEngineeringString(); String toPlainString(); BigInteger toBigInteger(); Decimal ulp(); static final int SCALE; static final Decimal ZERO; static final Decimal ONE; static final Decimal TWO; }### Answer: @Test public void ulp() throws Exception { Decimal x = new Decimal("1000000000000.0000000000000000001"); assertEquals( 1e-19,x.ulp().doubleValue(), 0); }
### Question: RSAOAEPPrivateKey extends AbstractPrivateKey { @Override public AbstractPublicKey getPublicKey() throws IllegalStateException { if (state == null) { throw new IllegalStateException(); } else { return state.publicKey; } } RSAOAEPPrivateKey(); RSAOAEPPrivateKey(byte[] e, byte[] p, byte[] q, HashType oaepHashType, HashType mgf1HashType, SecureRandom rng); @Override String toString(); @Override void generate(int bitStrength, HashType mgf1HashType); void generate(int bitStrength, byte[] e, int certainty, HashType oaepHashType, HashType mgf1HashType); @Override boolean isInitialized(); @Override int getBitStrength(); @Override AbstractPublicKey getPublicKey(); @Override boolean canDecrypt(); @Override byte[] decrypt(byte[] ciphertext); @Override byte[] sign(InputStream input, HashType hashType, @Nullable byte[] salt); @NonNull @Override Map<String, Object> toHash(); @Override void updateFromHash(Map<String, Object> hash); @Override byte[] pack(); static final HashType DEFAULT_OAEP_HASH; static final HashType DEFAULT_MGF1_HASH; }### Answer: @Test public void getPublicKey() throws Exception { AbstractPublicKey randomPublicKey4096 = randomPrivateKey4096.getPublicKey(); assertTrue(randomPublicKey4096 instanceof RSAOAEPPublicKey); AbstractPrivateKey rsaPrivateKey = oaepSpec.getPrivateKey(); AbstractPublicKey rsaPublicKey = rsaPrivateKey.getPublicKey(); ((RSAOAEPPublicKey) rsaPublicKey).resetEncryptor(); assertArrayEquals(rsaPublicKey.encrypt(oaepSpec.M), oaepSpec.C); }
### Question: RoleLink extends Role { @Override public <T extends Role> T resolve() { return resolve(true); } private RoleLink(); RoleLink(String name,Contract contract); @Deprecated RoleLink(String name); RoleLink(String name, Contract contract, String roleName); @Deprecated RoleLink(String name, String roleName); @Nullable Role getRole(); @Override T resolve(); T resolve(boolean ignoreRefs); @Override @Deprecated Set<KeyRecord> getKeyRecords(); @Override @Deprecated Set<AnonymousId> getAnonymousIds(); @Override @Deprecated Set<KeyAddress> getKeyAddresses(); @Override @Deprecated Set<PublicKey> getKeys(); @Override boolean isAllowedForKeysQuantized(Set<? extends AbstractKey> keys); @Override boolean isValid(); @Override @Deprecated boolean equalKeys(Role otherRole); @Override void initWithDsl(Binder serializedRole); @Override String toString(); @Override Binder serialize(BiSerializer s); @Override void deserialize(Binder data, BiDeserializer deserializer); @Override void anonymize(); }### Answer: @Test public void resolve() throws Exception { Contract c = new Contract(); SimpleRole s1 = new SimpleRole("owner",c); c.addRole(s1); RoleLink r1 = new RoleLink("lover",c, "owner"); c.addRole(r1); RoleLink r2 = r1.linkAs("mucker"); assertSame(s1, s1.resolve()); assertSame(s1, r1.resolve()); assertSame(s1, r2.resolve()); } @Test public void detectsCirculars() throws Exception { Contract c = new Contract(); RoleLink r1 = new RoleLink("bar", "foo"); RoleLink r2 = new RoleLink("foo", "bar"); c.registerRole(r1); c.registerRole(r2); assertNull(r2.resolve()); }
### Question: RoleLink extends Role { @Override public Binder serialize(BiSerializer s) { return super.serialize(s).putAll( "name", getName(), "target_name", roleName ); } private RoleLink(); RoleLink(String name,Contract contract); @Deprecated RoleLink(String name); RoleLink(String name, Contract contract, String roleName); @Deprecated RoleLink(String name, String roleName); @Nullable Role getRole(); @Override T resolve(); T resolve(boolean ignoreRefs); @Override @Deprecated Set<KeyRecord> getKeyRecords(); @Override @Deprecated Set<AnonymousId> getAnonymousIds(); @Override @Deprecated Set<KeyAddress> getKeyAddresses(); @Override @Deprecated Set<PublicKey> getKeys(); @Override boolean isAllowedForKeysQuantized(Set<? extends AbstractKey> keys); @Override boolean isValid(); @Override @Deprecated boolean equalKeys(Role otherRole); @Override void initWithDsl(Binder serializedRole); @Override String toString(); @Override Binder serialize(BiSerializer s); @Override void deserialize(Binder data, BiDeserializer deserializer); @Override void anonymize(); }### Answer: @Test public void serialize() throws Exception { RoleLink r1 = new RoleLink("name", "target"); r1.addRequiredReference("ref", Role.RequiredMode.ALL_OF); Binder s = DefaultBiMapper.serialize(r1); RoleLink r2 = DefaultBiMapper.deserialize(s); assertEquals(r1, r2); assertEquals(r1.getName(), r2.getName()); }
### Question: RoleLink extends Role { @Override @Nullable KeyAddress getSimpleAddress(boolean ignoreRefs) { Role r = resolve(ignoreRefs); if (r != null && r != this) return r.getSimpleAddress(ignoreRefs); return null; } private RoleLink(); RoleLink(String name,Contract contract); @Deprecated RoleLink(String name); RoleLink(String name, Contract contract, String roleName); @Deprecated RoleLink(String name, String roleName); @Nullable Role getRole(); @Override T resolve(); T resolve(boolean ignoreRefs); @Override @Deprecated Set<KeyRecord> getKeyRecords(); @Override @Deprecated Set<AnonymousId> getAnonymousIds(); @Override @Deprecated Set<KeyAddress> getKeyAddresses(); @Override @Deprecated Set<PublicKey> getKeys(); @Override boolean isAllowedForKeysQuantized(Set<? extends AbstractKey> keys); @Override boolean isValid(); @Override @Deprecated boolean equalKeys(Role otherRole); @Override void initWithDsl(Binder serializedRole); @Override String toString(); @Override Binder serialize(BiSerializer s); @Override void deserialize(Binder data, BiDeserializer deserializer); @Override void anonymize(); }### Answer: @Test public void testGetSimpleAddress() throws Exception { Set<Object> keyAddresses = new HashSet<>(); keyAddresses.add(TestKeys.publicKey(0).getLongAddress()); Contract c = new Contract(); SimpleRole sr = new SimpleRole("sr",c, keyAddresses); c.addRole(sr); RoleLink rl = new RoleLink("rl",c,sr.getName()); c.addRole(rl); assertEquals(rl.getSimpleAddress(),TestKeys.publicKey(0).getLongAddress()); rl.addRequiredReference("dummy", Role.RequiredMode.ALL_OF); assertNull(rl.getSimpleAddress()); assertEquals(RoleExtractor.extractSimpleAddress(rl),TestKeys.publicKey(0).getLongAddress()); }
### Question: ListRole extends Role { public void setMode(Mode newMode) { if (newMode != Mode.QUORUM) this.mode = newMode; else throw new IllegalArgumentException("Only ANY or ALL of the modes should be set."); } ListRole(); ListRole(String name,Contract contract); @Deprecated ListRole(String name); ListRole(String name, Contract contract, Mode mode, @NonNull Collection<Role> roles); @Deprecated ListRole(String name, Mode mode, @NonNull Collection<Role> roles); ListRole(String name, Contract contract, int quorumSize, @NonNull Collection<Role> roles); @Deprecated ListRole(String name, int quorumSize, @NonNull Collection<Role> roles); void addAll(Collection<Role> roles); Set<Role> getRoles(); ListRole addRole(Role role); void setQuorum(int n); int getQuorum(); void setMode(Mode newMode); Mode getMode(); @Override boolean isAllowedForKeysQuantized(Set<? extends AbstractKey> keys); @Override boolean isValid(); @Override void initWithDsl(Binder serializedRole); @Override void setContract(Contract contract); @Override @Deprecated Set<KeyRecord> getKeyRecords(); @Override @Deprecated Set<PublicKey> getKeys(); @Override @Deprecated Set<AnonymousId> getAnonymousIds(); @Override @Deprecated Set<KeyAddress> getKeyAddresses(); @Override String toString(); @Override void deserialize(Binder data, BiDeserializer deserializer); @Override Binder serialize(BiSerializer s); @Override void anonymize(); }### Answer: @Test public void shouldNotAllowToSetQuorum() { ListRole listRole = new ListRole("roles"); try { listRole.setMode(ListRole.Mode.QUORUM); fail("Expected exception to be thrown."); } catch (IllegalArgumentException e) { assertTrue(e.getMessage().equalsIgnoreCase("Only ANY or ALL of the modes should be set.")); } }
### Question: TransactionPack implements BiSerializable { public static TransactionPack unpack(byte[] packOrContractBytes, boolean allowNonTransactions) throws IOException { Object x = Boss.load(packOrContractBytes); if (x instanceof TransactionPack) { return (TransactionPack) x; } if (!allowNonTransactions) throw new IOException("expected transaction pack"); TransactionPack tp = new TransactionPack(); tp.reconstructed = true; tp.packedBinary = packOrContractBytes; tp.contract = Contract.fromSealedBinary(packOrContractBytes, tp); return tp; } TransactionPack(Contract contract); TransactionPack(); Contract getContract(); Contract getSubItem(HashId id); Contract getSubItem(HashIdentifiable hid); Set<PublicKey> getKeysForPack(); void setContract(Contract c); void addSubItem(Contract subItem); void addReferencedItem(Contract referencedItem); void addTag(String tag, HashId itemId); void addKeys(PublicKey... keys); @Override void deserialize(Binder data, BiDeserializer deserializer); @Override Binder serialize(BiSerializer serializer); final boolean isReconstructed(); static TransactionPack unpack(byte[] packOrContractBytes, boolean allowNonTransactions); static TransactionPack unpack(byte[] packOrContractBytes); synchronized byte[] pack(); Map<HashId, Contract> getSubItems(); Map<HashId, Contract> getReferencedItems(); Map<String, Contract> getTags(); void trace(); void setReferenceContextKeys(Set<PublicKey> referenceEffectiveKeys); Contract findContract(Predicate<Contract> function); static final String TAG_PREFIX_RESERVED; }### Answer: @Test public void deserializeOldContract() throws Exception { TransactionPack tp = TransactionPack.unpack(c.sealAsV2()); checkSimplePack(tp); }
### Question: TransactionPack implements BiSerializable { public void setContract(Contract c) { if (contract != null) throw new IllegalArgumentException("the contract is already added"); contract = c; packedBinary = null; extractAllSubItemsAndReferenced(c); c.setTransactionPack(this); for (PrivateKey key : c.getKeysToSignWith()) addKeys(key.getPublicKey()); } TransactionPack(Contract contract); TransactionPack(); Contract getContract(); Contract getSubItem(HashId id); Contract getSubItem(HashIdentifiable hid); Set<PublicKey> getKeysForPack(); void setContract(Contract c); void addSubItem(Contract subItem); void addReferencedItem(Contract referencedItem); void addTag(String tag, HashId itemId); void addKeys(PublicKey... keys); @Override void deserialize(Binder data, BiDeserializer deserializer); @Override Binder serialize(BiSerializer serializer); final boolean isReconstructed(); static TransactionPack unpack(byte[] packOrContractBytes, boolean allowNonTransactions); static TransactionPack unpack(byte[] packOrContractBytes); synchronized byte[] pack(); Map<HashId, Contract> getSubItems(); Map<HashId, Contract> getReferencedItems(); Map<String, Contract> getTags(); void trace(); void setReferenceContextKeys(Set<PublicKey> referenceEffectiveKeys); Contract findContract(Predicate<Contract> function); static final String TAG_PREFIX_RESERVED; }### Answer: @Test public void serializeNew() throws Exception { TransactionPack tp = new TransactionPack(); tp.setContract(c); checkSimplePack(tp); }
### Question: UnikeyFactory { @Nullable static RSAOAEPPrivateKey rsaOaepPKFromUnikey(@NonNull byte[] bytes) { assert bytes != null; try { final ArrayList unpackedFromBoss = Boss.load(bytes); assert ((Integer) unpackedFromBoss.get(0)) == 0; final byte[] e = ((Bytes) unpackedFromBoss.get(1)).toArray(), p = ((Bytes) unpackedFromBoss.get(2)).toArray(), q = ((Bytes) unpackedFromBoss.get(3)).toArray(); return new RSAOAEPPrivateKey( e, p, q, RSAOAEPPrivateKey.DEFAULT_OAEP_HASH, RSAOAEPPrivateKey.DEFAULT_MGF1_HASH, new SecureRandom()); } catch (Throwable e) { return null; } } @Nullable static PrivateKey fromUnikey(@NonNull byte[] bytes); @NonNull static byte[] toUnikey(@NonNull PrivateKey privateKey); }### Answer: @Test public void testFromUnikeyRSAOAEP() throws Exception { final RSAOAEPPrivateKey pk1 = UnikeyFactory.rsaOaepPKFromUnikey(pk1Bytes); assertNotNull(pk1); assertArrayEquals( pk1E, BigIntegers.asUnsignedByteArray(pk1.state.keyParameters.getPublicExponent())); assertArrayEquals( pk1P, BigIntegers.asUnsignedByteArray(pk1.state.keyParameters.getP())); assertArrayEquals( pk1Q, BigIntegers.asUnsignedByteArray(pk1.state.keyParameters.getQ())); }
### Question: ExtendedSignature { public static PublicKey extractPublicKey(byte[] signature) { Binder src = Boss.unpack(signature); PublicKey publicKey = null; byte[] exts = src.getBinaryOrThrow("exts"); Binder b = Boss.unpack(exts); try { byte[] publicKeyBytes = b.getBinaryOrThrow("pub_key"); publicKey = new PublicKey(publicKeyBytes); } catch (EncryptionError e) { publicKey = null; } catch (IllegalArgumentException e) { publicKey = null; } return publicKey; } Bytes getKeyId(); ZonedDateTime getCreatedAt(); PublicKey getPublicKey(); static byte[] sign(PrivateKey key, byte[] data); static byte[] sign(PrivateKey key, byte[] data, boolean savePublicKey); static byte[] createTargetSignature(PublicKey publicKey, byte[] data, boolean savePublicKey); @Deprecated static byte[] of(byte[] targetSignature, byte[] sign, byte[] sign2); static byte[] ofSha512AndSha3_384(byte[] targetSignature, byte[] sign512, byte[] sign3_384); static Bytes keyId(AbstractKey key); static Bytes extractKeyId(byte[] signature); static PublicKey extractPublicKey(byte[] signature); byte[] getSignature(); static ExtendedSignature verify(PublicKey key, byte[] signature, byte[] data); }### Answer: @Test public void extractPublicKey() throws Exception { byte[] data = "Hello world".getBytes(); PrivateKey k = TestKeys.privateKey(3); byte [] signature = ExtendedSignature.sign(k, data); PublicKey pubKey = k.getPublicKey(); ExtendedSignature es = ExtendedSignature.verify(pubKey, signature, data); assertNotNull(es); assertAlmostSame(es.getCreatedAt(), ZonedDateTime.now()); assertEquals(ExtendedSignature.keyId(k), ExtendedSignature.keyId(pubKey)); assertEquals(ExtendedSignature.keyId(k), ExtendedSignature.extractKeyId(signature)); assertNotNull(es.getPublicKey()); assertEquals(pubKey, es.getPublicKey()); }
### Question: UnikeyFactory { @NonNull static byte[] toUnikey(@NonNull RSAOAEPPrivateKey privateKey) { assert privateKey != null; return privateKey.pack(); } @Nullable static PrivateKey fromUnikey(@NonNull byte[] bytes); @NonNull static byte[] toUnikey(@NonNull PrivateKey privateKey); }### Answer: @Test public void testToUnikeyRSAOAEP() throws Exception { final RSAOAEPPrivateKey pk1 = new RSAOAEPPrivateKey( pk1E, pk1P, pk1Q, HashType.SHA1, HashType.SHA1, new SecureRandom()); assertArrayEquals( pk1Bytes, UnikeyFactory.toUnikey(pk1)); }
### Question: RSAOAEPDigestFactory { public static Digest cloneDigest(Digest digest) { try { return digest.getClass().newInstance(); } catch (InstantiationException | IllegalAccessException exc) { exc.printStackTrace(); return digest; } } @Nullable static Digest getDigestByName(String digestName); static Digest cloneDigest(Digest digest); }### Answer: @Test public void cloneDigest() throws Exception { Digest d1Orig = new SHA512Digest(); Digest d1Clone = RSAOAEPDigestFactory.cloneDigest(d1Orig); assertTrue(d1Clone instanceof SHA512Digest); assertNotEquals(d1Orig, d1Clone); }
### Question: RSAOAEPPublicKey extends AbstractPublicKey { @NonNull @Override public byte[] encrypt(byte[] plaintext) throws EncryptionError, IllegalStateException { if (state == null) { throw new IllegalStateException(); } else { try { return state.encryptor.processBlock(plaintext, 0, plaintext.length); } catch (InvalidCipherTextException e) { throw new EncryptionError(String.format("Cannot encode: %s", e.toString())); } } } RSAOAEPPublicKey(); RSAOAEPPublicKey(byte[] n, byte[] e, HashType oaepHashType, HashType mgf1HashType, SecureRandom rng); @Override String toString(); @Override boolean canEncrypt(); @Override int getBitStrength(); @Override boolean isInitialized(); @NonNull @Override byte[] encrypt(byte[] plaintext); @NonNull @Override boolean checkSignature(InputStream input, byte[] signature, HashType hashType, int saltLength); @NonNull @Override String algorithmTag(); @NonNull @Override Map<String, Object> toHash(); @Override void updateFromHash(Map<String, Object> hash); static final HashType DEFAULT_OAEP_HASH; static final HashType DEFAULT_MGF1_HASH; }### Answer: @Test public void encrypt() throws Exception { AbstractPublicKey rsaPublicKey = oaepSpec.getPublicKey(); ((RSAOAEPPublicKey) rsaPublicKey).resetEncryptor(); assertArrayEquals(rsaPublicKey.encrypt(oaepSpec.M), oaepSpec.C); }
### Question: StandaloneBean { public String returnMessage() { return message; } String returnMessage(); }### Answer: @Test public void testReturnMessage() throws Exception { logger.info("Testing standalone.ejb.StandaloneBean.returnMessage()"); StandaloneBean instance = (StandaloneBean) ctx.lookup("java:global/classes/StandaloneBean"); String expResult = "Greetings!"; String result = instance.returnMessage(); assertEquals(expResult, result); }
### Question: ProductTypeRefinerDocProc extends DocumentProcessor { @Override public Progress process(Processing processing) { for (DocumentOperation op : processing.getDocumentOperations()) { if (op instanceof DocumentPut) { DocumentPut put = (DocumentPut) op; Document document = put.getDocument(); if (document.getDataType().isA(MUSIC_DOCUMENT_TYPE)) { logger.info("Before processing: " + document.toJson()); processPut(document); logger.info("After processing: " + document.toJson()); return Progress.DONE; } } } return Progress.DONE; } @Override Progress process(Processing processing); @Override void deconstruct(); }### Answer: @Test public void testRefinement() { Document doc = new Document(createMusicType(), "id:mynamespace:music::1"); doc.setFieldValue(PRODUCT_TYPE_FIELD_NAME, new StringFieldValue("Media > Music & Sound Recordings > Music Cassette Tapes")); Processing p = getProcessing(new DocumentPut(doc)); DocprocService service = setupDocprocService(new ProductTypeRefinerDocProc()); service.getExecutor().process(p); assertEquals("Media | Music & Sound Recordings | Music Cassette Tapes", doc.getFieldValue(PRODUCT_TYPE_FIELD_NAME).toString()); }
### Question: SubqueriesSearcher extends Searcher { public Result search(Query query, Execution execution) { Result result = execution.search(query); execution.fill(result); for (Hit hit : result.hits().asList()) { if (hit.isMeta()) continue; simplifySubqueriesFor("target", hit); hit.removeField("summaryfeatures"); } return result; } SubqueriesSearcher(); Result search(Query query, Execution execution); }### Answer: @Test public void hit_is_added() throws Exception { try (Application app = Application.fromApplicationPackage( Paths.get("src/test/application"), Networking.disable)) { Search search = app.getJDisc("jdisc").search(); Result result = search.process(ComponentSpecification.fromString("default"), new Query("?query=ignored")); assertEquals(3, result.hits().size()); Hit hit = result.hits().get(0); assertEquals(null, hit.getField("summaryfeatures")); assertEquals(0x100000003L, hit.getField("subqueries(target)")); } }
### Question: ProductTypeTokenizerDocProc extends DocumentProcessor { @Override public Progress process(Processing processing) { for (DocumentOperation op : processing.getDocumentOperations()) { if (op instanceof DocumentPut) { DocumentPut put = (DocumentPut) op; Document document = put.getDocument(); if (document.getDataType().isA(MUSIC_DOCUMENT_TYPE)) { logger.info("Before processing: " + document.toJson()); processPut(document); logger.info("After processing: " + document.toJson()); return Progress.DONE; } } } return Progress.DONE; } @Override Progress process(Processing processing); @Override void deconstruct(); }### Answer: @Test public void testTokenizer() { Document doc = new Document(createMusicType(), "id:mynamespace:music::1"); doc.setFieldValue(PRODUCT_TYPE_FIELD_NAME, new StringFieldValue("Media > Music & Sound Recordings > Music Cassette Tapes")); Processing p = getProcessing(new DocumentPut(doc)); DocprocService service = setupDocprocService(new ProductTypeTokenizerDocProc()); service.getExecutor().process(p); Array<?> tokens = (Array<?>)doc.getFieldValue(PRODUCT_TYPE_TOKENS_FIELD_NAME); assertEquals(55, tokens.size()); assertEquals("M", tokens.get(0).toString()); assertEquals("Media > Music & Sound Recordings > Music Cassette Tapes", tokens.get(54).toString()); }
### Question: EquivSearcher extends Searcher { @Override public Result search(Query query, Execution execution) { query.trace("Before equivize:" + query.toDetailString(), false, 6); QueryTree tree = query.getModel().getQueryTree(); Item rootItem = tree.getRoot(); rootItem = equivize(rootItem); tree.setRoot(rootItem); query.trace("After equivize:" + query.toDetailString(), false, 6); return execution.search(query); } @Override Result search(Query query, Execution execution); }### Answer: @Test void testMetallica() { Chain<Searcher> myChain = new Chain<>(new MinimalQueryInserter(), new EquivSearcher()); Execution.Context context = Execution.Context.createContextStub(); Execution execution = new Execution(myChain, context); for (String yql: queries) { Query query = new Query("/search/?yql=" + encode(yql, StandardCharsets.UTF_8)); query.setTraceLevel(6); Result result = execution.search(query); System.out.println(result.getContext(false).getTrace()); } }
### Question: ExampleProcessor extends Processor { @SuppressWarnings("unchecked") @Override public Response process(Request request, Execution execution) { request.properties().set("foo", "bar"); Response response = execution.process(request); response.data().add(new StringData(request, message)); return response; } @Inject ExampleProcessor(ExampleProcessorConfig config); @SuppressWarnings("unchecked") @Override Response process(Request request, Execution execution); }### Answer: @Test public void requireThatResultContainsHelloWorld() { ExampleProcessorConfig.Builder config = new ExampleProcessorConfig.Builder().message("Hello, processor!"); Processor processor = new ExampleProcessor(new ExampleProcessorConfig(config)); Response response = newExecution(processor).process(new Request()); assertEquals("Hello, processor!", response.data().get(0).toString()); }
### Question: Out implements SubTraversal<Element, Vertex> { @SuppressWarnings("PMD.ShortMethodName") public static Out of(org.apache.tinkerpop.gremlin.object.structure.Element element) { return of(org.apache.tinkerpop.gremlin.object.reflect.Label.of(element)); } @SuppressWarnings("PMD.ShortMethodName") static Out of(org.apache.tinkerpop.gremlin.object.structure.Element element); @SuppressWarnings("PMD.ShortMethodName") static Out of( Class<? extends org.apache.tinkerpop.gremlin.object.structure.Element> elementType); @Override GraphTraversal<Element, Vertex> apply(GraphTraversal<Element, Element> traversal); }### Answer: @Test public void testOutTraversal() { Out out = Out.of(sanFrancisco); traverse(out); verify(traversal, times(1)).out("City"); assertEquals(sanFrancisco.label(), out.label()); }
### Question: Classes { public static boolean isSet(Object object) { return object != null && isSet(object.getClass()); } private Classes(); static boolean isElement(Class<?> type); static boolean isVertex(Object object); static boolean isVertex(Class<?> type); static boolean isEdge(Object object); static boolean isEdge(Class<?> type); static boolean isList(Object object); static boolean isList(Class<?> type); static boolean isSet(Object object); static boolean isSet(Class<?> type); static boolean isCollection(Object object); static boolean isCollection(Class<?> type); static boolean isFunctional(Class<?> type); @SuppressWarnings({"PMD.ShortMethodName"}) static boolean is(Class<?> type, Object that); @SuppressWarnings({"PMD.ShortMethodName"}) static boolean is(Object object, Class<?> that); @SuppressWarnings({"PMD.ShortMethodName"}) static boolean is(Class<?> type, Class<?> that); @SuppressWarnings("unchecked") static void sortCollection(Class<?> clazz, Collection<?> collection); @SneakyThrows @SuppressWarnings("rawtypes") static Collection newCollection(Class<?> clazz); static String name(Class<?> type); }### Answer: @Test public void testIsSet() { assertTrue(isSet(new HashSet<>())); assertFalse(isSet(Person.class)); }
### Question: Classes { public static boolean isCollection(Object object) { return object != null && isCollection(object.getClass()); } private Classes(); static boolean isElement(Class<?> type); static boolean isVertex(Object object); static boolean isVertex(Class<?> type); static boolean isEdge(Object object); static boolean isEdge(Class<?> type); static boolean isList(Object object); static boolean isList(Class<?> type); static boolean isSet(Object object); static boolean isSet(Class<?> type); static boolean isCollection(Object object); static boolean isCollection(Class<?> type); static boolean isFunctional(Class<?> type); @SuppressWarnings({"PMD.ShortMethodName"}) static boolean is(Class<?> type, Object that); @SuppressWarnings({"PMD.ShortMethodName"}) static boolean is(Object object, Class<?> that); @SuppressWarnings({"PMD.ShortMethodName"}) static boolean is(Class<?> type, Class<?> that); @SuppressWarnings("unchecked") static void sortCollection(Class<?> clazz, Collection<?> collection); @SneakyThrows @SuppressWarnings("rawtypes") static Collection newCollection(Class<?> clazz); static String name(Class<?> type); }### Answer: @Test public void testIsCollection() { assertTrue(isCollection(new ArrayList<>())); assertFalse(isCollection(new PriorityQueue<>())); assertFalse(isCollection(Person.class)); }
### Question: Classes { public static boolean isFunctional(Class<?> type) { return is(type, Function.class); } private Classes(); static boolean isElement(Class<?> type); static boolean isVertex(Object object); static boolean isVertex(Class<?> type); static boolean isEdge(Object object); static boolean isEdge(Class<?> type); static boolean isList(Object object); static boolean isList(Class<?> type); static boolean isSet(Object object); static boolean isSet(Class<?> type); static boolean isCollection(Object object); static boolean isCollection(Class<?> type); static boolean isFunctional(Class<?> type); @SuppressWarnings({"PMD.ShortMethodName"}) static boolean is(Class<?> type, Object that); @SuppressWarnings({"PMD.ShortMethodName"}) static boolean is(Object object, Class<?> that); @SuppressWarnings({"PMD.ShortMethodName"}) static boolean is(Class<?> type, Class<?> that); @SuppressWarnings("unchecked") static void sortCollection(Class<?> clazz, Collection<?> collection); @SneakyThrows @SuppressWarnings("rawtypes") static Collection newCollection(Class<?> clazz); static String name(Class<?> type); }### Answer: @Test public void testIsFunctional() { assertTrue(isFunctional(HasKeys.class)); assertFalse(isFunctional(Person.class)); }
### Question: Classes { @SuppressWarnings({"PMD.ShortMethodName"}) public static boolean is(Class<?> type, Object that) { return that != null && is(type, that.getClass()); } private Classes(); static boolean isElement(Class<?> type); static boolean isVertex(Object object); static boolean isVertex(Class<?> type); static boolean isEdge(Object object); static boolean isEdge(Class<?> type); static boolean isList(Object object); static boolean isList(Class<?> type); static boolean isSet(Object object); static boolean isSet(Class<?> type); static boolean isCollection(Object object); static boolean isCollection(Class<?> type); static boolean isFunctional(Class<?> type); @SuppressWarnings({"PMD.ShortMethodName"}) static boolean is(Class<?> type, Object that); @SuppressWarnings({"PMD.ShortMethodName"}) static boolean is(Object object, Class<?> that); @SuppressWarnings({"PMD.ShortMethodName"}) static boolean is(Class<?> type, Class<?> that); @SuppressWarnings("unchecked") static void sortCollection(Class<?> clazz, Collection<?> collection); @SneakyThrows @SuppressWarnings("rawtypes") static Collection newCollection(Class<?> clazz); static String name(Class<?> type); }### Answer: @Test public void testIsSomething() { assertTrue(is(Develops.class, Edge.class)); assertTrue(is(develops, Edge.class)); assertTrue(is(Develops.class, develops)); assertFalse(is(Develops.class, Vertex.class)); assertFalse(is(develops, Vertex.class)); assertFalse(is(Develops.class, marko)); }
### Question: Label { @SuppressWarnings("PMD.ShortMethodName") public static String of(Element element) { return of(element.getClass()); } private Label(); @SuppressWarnings("PMD.ShortMethodName") static String of(Element element); @SuppressWarnings("PMD.ShortMethodName") static String of(Class<? extends Element> elementType); }### Answer: @Test public void testVertexLabelWithAlias() { assertEquals("person", of(Person.class)); assertEquals("person", of(marko)); } @Test public void testEdgeLabelWithoutAlias() { assertEquals("develops", of(Develops.class)); assertEquals("develops", of(develops)); } @Test public void testVertexLabelWithoutAlias() { assertEquals("City", of(City.class)); }
### Question: Primitives { public static boolean isPrimitive(Field field) { return isPrimitive(field.getType()); } private Primitives(); static void registerPrimitiveClass(Class primitiveClass); @SneakyThrows static void registerPrimitiveClass(Class primitiveClass, Object primitiveDefault); @SuppressWarnings("unchecked") static void registerStringConverters(Class<P> primitiveClass, Function<String, P> stringConverter); @SuppressWarnings("unchecked") static void registerTimeConverters(Class sourceTimeClass, Class targetTimeClass, Function<Object, Object> timeConverter); static boolean isPrimitive(Field field); static boolean isPrimitive(Class clazz); static boolean isPrimitiveDefault(Field field, Object value); static Object asPrimitiveType(Field field, String defaultValue); static boolean isMissing(Object object); static boolean isTimeType(Class clazz); static Date toDate(long epoch); static Date toDate(long epoch, TimeUnit timeUnit); static long toEpoch(Date date); static Instant toInstant(long epoch); static long toEpoch(Instant instant); static Instant toInstant(Date date); static Date toDate(Instant instant); @SuppressWarnings("unchecked") static T toTimeType(Object timeValue, Class<T> targetTimeType); static boolean allowDefaultKeys; }### Answer: @Test public void testIsPrimitiveType() { assertTrue(isPrimitive(String.class)); assertTrue(isPrimitive(Graph.Should.class)); assertFalse(isPrimitive(Set.class)); }
### Question: Primitives { public static boolean isTimeType(Class clazz) { return clazz.equals(Date.class) || clazz.equals(Instant.class) || clazz.equals(Long.class); } private Primitives(); static void registerPrimitiveClass(Class primitiveClass); @SneakyThrows static void registerPrimitiveClass(Class primitiveClass, Object primitiveDefault); @SuppressWarnings("unchecked") static void registerStringConverters(Class<P> primitiveClass, Function<String, P> stringConverter); @SuppressWarnings("unchecked") static void registerTimeConverters(Class sourceTimeClass, Class targetTimeClass, Function<Object, Object> timeConverter); static boolean isPrimitive(Field field); static boolean isPrimitive(Class clazz); static boolean isPrimitiveDefault(Field field, Object value); static Object asPrimitiveType(Field field, String defaultValue); static boolean isMissing(Object object); static boolean isTimeType(Class clazz); static Date toDate(long epoch); static Date toDate(long epoch, TimeUnit timeUnit); static long toEpoch(Date date); static Instant toInstant(long epoch); static long toEpoch(Instant instant); static Instant toInstant(Date date); static Date toDate(Instant instant); @SuppressWarnings("unchecked") static T toTimeType(Object timeValue, Class<T> targetTimeType); static boolean allowDefaultKeys; }### Answer: @Test public void testIsTimeType() { assertTrue(isTimeType(Instant.class)); assertFalse(isTimeType(Integer.class)); }
### Question: HasKeys implements ElementTo.Element { @SuppressWarnings("PMD.ShortMethodName") public static HasKeys of(org.apache.tinkerpop.gremlin.object.structure.Element element, Class<? extends Annotation> keyType) { return HasKeys.builder() .element(element) .keyType(keyType) .build(); } @SuppressWarnings("PMD.ShortMethodName") static HasKeys of(org.apache.tinkerpop.gremlin.object.structure.Element element, Class<? extends Annotation> keyType); @Override @SneakyThrows GraphTraversal<Element, Element> apply(GraphTraversal<Element, Element> traversal); }### Answer: @Test public void testHasPrimaryKeyTraversal() { HasKeys hasKeys = HasKeys.of(sanFrancisco); traverse(hasKeys); verify(traversal, times(1)).hasLabel("City"); verify(traversal, times(1)).has("name", "San Francisco"); assertEquals(sanFrancisco, hasKeys.element()); } @Test(expected = IllegalArgumentException.class) public void testNullPrimaryKeyTraversal() { sanFrancisco.setName(null); HasKeys hasKeys = HasKeys.of(sanFrancisco); traverse(hasKeys); }
### Question: Parser { public static boolean isPropertyValue(Field field) { return has(field, PropertyValue.class); } private Parser(); static void registerElementParser(ElementParser<?> elementParser); static boolean isPropertyValue(Field field); @SneakyThrows @SuppressWarnings({"PMD.ShortMethodName", "rawtypes"}) static T as(Object element, Class<T> objectClass); }### Answer: @Test public void testIsPropertyValue() { assertTrue(isPropertyValue(field(location, "name"))); assertFalse(isPropertyValue(field(marko, "age"))); }
### Question: Parser { @SneakyThrows @SuppressWarnings({"PMD.ShortMethodName", "rawtypes"}) public static <T> T as(Object element, Class<T> objectClass) { Class<?> elementType = element.getClass(); if (is(elementType, objectClass)) { return (T) element; } for (ElementParser elementParser : ELEMENT_PARSERS) { if (is(elementType, elementParser.elementType())) { return (T) elementParser.as(element, objectClass); } } if (objectClass.isEnum()) { return (T) Enum.valueOf((Class<Enum>) objectClass, (String) element); } throw Query.Exceptions.invalidObjectType(element, objectClass); } private Parser(); static void registerElementParser(ElementParser<?> elementParser); static boolean isPropertyValue(Field field); @SneakyThrows @SuppressWarnings({"PMD.ShortMethodName", "rawtypes"}) static T as(Object element, Class<T> objectClass); }### Answer: @Test public void testAsEnum() { assertEquals(MERGE, as("MERGE", Should.class)); } @Test public void testAsItself() { assertEquals(MERGE, as(MERGE, Should.class)); } @Test(expected = ClassCastException.class) public void testAsUnhandled() { assertEquals(Collections.emptyList(), as(new ArrayList<>(), Person.class)); } @Test public void testAsVertex() { assertEquals(marko, as(new DetachedVertex( 1, "person", new HashMap<String, Object>() { { put("name", Arrays.asList(new HashMap<String, Object>() { { put("value", "marko"); } })); put("age", Arrays.asList(new HashMap<String, Object>() { { put("value", 29); } })); } }), Person.class)); } @Test public void testAsEdge() { assertEquals(develops, as(new DetachedEdge( null, Label.of(Develops.class), new HashMap<String, Object>() { { put("since", develops.since()); } }, null, null, null, null), Develops.class)); }
### Question: Fields { public static boolean has(Field field, Class<? extends Annotation> annotationType) { return field.getAnnotation(annotationType) != null; } private Fields(); static boolean has(Field field, Class<? extends Annotation> annotationType); static String alias(AnnotatedElement element, Function<Alias, String> property); static String propertyKey(Field field); @SneakyThrows static Object propertyValue(Field field, Object instance); static Field field(E element, String fieldName); static Field field(Class<E> elementType, String fieldName); static List<Field> fields(E element); static List<Field> fields(E element, Predicate<Field> predicate); static List<Field> fields(Class<E> elementType); static List<Field> fields(Class<E> elementType, Predicate<Field> predicate); static Class<?> listType(Field field); static boolean isSimple(Field field); static long elementCacheSize; static final Comparator<Field> BY_NAME; static final Comparator<Field> BY_KEYS; }### Answer: @Test public void testHasAnnotation() { assertTrue(has(name, PrimaryKey.class)); assertFalse(has(name, OrderingKey.class)); }
### Question: Fields { public static String alias(AnnotatedElement element, Function<Alias, String> property) { Alias alias = element.getAnnotation(Alias.class); if (alias == null) { return null; } String value = property.apply(alias); return isNotEmpty(value) ? value : null; } private Fields(); static boolean has(Field field, Class<? extends Annotation> annotationType); static String alias(AnnotatedElement element, Function<Alias, String> property); static String propertyKey(Field field); @SneakyThrows static Object propertyValue(Field field, Object instance); static Field field(E element, String fieldName); static Field field(Class<E> elementType, String fieldName); static List<Field> fields(E element); static List<Field> fields(E element, Predicate<Field> predicate); static List<Field> fields(Class<E> elementType); static List<Field> fields(Class<E> elementType, Predicate<Field> predicate); static Class<?> listType(Field field); static boolean isSimple(Field field); static long elementCacheSize; static final Comparator<Field> BY_NAME; static final Comparator<Field> BY_KEYS; }### Answer: @Test public void testAliasProperty() { assertEquals("person", alias(Person.class, Alias::label)); assertNull(alias(locations, Alias::key)); }
### Question: Fields { public static String propertyKey(Field field) { String key = alias(field, Alias::key); return key != null ? key : field.getName(); } private Fields(); static boolean has(Field field, Class<? extends Annotation> annotationType); static String alias(AnnotatedElement element, Function<Alias, String> property); static String propertyKey(Field field); @SneakyThrows static Object propertyValue(Field field, Object instance); static Field field(E element, String fieldName); static Field field(Class<E> elementType, String fieldName); static List<Field> fields(E element); static List<Field> fields(E element, Predicate<Field> predicate); static List<Field> fields(Class<E> elementType); static List<Field> fields(Class<E> elementType, Predicate<Field> predicate); static Class<?> listType(Field field); static boolean isSimple(Field field); static long elementCacheSize; static final Comparator<Field> BY_NAME; static final Comparator<Field> BY_KEYS; }### Answer: @Test public void testPropertyKey() { assertEquals("name", propertyKey(name)); }
### Question: Fields { @SneakyThrows public static Object propertyValue(Field field, Object instance) { Object value = field.get(instance); if (isPrimitiveDefault(field, value)) { DefaultValue defaultValue = field.getAnnotation(DefaultValue.class); if (defaultValue != null) { return asPrimitiveType(field, defaultValue.value()); } } return value; } private Fields(); static boolean has(Field field, Class<? extends Annotation> annotationType); static String alias(AnnotatedElement element, Function<Alias, String> property); static String propertyKey(Field field); @SneakyThrows static Object propertyValue(Field field, Object instance); static Field field(E element, String fieldName); static Field field(Class<E> elementType, String fieldName); static List<Field> fields(E element); static List<Field> fields(E element, Predicate<Field> predicate); static List<Field> fields(Class<E> elementType); static List<Field> fields(Class<E> elementType, Predicate<Field> predicate); static Class<?> listType(Field field); static boolean isSimple(Field field); static long elementCacheSize; static final Comparator<Field> BY_NAME; static final Comparator<Field> BY_KEYS; }### Answer: @Test public void testPropertyValue() { assertEquals("marko", propertyValue(name, marko)); }
### Question: Fields { public static <E extends Element> Field field(E element, String fieldName) { return field(element.getClass(), fieldName); } private Fields(); static boolean has(Field field, Class<? extends Annotation> annotationType); static String alias(AnnotatedElement element, Function<Alias, String> property); static String propertyKey(Field field); @SneakyThrows static Object propertyValue(Field field, Object instance); static Field field(E element, String fieldName); static Field field(Class<E> elementType, String fieldName); static List<Field> fields(E element); static List<Field> fields(E element, Predicate<Field> predicate); static List<Field> fields(Class<E> elementType); static List<Field> fields(Class<E> elementType, Predicate<Field> predicate); static Class<?> listType(Field field); static boolean isSimple(Field field); static long elementCacheSize; static final Comparator<Field> BY_NAME; static final Comparator<Field> BY_KEYS; }### Answer: @Test public void testGetField() { assertEquals("age", field(marko, "age").getName()); }
### Question: Properties { @SuppressWarnings({"PMD.ShortMethodName"}) public static <E extends Element> Object[] id(E element) { return of(element, Keys::isKey); } private Properties(); @SuppressWarnings({"PMD.ShortMethodName"}) static Object[] id(E element); @SuppressWarnings({"PMD.ShortMethodName"}) static Object[] all(E element); @SuppressWarnings({"PMD.ShortMethodName"}) static Object[] all(E element, Predicate<Field> predicate, T... ts); @SuppressWarnings({"PMD.ShortMethodName"}) static Object[] of(V vertex); @SuppressWarnings({"PMD.ShortMethodName"}) static Object[] of(E edge); @SuppressWarnings({"PMD.ShortMethodName"}) static Object[] of(E element, Predicate<Field> predicate); static Object[] simple(E element, T... ts); static Object[] complex(E element); @SneakyThrows static List<Object> some(E element, Predicate<Field> predicate); static List<String> names(E element); static List<String> names(E element, Predicate<Field> predicate); @SneakyThrows @SuppressWarnings("unchecked") static List<Object> values(Object object); static List<Property> list(Object... objects); @SneakyThrows static List<String> nullKeys(E element); @SneakyThrows static List<String> listKeys(E element); }### Answer: @Test public void testPropertyId() { assertArrayEquals(new Object[] {"name", "marko", "age", 29}, id(marko)); assertArrayEquals(new Object[] {}, id(develops)); }
### Question: Properties { @SuppressWarnings({"PMD.ShortMethodName"}) public static <E extends Element> Object[] all(E element) { return of(element, field -> true); } private Properties(); @SuppressWarnings({"PMD.ShortMethodName"}) static Object[] id(E element); @SuppressWarnings({"PMD.ShortMethodName"}) static Object[] all(E element); @SuppressWarnings({"PMD.ShortMethodName"}) static Object[] all(E element, Predicate<Field> predicate, T... ts); @SuppressWarnings({"PMD.ShortMethodName"}) static Object[] of(V vertex); @SuppressWarnings({"PMD.ShortMethodName"}) static Object[] of(E edge); @SuppressWarnings({"PMD.ShortMethodName"}) static Object[] of(E element, Predicate<Field> predicate); static Object[] simple(E element, T... ts); static Object[] complex(E element); @SneakyThrows static List<Object> some(E element, Predicate<Field> predicate); static List<String> names(E element); static List<String> names(E element, Predicate<Field> predicate); @SneakyThrows @SuppressWarnings("unchecked") static List<Object> values(Object object); static List<Property> list(Object... objects); @SneakyThrows static List<String> nullKeys(E element); @SneakyThrows static List<String> listKeys(E element); }### Answer: @Test public void testPropertyAll() { assertArrayEquals(new Object[] {"name", "marko", "age", 29}, all(marko)); assertArrayEquals(new Object[] {"since", year(2000)}, all(develops)); }
### Question: HasLabel implements ElementTo.Element { @SuppressWarnings("PMD.ShortMethodName") public static HasLabel of(org.apache.tinkerpop.gremlin.object.structure.Element element) { return of(element.getClass()); } @SuppressWarnings("PMD.ShortMethodName") static HasLabel of(org.apache.tinkerpop.gremlin.object.structure.Element element); @SuppressWarnings("PMD.ShortMethodName") static HasLabel of( Class<? extends org.apache.tinkerpop.gremlin.object.structure.Element> elementType); @Override GraphTraversal<Element, Element> apply(GraphTraversal<Element, Element> traversal); }### Answer: @Test public void testHasLabelTraversal() { HasLabel hasLabel = HasLabel.of(sanFrancisco); traverse(hasLabel); verify(traversal, times(1)).hasLabel("City"); assertEquals(Label.of(sanFrancisco), hasLabel.label()); }
### Question: Properties { @SuppressWarnings({"PMD.ShortMethodName"}) public static <V extends Vertex> Object[] of(V vertex) { return of(vertex, field -> !isKey(field)); } private Properties(); @SuppressWarnings({"PMD.ShortMethodName"}) static Object[] id(E element); @SuppressWarnings({"PMD.ShortMethodName"}) static Object[] all(E element); @SuppressWarnings({"PMD.ShortMethodName"}) static Object[] all(E element, Predicate<Field> predicate, T... ts); @SuppressWarnings({"PMD.ShortMethodName"}) static Object[] of(V vertex); @SuppressWarnings({"PMD.ShortMethodName"}) static Object[] of(E edge); @SuppressWarnings({"PMD.ShortMethodName"}) static Object[] of(E element, Predicate<Field> predicate); static Object[] simple(E element, T... ts); static Object[] complex(E element); @SneakyThrows static List<Object> some(E element, Predicate<Field> predicate); static List<String> names(E element); static List<String> names(E element, Predicate<Field> predicate); @SneakyThrows @SuppressWarnings("unchecked") static List<Object> values(Object object); static List<Property> list(Object... objects); @SneakyThrows static List<String> nullKeys(E element); @SneakyThrows static List<String> listKeys(E element); }### Answer: @Test public void testPropertyOf() { assertArrayEquals(new Object[] {}, of(marko)); assertArrayEquals(new Object[] {"since", year(2000)}, of(develops)); }
### Question: Properties { public static <E extends Element> List<String> names(E element) { return names(element, field -> true); } private Properties(); @SuppressWarnings({"PMD.ShortMethodName"}) static Object[] id(E element); @SuppressWarnings({"PMD.ShortMethodName"}) static Object[] all(E element); @SuppressWarnings({"PMD.ShortMethodName"}) static Object[] all(E element, Predicate<Field> predicate, T... ts); @SuppressWarnings({"PMD.ShortMethodName"}) static Object[] of(V vertex); @SuppressWarnings({"PMD.ShortMethodName"}) static Object[] of(E edge); @SuppressWarnings({"PMD.ShortMethodName"}) static Object[] of(E element, Predicate<Field> predicate); static Object[] simple(E element, T... ts); static Object[] complex(E element); @SneakyThrows static List<Object> some(E element, Predicate<Field> predicate); static List<String> names(E element); static List<String> names(E element, Predicate<Field> predicate); @SneakyThrows @SuppressWarnings("unchecked") static List<Object> values(Object object); static List<Property> list(Object... objects); @SneakyThrows static List<String> nullKeys(E element); @SneakyThrows static List<String> listKeys(E element); }### Answer: @Test public void testPropertyNames() { assertEquals(Arrays.asList("name", "age", "locations", "titles"), names(marko)); assertEquals(Arrays.asList("since"), names(develops)); }
### Question: Keys { public static boolean isPrimaryKey(Field field) { return has(field, PrimaryKey.class); } private Keys(); static boolean isKey(Field field); static boolean isPrimaryKey(Field field); static boolean isOrderingKey(Field field); static List<Field> keyFields(Element element); static List<Field> keyFields(Class<? extends Element> elementType); static List<Field> primaryKeyFields(Element element); static List<Field> primaryKeyFields(Class<? extends Element> elementType); static boolean hasPrimaryKeys(Element element); static boolean hasPrimaryKeys(Class<? extends Element> elementType); static List<Field> orderingKeyFields(Element element); static List<Field> orderingKeyFields(Class<? extends Element> elementType); static List<String> primaryKeyNames(Element element); static List<String> primaryKeyNames(Class<? extends Element> elementType); @SneakyThrows @SuppressWarnings("PMD.ShortMethodName") static Object id(E element); }### Answer: @Test public void testIsPrimaryKey() { assertTrue(isPrimaryKey(personName)); assertFalse(isPrimaryKey(personAge)); assertFalse(isPrimaryKey(personTitles)); }
### Question: Keys { public static boolean isOrderingKey(Field field) { return has(field, OrderingKey.class); } private Keys(); static boolean isKey(Field field); static boolean isPrimaryKey(Field field); static boolean isOrderingKey(Field field); static List<Field> keyFields(Element element); static List<Field> keyFields(Class<? extends Element> elementType); static List<Field> primaryKeyFields(Element element); static List<Field> primaryKeyFields(Class<? extends Element> elementType); static boolean hasPrimaryKeys(Element element); static boolean hasPrimaryKeys(Class<? extends Element> elementType); static List<Field> orderingKeyFields(Element element); static List<Field> orderingKeyFields(Class<? extends Element> elementType); static List<String> primaryKeyNames(Element element); static List<String> primaryKeyNames(Class<? extends Element> elementType); @SneakyThrows @SuppressWarnings("PMD.ShortMethodName") static Object id(E element); }### Answer: @Test public void testIsOrderingKey() { assertFalse(isOrderingKey(personName)); assertTrue(isOrderingKey(personAge)); assertFalse(isOrderingKey(personTitles)); }
### Question: Keys { public static List<Field> primaryKeyFields(Element element) { return primaryKeyFields(element.getClass()); } private Keys(); static boolean isKey(Field field); static boolean isPrimaryKey(Field field); static boolean isOrderingKey(Field field); static List<Field> keyFields(Element element); static List<Field> keyFields(Class<? extends Element> elementType); static List<Field> primaryKeyFields(Element element); static List<Field> primaryKeyFields(Class<? extends Element> elementType); static boolean hasPrimaryKeys(Element element); static boolean hasPrimaryKeys(Class<? extends Element> elementType); static List<Field> orderingKeyFields(Element element); static List<Field> orderingKeyFields(Class<? extends Element> elementType); static List<String> primaryKeyNames(Element element); static List<String> primaryKeyNames(Class<? extends Element> elementType); @SneakyThrows @SuppressWarnings("PMD.ShortMethodName") static Object id(E element); }### Answer: @Test public void testPrimaryKeyFields() { assertEquals(Arrays.asList(personName), primaryKeyFields(Person.class)); assertTrue(primaryKeyFields(Develops.class).isEmpty()); }
### Question: Keys { public static boolean hasPrimaryKeys(Element element) { return hasPrimaryKeys(element.getClass()); } private Keys(); static boolean isKey(Field field); static boolean isPrimaryKey(Field field); static boolean isOrderingKey(Field field); static List<Field> keyFields(Element element); static List<Field> keyFields(Class<? extends Element> elementType); static List<Field> primaryKeyFields(Element element); static List<Field> primaryKeyFields(Class<? extends Element> elementType); static boolean hasPrimaryKeys(Element element); static boolean hasPrimaryKeys(Class<? extends Element> elementType); static List<Field> orderingKeyFields(Element element); static List<Field> orderingKeyFields(Class<? extends Element> elementType); static List<String> primaryKeyNames(Element element); static List<String> primaryKeyNames(Class<? extends Element> elementType); @SneakyThrows @SuppressWarnings("PMD.ShortMethodName") static Object id(E element); }### Answer: @Test public void testHasPrimaryKey() { assertTrue(hasPrimaryKeys(Person.class)); assertFalse(hasPrimaryKeys(Develops.class)); }
### Question: Keys { public static List<Field> orderingKeyFields(Element element) { return orderingKeyFields(element.getClass()); } private Keys(); static boolean isKey(Field field); static boolean isPrimaryKey(Field field); static boolean isOrderingKey(Field field); static List<Field> keyFields(Element element); static List<Field> keyFields(Class<? extends Element> elementType); static List<Field> primaryKeyFields(Element element); static List<Field> primaryKeyFields(Class<? extends Element> elementType); static boolean hasPrimaryKeys(Element element); static boolean hasPrimaryKeys(Class<? extends Element> elementType); static List<Field> orderingKeyFields(Element element); static List<Field> orderingKeyFields(Class<? extends Element> elementType); static List<String> primaryKeyNames(Element element); static List<String> primaryKeyNames(Class<? extends Element> elementType); @SneakyThrows @SuppressWarnings("PMD.ShortMethodName") static Object id(E element); }### Answer: @Test public void testOrderingKeyFields() { assertEquals(Arrays.asList(personAge), orderingKeyFields(Person.class)); assertTrue(orderingKeyFields(Develops.class).isEmpty()); }
### Question: Keys { public static List<String> primaryKeyNames(Element element) { return primaryKeyNames(element); } private Keys(); static boolean isKey(Field field); static boolean isPrimaryKey(Field field); static boolean isOrderingKey(Field field); static List<Field> keyFields(Element element); static List<Field> keyFields(Class<? extends Element> elementType); static List<Field> primaryKeyFields(Element element); static List<Field> primaryKeyFields(Class<? extends Element> elementType); static boolean hasPrimaryKeys(Element element); static boolean hasPrimaryKeys(Class<? extends Element> elementType); static List<Field> orderingKeyFields(Element element); static List<Field> orderingKeyFields(Class<? extends Element> elementType); static List<String> primaryKeyNames(Element element); static List<String> primaryKeyNames(Class<? extends Element> elementType); @SneakyThrows @SuppressWarnings("PMD.ShortMethodName") static Object id(E element); }### Answer: @Test public void testPrimaryKeyNames() { assertEquals(Arrays.asList("name"), primaryKeyNames(Person.class)); assertTrue(primaryKeyNames(Develops.class).isEmpty()); }
### Question: Values implements ElementTo.Any { @SuppressWarnings("PMD.ShortMethodName") public static Values of(org.apache.tinkerpop.gremlin.object.structure.Element element) { return of(Properties.names(element)); } @SuppressWarnings("PMD.ShortMethodName") static Values of(org.apache.tinkerpop.gremlin.object.structure.Element element); @SuppressWarnings("PMD.ShortMethodName") static Values of(List<String> propertyKeys); @SuppressWarnings("PMD.ShortMethodName") static Values of(String... propertyKeys); @Override GraphTraversal<Element, Object> apply(GraphTraversal<Element, Element> traversal); }### Answer: @Test public void testValuesTraversal() { City sanFrancisco = City.of("San Francisco"); Values values = Values.of(sanFrancisco); when(traversal.values(anyVararg())).thenReturn(traversal); traverse(values); verify(traversal, times(1)).values("name", "population"); verify(traversal, times(1)).dedup(); assertArrayEquals(new String[] {"name", "population"}, values.propertyKeys()); }
### Question: Vertex extends Element { public void remove() { org.apache.tinkerpop.gremlin.structure.Vertex delegate = delegate(); if (delegate == null) { throw Element.Exceptions.removingDetachedElement(this); } delegate.remove(); } Vertex(Element element); org.apache.tinkerpop.gremlin.structure.Vertex delegate(); void remove(); }### Answer: @Test(expected = IllegalStateException.class) public void testCannotDeleteDetachedVertex() { Person person = createElement(); person.remove(); }
### Question: VertexGraph extends ElementGraph { protected <V extends Vertex> GraphTraversal update(V vertex) { GraphTraversal traversal = find(vertex); return update(traversal, vertex, Properties::of); } VertexGraph(Graph graph, GraphTraversalSource g); org.apache.tinkerpop.gremlin.structure.Vertex delegate(V vertex); Vertex addVertex(V vertex); Vertex removeVertex(V vertex); void reset(); }### Answer: @Test public void testUpdateElement() { Person marko = createElement(); vertexGraph.update(traversal, marko, Properties::of); InOrder inOrder = inOrder(traversal); inOrder.verify(traversal, times(1)) .property(should.equals(REPLACE) ? single : list, "locations", "san diego", new Object[] { "startTime", year(1997), "endTime", year(2001)}); inOrder.verify(traversal, times(1)) .property(list, "locations", "santa cruz", new Object[] { "startTime", year(2001), "endTime", year(2004) } ); }
### Question: VertexGraph extends ElementGraph { public <V extends Vertex> Vertex removeVertex(V vertex) { GraphTraversal traversal = find(vertex); log.info("Executing 'remove vertex' traversal {} ", traversal); traversal.drop().toList(); if (vertex.id() != null) { delegates.remove(vertex); } observers.notifyAll(observer -> observer.vertexRemoved(vertex)); return vertex; } VertexGraph(Graph graph, GraphTraversalSource g); org.apache.tinkerpop.gremlin.structure.Vertex delegate(V vertex); Vertex addVertex(V vertex); Vertex removeVertex(V vertex); void reset(); }### Answer: @Test public void testRemoveVertex() { Person marko = createElement(); vertexGraph.removeVertex(marko); InOrder inOrder = inOrder(g, traversal); inOrder.verify(g, times(1)).V(); inOrder.verify(traversal, times(1)).hasLabel(marko.label()); inOrder.verify(traversal, times(1)).has("name", marko.name()); inOrder.verify(traversal, times(1)).drop(); inOrder.verify(traversal, times(1)).toList(); }
### Question: EdgeGraph extends ElementGraph { <E extends Edge> GraphTraversal find(E edge, Object fromId, Object toId) { return g.V() .hasId(fromId).as("from") .outE(edge.label()).as("edge") .inV().hasId(toId).as("to") .select("edge"); } EdgeGraph(Graph graph, Query query, GraphTraversalSource g); org.apache.tinkerpop.gremlin.structure.Edge delegate(Edge edge); Edge addEdge(E edge, org.apache.tinkerpop.gremlin.structure.Vertex from, AnyTraversal anyTraversal); Edge addEdge(E edge, org.apache.tinkerpop.gremlin.structure.Vertex from, SubTraversal... subTraversals); Edge removeEdge(E edge); void reset(); }### Answer: @Test public void testFindElement() { Develops develops = createElement(); edgeGraph.find(develops); InOrder inOrder = inOrder(traversal); inOrder.verify(traversal, times(1)).hasLabel(develops.label()); inOrder.verify(traversal, times(1)).has("since", develops.since()); }
### Question: Keys implements ElementTo.Any { @SuppressWarnings("PMD.ShortMethodName") public static Keys of(org.apache.tinkerpop.gremlin.object.structure.Element element) { return of(element.getClass()); } @SuppressWarnings("PMD.ShortMethodName") static Keys of(org.apache.tinkerpop.gremlin.object.structure.Element element); @Override GraphTraversal<Element, Object> apply(GraphTraversal<Element, Element> traversal); }### Answer: @Test public void testKeysTraversal() { Keys keys = Keys.of(sanFrancisco); when(traversal.values(anyVararg())).thenReturn(traversal); traverse(keys); verify(traversal, times(1)).values("name"); verify(traversal, times(1)).dedup(); assertEquals(City.class, keys.elementType()); }
### Question: EdgeGraph extends ElementGraph { <E extends Edge> GraphTraversal update(E edge, Object fromId, Object toId) { GraphTraversal traversal = find(edge, fromId, toId); return update(traversal, edge, Properties::of); } EdgeGraph(Graph graph, Query query, GraphTraversalSource g); org.apache.tinkerpop.gremlin.structure.Edge delegate(Edge edge); Edge addEdge(E edge, org.apache.tinkerpop.gremlin.structure.Vertex from, AnyTraversal anyTraversal); Edge addEdge(E edge, org.apache.tinkerpop.gremlin.structure.Vertex from, SubTraversal... subTraversals); Edge removeEdge(E edge); void reset(); }### Answer: @Test public void testUpdateElement() { Develops develops = createElement(); edgeGraph.update(traversal, develops, Properties::all); verify(traversal, times(1)).property("since", develops.since()); }
### Question: EdgeGraph extends ElementGraph { public <E extends Edge> Edge removeEdge(E edge) { if (edge.fromId() == null || edge.toId() == null) { throw Element.Exceptions.removingDetachedElement(edge); } GraphTraversal traversal = find(edge, edge.fromId(), edge.toId()); log.info("Executing 'remove edge' traversal {}", traversal); traversal.select("edge").drop().toList(); if (edge.id() != null) { delegates.remove(edge); } observers.notifyAll(observer -> observer.edgeRemoved(edge)); return edge; } EdgeGraph(Graph graph, Query query, GraphTraversalSource g); org.apache.tinkerpop.gremlin.structure.Edge delegate(Edge edge); Edge addEdge(E edge, org.apache.tinkerpop.gremlin.structure.Vertex from, AnyTraversal anyTraversal); Edge addEdge(E edge, org.apache.tinkerpop.gremlin.structure.Vertex from, SubTraversal... subTraversals); Edge removeEdge(E edge); void reset(); }### Answer: @Test public void testRemoveEdge() { Develops develops = createElement(); develops.fromId(marko.id()); develops.toId(vadas.id()); edgeGraph.removeEdge(develops); InOrder inOrder = inOrder(g, traversal); inOrder.verify(g, times(1)).V(); inOrder.verify(traversal, times(1)).hasId(marko.id()); inOrder.verify(traversal, times(1)).as("from"); inOrder.verify(traversal, times(1)).outE(develops.label()); inOrder.verify(traversal, times(1)).as("edge"); inOrder.verify(traversal, times(1)).inV(); inOrder.verify(traversal, times(1)).hasId(vadas.id()); inOrder.verify(traversal, times(1)).as("to"); inOrder.verify(traversal, times(2)).select("edge"); inOrder.verify(traversal, times(1)).toList(); }
### Question: ElementGraph { protected <E extends Element> GraphTraversal find(E element) { GraphTraversal traversal = g.V(); if (element.id() != null) { traversal = traversal.hasId(element.id()); } else { traversal = traversal.hasLabel(element.label()); Object[] properties = Properties.id(element); if (properties == null || properties.length == 0) { properties = Properties.all(element); } for (Property property : list(properties)) { traversal = traversal.has(property.key(), property.value()); } } return traversal; } }### Answer: @Test public void testFindElement() { Location location = (Location) createElement(); elementGraph.find(location); InOrder inOrder = inOrder(traversal); inOrder.verify(traversal, times(1)).hasLabel(location.label()); inOrder.verify(traversal, times(1)).has("name", location.name()); inOrder.verify(traversal, times(1)).has("startTime", location.startTime()); }
### Question: ElementGraph { protected <E extends Element> GraphTraversal update( GraphTraversal traversal, E element, Function<E, Object[]> lister) { return update(traversal, UpdateBy.TRAVERSAL, element, lister); } }### Answer: @Test public void testUpdateElement() { Location location = (Location) createElement(); elementGraph.update(traversal, location, Properties::all); InOrder inOrder = inOrder(traversal); inOrder.verify(traversal, times(1)).property("name", "San Francisco"); inOrder.verify(traversal, times(1)).property("startTime", location.startTime()); }
### Question: Element implements Comparable<Element> { @SuppressWarnings({"PMD.ShortMethodName"}) public final Object id() { if (userSuppliedId != null) { return userSuppliedId; } if (delegate != null) { return delegate.id(); } return null; } Element(Element other); final String label(); @SuppressWarnings({"PMD.ShortMethodName"}) final Object id(); @SneakyThrows @SuppressWarnings({"PMD.ShortMethodName"}) ElementTo.Element s(String key); void validate(); static void cache(long numberOfElements); @Override boolean equals(Object other); @Override @SneakyThrows int hashCode(); @Override int compareTo(Element that); boolean existsIn(Collection<? extends Element> elements); @SuppressWarnings("unchecked") static final Comparator<Element> valuesOf(List<Field> fields); static final long serialVersionUID; final ElementTo.Element withLabel; final ElementTo.Element withId; }### Answer: @Test public void testWithIdTraversal() { Element element = createElement(); traverse(element.withId); verify(traversal, times(1)).hasId(element.id()); }
### Question: Element implements Comparable<Element> { public final String label() { return Label.of(getClass()); } Element(Element other); final String label(); @SuppressWarnings({"PMD.ShortMethodName"}) final Object id(); @SneakyThrows @SuppressWarnings({"PMD.ShortMethodName"}) ElementTo.Element s(String key); void validate(); static void cache(long numberOfElements); @Override boolean equals(Object other); @Override @SneakyThrows int hashCode(); @Override int compareTo(Element that); boolean existsIn(Collection<? extends Element> elements); @SuppressWarnings("unchecked") static final Comparator<Element> valuesOf(List<Field> fields); static final long serialVersionUID; final ElementTo.Element withLabel; final ElementTo.Element withId; }### Answer: @Test public void testWithLabelTraversal() { Element element = createElement(); traverse(element.withLabel); verify(traversal, times(1)).hasLabel(element.label()); } @Test public void testLabelExists() { Element element = createElement(); assertEquals(Label.of(element), element.label()); }
### Question: Element implements Comparable<Element> { public boolean existsIn(Collection<? extends Element> elements) { final List<Field> fields = keyFields(getClass()); if (fields.isEmpty()) { fields.addAll(fields(getClass())); } return elements.stream() .anyMatch(element -> valuesOf(fields).compare(element, this) == 0); } Element(Element other); final String label(); @SuppressWarnings({"PMD.ShortMethodName"}) final Object id(); @SneakyThrows @SuppressWarnings({"PMD.ShortMethodName"}) ElementTo.Element s(String key); void validate(); static void cache(long numberOfElements); @Override boolean equals(Object other); @Override @SneakyThrows int hashCode(); @Override int compareTo(Element that); boolean existsIn(Collection<? extends Element> elements); @SuppressWarnings("unchecked") static final Comparator<Element> valuesOf(List<Field> fields); static final long serialVersionUID; final ElementTo.Element withLabel; final ElementTo.Element withId; }### Answer: @Test public void testExistsIn() { Element element = createElement(); Element other = anotherElement(); assertTrue(element.existsIn(Arrays.asList(element))); assertFalse(element.existsIn(Arrays.asList(other))); }
### Question: Edge extends Element { @SuppressWarnings("PMD.CloseResource") public boolean connects(Vertex from, Vertex to) { return connects(from.getClass(), to.getClass()); } org.apache.tinkerpop.gremlin.structure.Edge delegate(); V fromAs(Class<V> vertexType); V toAs(Class<V> vertexType); @SuppressWarnings("PMD.CloseResource") boolean connects(Vertex from, Vertex to); @SuppressWarnings("PMD.CloseResource") boolean connects(Class<? extends Vertex> fromClass, Class<? extends Vertex> toClass); }### Answer: @Test public void testConnectsProperly() { Develops develops = createElement(); assertTrue(develops.connects(Person.class, Software.class)); assertFalse(develops.connects(Person.class, Person.class)); }
### Question: Classes { public static boolean isElement(Class<?> type) { return is(type, Element.class); } private Classes(); static boolean isElement(Class<?> type); static boolean isVertex(Object object); static boolean isVertex(Class<?> type); static boolean isEdge(Object object); static boolean isEdge(Class<?> type); static boolean isList(Object object); static boolean isList(Class<?> type); static boolean isSet(Object object); static boolean isSet(Class<?> type); static boolean isCollection(Object object); static boolean isCollection(Class<?> type); static boolean isFunctional(Class<?> type); @SuppressWarnings({"PMD.ShortMethodName"}) static boolean is(Class<?> type, Object that); @SuppressWarnings({"PMD.ShortMethodName"}) static boolean is(Object object, Class<?> that); @SuppressWarnings({"PMD.ShortMethodName"}) static boolean is(Class<?> type, Class<?> that); @SuppressWarnings("unchecked") static void sortCollection(Class<?> clazz, Collection<?> collection); @SneakyThrows @SuppressWarnings("rawtypes") static Collection newCollection(Class<?> clazz); static String name(Class<?> type); }### Answer: @Test public void testIsElement() { assertTrue(isElement(Person.class)); assertTrue(isElement(Develops.class)); }
### Question: Classes { public static boolean isVertex(Object object) { return object != null && isVertex(object.getClass()); } private Classes(); static boolean isElement(Class<?> type); static boolean isVertex(Object object); static boolean isVertex(Class<?> type); static boolean isEdge(Object object); static boolean isEdge(Class<?> type); static boolean isList(Object object); static boolean isList(Class<?> type); static boolean isSet(Object object); static boolean isSet(Class<?> type); static boolean isCollection(Object object); static boolean isCollection(Class<?> type); static boolean isFunctional(Class<?> type); @SuppressWarnings({"PMD.ShortMethodName"}) static boolean is(Class<?> type, Object that); @SuppressWarnings({"PMD.ShortMethodName"}) static boolean is(Object object, Class<?> that); @SuppressWarnings({"PMD.ShortMethodName"}) static boolean is(Class<?> type, Class<?> that); @SuppressWarnings("unchecked") static void sortCollection(Class<?> clazz, Collection<?> collection); @SneakyThrows @SuppressWarnings("rawtypes") static Collection newCollection(Class<?> clazz); static String name(Class<?> type); }### Answer: @Test public void testIsVertex() { assertTrue(isVertex(Person.class)); assertFalse(isVertex(Develops.class)); }
### Question: Classes { public static boolean isEdge(Object object) { return object != null && isEdge(object.getClass()); } private Classes(); static boolean isElement(Class<?> type); static boolean isVertex(Object object); static boolean isVertex(Class<?> type); static boolean isEdge(Object object); static boolean isEdge(Class<?> type); static boolean isList(Object object); static boolean isList(Class<?> type); static boolean isSet(Object object); static boolean isSet(Class<?> type); static boolean isCollection(Object object); static boolean isCollection(Class<?> type); static boolean isFunctional(Class<?> type); @SuppressWarnings({"PMD.ShortMethodName"}) static boolean is(Class<?> type, Object that); @SuppressWarnings({"PMD.ShortMethodName"}) static boolean is(Object object, Class<?> that); @SuppressWarnings({"PMD.ShortMethodName"}) static boolean is(Class<?> type, Class<?> that); @SuppressWarnings("unchecked") static void sortCollection(Class<?> clazz, Collection<?> collection); @SneakyThrows @SuppressWarnings("rawtypes") static Collection newCollection(Class<?> clazz); static String name(Class<?> type); }### Answer: @Test public void testIsEdge() { assertFalse(isEdge(Person.class)); assertTrue(isEdge(Develops.class)); }
### Question: Classes { public static boolean isList(Object object) { return object != null && isList(object.getClass()); } private Classes(); static boolean isElement(Class<?> type); static boolean isVertex(Object object); static boolean isVertex(Class<?> type); static boolean isEdge(Object object); static boolean isEdge(Class<?> type); static boolean isList(Object object); static boolean isList(Class<?> type); static boolean isSet(Object object); static boolean isSet(Class<?> type); static boolean isCollection(Object object); static boolean isCollection(Class<?> type); static boolean isFunctional(Class<?> type); @SuppressWarnings({"PMD.ShortMethodName"}) static boolean is(Class<?> type, Object that); @SuppressWarnings({"PMD.ShortMethodName"}) static boolean is(Object object, Class<?> that); @SuppressWarnings({"PMD.ShortMethodName"}) static boolean is(Class<?> type, Class<?> that); @SuppressWarnings("unchecked") static void sortCollection(Class<?> clazz, Collection<?> collection); @SneakyThrows @SuppressWarnings("rawtypes") static Collection newCollection(Class<?> clazz); static String name(Class<?> type); }### Answer: @Test public void testIsList() { assertFalse(isList(Person.class)); assertTrue(isList(Arrays.asList(develops))); }
### Question: CounterViewModel extends BaseObservable { @Bindable public int getCount() { return count; } void increment(); void decrement(); @Bindable int getCount(); }### Answer: @Test public void testInitialState() { Assert.assertEquals(0, counterViewModel.getCount()); }
### Question: CounterViewModel extends BaseObservable { public void increment() { setCount(getCount() + 1); } void increment(); void decrement(); @Bindable int getCount(); }### Answer: @Test public void testIncrement() { for (int i = 1; i <= 5; i++) { counterViewModel.increment(); Assert.assertEquals(i, counterViewModel.getCount()); } }
### Question: CounterViewModel extends BaseObservable { public void decrement() { setCount(getCount() - 1); } void increment(); void decrement(); @Bindable int getCount(); }### Answer: @Test public void testDecrement() { for (int i = 1; i <= 5; i++) { counterViewModel.decrement(); Assert.assertEquals(i * -1, counterViewModel.getCount()); } }
### Question: IniRealmDemo { public boolean helloShiro(String username, String password) { initSecurityUtils(); UsernamePasswordToken usernamePasswordToken = new UsernamePasswordToken(username, password); usernamePasswordToken.setRememberMe(true); Subject currentUser = SecurityUtils.getSubject(); try { currentUser.login(usernamePasswordToken); log.debug("currentUser.isAuthenticated()'s value : {}", currentUser.isAuthenticated()); } catch (Exception e) { log.error("usernamePasswordToken's value : {}", usernamePasswordToken); } return currentUser.isAuthenticated(); } boolean helloShiro(String username, String password); }### Answer: @Test void helloShiro() { String username = "admin"; String password = "admin"; IniRealmDemo iniRealmDemo = new IniRealmDemo(); Assert.assertEquals(true, iniRealmDemo.helloShiro(username, password)); }
### Question: StaticCglibProxyDemo extends UserServiceImpl { @Override public void removeUser(String name) { log.warn("before remove user"); super.removeUser(name); log.warn("after remove user"); } @Override void addUser(String name); @Override void removeUser(String name); @Override String getUsername(String name); }### Answer: @Test void removeUser() { }
### Question: StaticCglibProxyDemo extends UserServiceImpl { @Override public String getUsername(String name) { log.warn("before get username"); String username = super.getUsername(name); log.warn("after get username"); return username; } @Override void addUser(String name); @Override void removeUser(String name); @Override String getUsername(String name); }### Answer: @Test void getUsername() { }
### Question: JDKProxyDemo { public UserService getUserService(){ ProxyHandler proxyHandler = new ProxyHandler(userService); return (UserService) Proxy.newProxyInstance(proxyHandler.getClass().getClassLoader(),userService.getClass().getInterfaces(),proxyHandler); } UserService getUserService(); }### Answer: @Test void getUserService() { jdkProxyDemo.getUserService().addUser("xiaoming"); jdkProxyDemo.getUserService().removeUser("xiaoming"); jdkProxyDemo.getUserService().getUsername("xiaoming"); System.out.println(); jdkProxyDemo.getUserService().getClass(); } @Test void getUserService2(){ jdkProxyDemo.getUserService().getUsernameFromSelf("xiaoming"); }
### Question: CglibProxyDemo { public UserService getUserService(){ Enhancer en = new Enhancer(); en.setSuperclass(userService.getClass()); en.setCallback((MethodInterceptor) (arg0, method, args, arg3) -> { log.info("pre class: {} method: {} return type:{} args:{}", userService.getClass().getName(),method.getName(),method.getReturnType(),args); Object result = method.invoke(userService, args); log.info("post class: {} method: {} return type:{} result:{}", userService.getClass().getName(),method.getName(),method.getReturnType(),result); return result; }); return (UserService) en.create(); } UserService getUserService(); }### Answer: @Test void getUserService() { cglibProxyDemo.getUserService().getUsernameFromSelf("xiaoming"); } @Test void getUserService1() { cglibProxyDemo.getUserService().getUsername("xiaoming"); }
### Question: LogAop { @Pointcut("execution(public * org.laidu.learn.spring.aop.service..*(..))") public void serviceLog(){} @Pointcut("execution(* org.laidu.learn.spring.aop.service..*(..))") void serviceLog(); @Before("serviceLog()") void doBefore(JoinPoint joinPoint); @AfterReturning(returning = "ret", pointcut = "serviceLog()") void doAfterReturning(Object ret); }### Answer: @Test void serviceLog() { userService.getUsername("xiaomig"); }
### Question: UserServiceImpl implements UserService { @Override @Cacheable("getUserInfo") public UserInfo getUserInfo(String key) { UserInfo userInfo = redisTemplate.opsForValue().get(key); if (userInfo == null) { log.info("cache null : {}", key); userInfo = addUser("demo","demo"); } return userInfo; } @Autowired UserServiceImpl(RedisTemplate<String, UserInfo> redisTemplate); @Override @Cacheable("getUserInfo") UserInfo getUserInfo(String key); @Override @Cacheable("userinfo") UserInfo addUser(String username, String password); @Override UserInfo updateUsername(String id, String username); }### Answer: @Test void getUserInfo() { UserInfo userInfo = userService.getUserInfo("xiaoming"); log.info("user info: {}", userInfo); }
### Question: UserServiceImpl implements UserService { @Override @Cacheable("userinfo") public UserInfo addUser(String username, String password) { return UserInfo.builder() .userId(UUID.randomUUID().toString()) .username(username) .build(); } @Autowired UserServiceImpl(RedisTemplate<String, UserInfo> redisTemplate); @Override @Cacheable("getUserInfo") UserInfo getUserInfo(String key); @Override @Cacheable("userinfo") UserInfo addUser(String username, String password); @Override UserInfo updateUsername(String id, String username); }### Answer: @Test void addUser() { UserInfo userInfo = userService.addUser("xiaoming","123123"); log.info("user info: {}", userInfo); }
### Question: UserServiceImpl implements UserService { @Override public UserInfo updateUsername(String id, String username) { boolean res = false; UserInfo info = null; RLock lock = redission.getLock("lock_"+id); try { lock.lock(10, TimeUnit.SECONDS); System.out.println("got lock"); }catch (Exception e){ log.warn("获取redis锁失败! {}",id); } finally { try{ lock.unlock(); }finally { System.out.println("unlock"); } } return info; } @Autowired UserServiceImpl(RedisTemplate<String, UserInfo> redisTemplate); @Override @Cacheable("getUserInfo") UserInfo getUserInfo(String key); @Override @Cacheable("userinfo") UserInfo addUser(String username, String password); @Override UserInfo updateUsername(String id, String username); }### Answer: @Test void updateUsername() { IntStream.range(0,1000).parallel() .forEach( i -> { userService.updateUsername("123","xiaoming"+i); }); }
### Question: SpringClientDemo implements ClientDemo { @Override public void declareQueue() throws IOException { RabbitAdmin rabbitAdmin = rabbitAdmin(); try { rabbitAdmin.declareQueue(new Queue("demo2",false,false,false)); }catch (Exception e){ try { if (406 == ((AMQImpl.Channel.Close) ((ShutdownSignalException)e.getCause().getCause()).getReason()).getReplyCode()) { rabbitAdmin.deleteQueue("demo2"); declareQueue(); } }catch (Exception e1){ } log.error("e 's value : {}", e); } } CachingConnectionFactory cachingConnectionFactory(); RabbitAdmin rabbitAdmin(); @Override void declareQueue(); static void main(String[] args); }### Answer: @Test void declareQueue() throws IOException { SpringClientDemo clientDemo = new SpringClientDemo(); clientDemo.declareQueue(); }
### Question: ExtendClass implements InterfaceA,InterfaceB { @Override public void sayHello() { log.debug("-*--*--*--*--*--*--*--*--*-- sayHello --*--*--*--*--*--*--*--*--*-: {}","123"); } @Override void sayHello(); @Override void sayBye(); @Override void sayGood(); static void main(String[] args); }### Answer: @Test @DisplayName("") void sayHello() { new ExtendClass().sayHello(); }
### Question: ExtendClass implements InterfaceA,InterfaceB { @Override public void sayBye() { ((InterfaceA) () -> log.debug("-*--*--*--*--*--*--*--*--*-- sayGood --*--*--*--*--*--*--*--*--*-: {}","good")).sayBye(); } @Override void sayHello(); @Override void sayBye(); @Override void sayGood(); static void main(String[] args); }### Answer: @Test void sayBye() { }
### Question: ExtendClass implements InterfaceA,InterfaceB { @Override public void sayGood() { log.debug("-*--*--*--*--*--*--*--*--*-- sayGood --*--*--*--*--*--*--*--*--*-: {}","good"); } @Override void sayHello(); @Override void sayBye(); @Override void sayGood(); static void main(String[] args); }### Answer: @Test void sayGood() { }
### Question: ListStreamDemo { public static String list2String(List<String> list){ return list.parallelStream().collect(Collectors.joining(",")); } static String list2String(List<String> list); static String list2String2(List<String> list); static List<Student> distinctBy(List<Student> students); }### Answer: @Test void list2String() { log.info("string result: {}", ListStreamDemo.list2String(list)); }
### Question: ListStreamDemo { public static String list2String2(List<String> list){ return String.join(",",list); } static String list2String(List<String> list); static String list2String2(List<String> list); static List<Student> distinctBy(List<Student> students); }### Answer: @Test void list2String2() { log.info("String2 result: {}", ListStreamDemo.list2String2(list)); }
### Question: StringPartMethod { public static String join(CharSequence delimiter, CharSequence... elements) { Objects.requireNonNull(delimiter); Objects.requireNonNull(elements); StringJoiner joiner = new StringJoiner(delimiter); for (CharSequence cs: elements) { joiner.add(cs); } return joiner.toString(); } static String join(CharSequence delimiter, CharSequence... elements); static String join(CharSequence delimiter, Iterable<? extends CharSequence> elements); }### Answer: @Test @DisplayName("java 8 新增方法") void join() { String var = "123123"; var = String.join(":", "a","b","c"); log.info("-*--*--*--*- var: {} -*--*--*--*--",var); } @Test void join1() { String var = "123123"; List<CharSequence> charSequences = Arrays.asList("a","b","c"); var = String.join("-",charSequences); log.info("-*--*--*--*- var: {} -*--*--*--*--",var); }
### Question: CurlParserUtil { public Map<String, String> getHeaders(String curlLine) { Map<String, String> keyValuePairs = keyValuePairs(curlLine); keyValuePairs.remove("Content-Length"); return keyValuePairs; } private CurlParserUtil(); static CurlParserUtil getInstance(); Map<String, String> getHeaders(String curlLine); Map<String, String> getCookies(String curlLine); String getMethod(String curlLine); String getUrl(String curlLine); String getBodyString(String curlLine); Map<String, String> getFormBody(String curlLine); }### Answer: @Test void getHeaders() { CurlParserUtil.getInstance().getHeaders(curlLine); }
### Question: CurlParserUtil { public Map<String, String> getCookies(String curlLine) { Map<String, String> cookieMap = new HashMap<>(); StringBuilder cookiesString = new StringBuilder(); cookiesString.append(getHeaders(curlLine).get("Cookie")); cookiesString.append(getBCookiesString(curlLine)); if (StringUtil.isNotBlank(cookiesString.toString())) { String cookiesPattern = "([^; ]*=[^;]*)+"; List<String> cookieStringList = RegexUtil.getInstance().getMacthAllResult(cookiesPattern,cookiesString.toString()); cookieStringList.forEach(cookie -> { String[] cookiePairs = cookie.split("=", 2); if (cookiePairs.length == 2) { cookieMap.put(cookiePairs[0].trim(), URLDecoder.decode(cookiePairs[1].trim())); } }); } return cookieMap; } private CurlParserUtil(); static CurlParserUtil getInstance(); Map<String, String> getHeaders(String curlLine); Map<String, String> getCookies(String curlLine); String getMethod(String curlLine); String getUrl(String curlLine); String getBodyString(String curlLine); Map<String, String> getFormBody(String curlLine); }### Answer: @Test void getCookies() { CurlParserUtil.getInstance().getCookies(curlLine).forEach((k,v) -> System.out.println(k + " : " + v)); }
### Question: CurlParserUtil { public String getMethod(String curlLine) { String methodPattern = "-X \\$'([A-Z]{2,5})'"; int methodIndex = 1; return RegexUtil.getInstance().getMacthResult(methodPattern, curlLine, methodIndex, "GET"); } private CurlParserUtil(); static CurlParserUtil getInstance(); Map<String, String> getHeaders(String curlLine); Map<String, String> getCookies(String curlLine); String getMethod(String curlLine); String getUrl(String curlLine); String getBodyString(String curlLine); Map<String, String> getFormBody(String curlLine); }### Answer: @Test void getMethod() { Assert.assertEquals("POST",CurlParserUtil.getInstance().getMethod(curlLine)); }
### Question: RabbitmqClientDemo implements ClientDemo { public ConnectionFactory connectionFactory(){ ConnectionFactory connectionFactory = new ConnectionFactory(); connectionFactory.setHost("dev"); connectionFactory.setPort(5672); connectionFactory.setUsername("admin"); connectionFactory.setPassword("admin"); connectionFactory.setVirtualHost("/learn"); return connectionFactory; } ConnectionFactory connectionFactory(); Connection connection(ConnectionFactory connectionFactory); @Override void declareQueue(); }### Answer: @Test void connectionFactory() { }
### Question: CurlParserUtil { public String getUrl(String curlLine) { String urlPattern = "\\$'(https?: int urlIndex = 1; return RegexUtil.getInstance().getMacthResult(urlPattern, curlLine, urlIndex); } private CurlParserUtil(); static CurlParserUtil getInstance(); Map<String, String> getHeaders(String curlLine); Map<String, String> getCookies(String curlLine); String getMethod(String curlLine); String getUrl(String curlLine); String getBodyString(String curlLine); Map<String, String> getFormBody(String curlLine); }### Answer: @Test void getUrl() { Assert.assertEquals("http: }
### Question: CurlParserUtil { public String getBodyString(String curlLine) { String stringBodyPattern = "--data-binary \\$'([^\\$]*)'"; int stringBodyIndex = 1; return RegexUtil.getInstance().getMacthResult(stringBodyPattern, curlLine, stringBodyIndex); } private CurlParserUtil(); static CurlParserUtil getInstance(); Map<String, String> getHeaders(String curlLine); Map<String, String> getCookies(String curlLine); String getMethod(String curlLine); String getUrl(String curlLine); String getBodyString(String curlLine); Map<String, String> getFormBody(String curlLine); }### Answer: @Test void getBodyString() { String dataString = "jlX3dWILl/dMQ+wc0JAMHlKhylfeLb19HyBcb/QKcPKRMtB5Ri77QJ2OpC6P8Rp/aai3j7awGyo1SD/MckKxnHTeGnUIh9Uopg7S+4Db1n8hVV9vsQMLrmZy+0VCnGFgVuTWYvMgiow9+tZJFFdQ549IhLmXBs4Lm3UkEtzpfvwfdoCZC9vAaTbvc6YrGFk9vTRUag3oT+Wlm+RY8KaejV7JXCzV4+jA98GFbVTAn4yNuPIyIoHyhoELsnvMwlbuVmftKn0DDlVWM7xt7P9+AMiyXbNu+2xMuW6w+1EK Assert.assertEquals(dataString,CurlParserUtil.getInstance().getBodyString(curlLine)); }
### Question: CurlParserUtil { public Map<String, String> getFormBody(String curlLine) { Map<String, String> formMap = new HashMap<>(); String formBodyString = getBodyString(curlLine); String formDataPattern = "([^=&]+=[^&']*)+"; int formDataIndex = 1; List<String> formStringList = RegexUtil.getInstance().getMacthAllResult(formDataPattern, formBodyString, formDataIndex); formStringList.forEach(formString -> { String[] form = formString.split("=",2); if (form.length==2) { formMap.put(form[0].trim(),form[1].trim()); } }); return formMap; } private CurlParserUtil(); static CurlParserUtil getInstance(); Map<String, String> getHeaders(String curlLine); Map<String, String> getCookies(String curlLine); String getMethod(String curlLine); String getUrl(String curlLine); String getBodyString(String curlLine); Map<String, String> getFormBody(String curlLine); }### Answer: @Test void getFormBody() { CurlParserUtil.getInstance().getFormBody(curlLine).forEach((k,v) -> System.out.println(k + " : " + v)); }
### Question: JAXBUtil { public String obj2Xml(Object obj) throws JAXBException, UnsupportedEncodingException { ByteArrayOutputStream os = new ByteArrayOutputStream(); JAXBContext jaxbContext = JAXBContext.newInstance(obj.getClass()); Marshaller jaxbMarshaller = jaxbContext.createMarshaller(); jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true ); jaxbMarshaller.marshal(obj,os); return new String(os.toByteArray(),"UTF-8"); } private JAXBUtil(); static JAXBUtil getInstance(); String obj2Xml(Object obj); T xml2Obj(String xmlSource, Class<T> clazz); }### Answer: @Test void obj2Xml() throws JAXBException, UnsupportedEncodingException { List<String> names = new ArrayList<>(); names.add("123"); names.add("123"); names.add("123"); names.add("123"); Person person = Person.builder() .name("xiaoming/name>aadsadsa]") .dsaa(names) .sex("nam") .build(); List<Person> people = new ArrayList<>(); people.add(person); people.add(person); people.add(person); people.add(person); String result = JAXBUtil.getInstance().obj2Xml(Person1.builder().person(people).build()); System.out.println(result); }
### Question: RegexUtil { public List<String> getMacthAllResult(String regex, String source, int index) { return getMacthAllResult(Pattern.compile(regex),source,index); } private RegexUtil(); static RegexUtil getInstance(); List<String> getMacthAllResult(String regex, String source, int index); List<String> getMacthAllResult(Pattern pattern, String source, int index); List<String> getMacthAllResult(String regex, String source); List<String> getMacthAllResult(Pattern pattern, String source); String getMacthResult(String regex, String source, int index); String getMacthResult(Pattern pattern, String source, int index); String getMacthResult(String regex, String source); String getMacthResult(Pattern pattern, String source); String getMacthResult(String regex, String source, int index, String defaultValue); String getMacthResult(Pattern pattern, String source, int index, String defaultValue); }### Answer: @Test void getMacthAllResult() { }
### Question: AESEncryptionUtil { public byte[] cbcEncrypt(byte[] data, byte[] key, byte[] ivp) { return BasicEncryptionUtil.getInstance().encrypt(HelperHolder.ALGORITHM, HelperHolder.ALGORITHM_CBC_KEY, key, ivp, data); } private AESEncryptionUtil(); static AESEncryptionUtil getInstance(); byte[] cbcEncrypt(byte[] data, byte[] key, byte[] ivp); byte[] cbcDecrypt(byte[] data, byte[] key, byte[] ivp); byte[] ecbEncrypt(byte[] data, byte[] key); byte[] ecbDecrypt(byte[] data, byte[] key); }### Answer: @Test void cbcEncrypt() throws DecoderException { byte[] result = AESEncryptionUtil.getInstance().cbcEncrypt(palaintext.getBytes(), key.getBytes(), Base64.decode(ivp)); log.info("result 's value : {}", result); Assert.assertEquals(URLDecoder.decode(cryptograph), Base64.encodeToString(result)); }