target
stringlengths
20
113k
src_fm
stringlengths
11
86.3k
src_fm_fc
stringlengths
21
86.4k
src_fm_fc_co
stringlengths
30
86.4k
src_fm_fc_ms
stringlengths
42
86.8k
src_fm_fc_ms_ff
stringlengths
43
86.8k
@Ignore @Test public void nodeStatsTest() throws Exception { PrivateKey issuerKey = new PrivateKey(Do.read("./src/test_contracts/keys/reconfig_key.private.unikey")); TestSpace testSpace = prepareTestSpace(issuerKey); Thread.sleep(2000); Binder b = testSpace.client.getStats(90); int uptime = b.getIntOrThrow("uptime"); testSpace.nodes.get(0).config.setStatsIntervalSmall(Duration.ofSeconds(4)); testSpace.nodes.get(0).config.setStatsIntervalBig(Duration.ofSeconds(60)); testSpace.nodes.get(0).config.getAddressesWhiteList().add(new KeyAddress(issuerKey.getPublicKey(), 0, true)); while (testSpace.client.getStats(null).getIntOrThrow("uptime") >= uptime) { Thread.sleep(500); } for (int i = 0; i < 30; i++) { Instant now = Instant.now(); Contract contract = new Contract(issuerKey); contract.seal(); testSpace.client.register(contract.getPackedTransaction(), 1500); contract = new Contract(issuerKey); contract.seal(); testSpace.client.register(contract.getPackedTransaction(), 1500); Thread.sleep(4000 - (Instant.now().toEpochMilli() - now.toEpochMilli())); Binder binder = testSpace.client.getStats(90); assertEquals(binder.getIntOrThrow("smallIntervalApproved"), 2); int target = i < 15 ? (i + 1) * 2 : 30; assertTrue(binder.getIntOrThrow("bigIntervalApproved") <= target && binder.getIntOrThrow("bigIntervalApproved") >= target - 2); } testSpace.nodes.forEach(x -> x.shutdown()); }
public void shutdown() { try { if (hookThread != null) Runtime.getRuntime().removeShutdownHook(hookThread); ledger.close(); log("shutting down"); network.shutdown(); clientHTTPServer.shutdown(); } catch (Exception e) { } synchronized (parser) { parser.notifyAll(); } try { logger.close(); } catch (Exception e) { e.printStackTrace(); } }
Main { public void shutdown() { try { if (hookThread != null) Runtime.getRuntime().removeShutdownHook(hookThread); ledger.close(); log("shutting down"); network.shutdown(); clientHTTPServer.shutdown(); } catch (Exception e) { } synchronized (parser) { parser.notifyAll(); } try { logger.close(); } catch (Exception e) { e.printStackTrace(); } } }
Main { public void shutdown() { try { if (hookThread != null) Runtime.getRuntime().removeShutdownHook(hookThread); ledger.close(); log("shutting down"); network.shutdown(); clientHTTPServer.shutdown(); } catch (Exception e) { } synchronized (parser) { parser.notifyAll(); } try { logger.close(); } catch (Exception e) { e.printStackTrace(); } } Main(String[] args); }
Main { public void shutdown() { try { if (hookThread != null) Runtime.getRuntime().removeShutdownHook(hookThread); ledger.close(); log("shutting down"); network.shutdown(); clientHTTPServer.shutdown(); } catch (Exception e) { } synchronized (parser) { parser.notifyAll(); } try { logger.close(); } catch (Exception e) { e.printStackTrace(); } } Main(String[] args); static void main(String[] args); void waitReady(); void shutdown(); void setVerboseLevel(int level); void setUDPVerboseLevel(int level); void restartUDPAdapter(); PublicKey getNodePublicKey(); }
Main { public void shutdown() { try { if (hookThread != null) Runtime.getRuntime().removeShutdownHook(hookThread); ledger.close(); log("shutting down"); network.shutdown(); clientHTTPServer.shutdown(); } catch (Exception e) { } synchronized (parser) { parser.notifyAll(); } try { logger.close(); } catch (Exception e) { e.printStackTrace(); } } Main(String[] args); static void main(String[] args); void waitReady(); void shutdown(); void setVerboseLevel(int level); void setUDPVerboseLevel(int level); void restartUDPAdapter(); PublicKey getNodePublicKey(); static final String NODE_VERSION; final Reporter reporter; final BufferedLogger logger; public NetConfig netConfig; public NetworkV2 network; final Config config; public NodeInfo myInfo; public Node node; public ItemCache cache; public ParcelCache parcelCache; public PaidOperationCache paidOperationCache; }
@Test public void resynItemTest() throws Exception { PrivateKey issuerKey = new PrivateKey(Do.read("./src/test_contracts/keys/reconfig_key.private.unikey")); TestSpace testSpace = prepareTestSpace(issuerKey); testSpace.nodes.forEach(n -> n.config.setIsFreeRegistrationsAllowedFromYaml(true)); int absentNode = testSpace.nodes.size() - 1; testSpace.nodes.get(absentNode).shutdown(); testSpace.nodes.remove(absentNode); Contract contract = new Contract(issuerKey); contract.seal(); testSpace.client.register(contract.getPackedTransaction(), 1500); assertEquals(testSpace.client.getState(contract.getId()).state, ItemState.APPROVED); testSpace.nodes.forEach(n -> n.shutdown()); Thread.sleep(2000); testSpace = prepareTestSpace(issuerKey); testSpace.nodes.forEach(n -> n.config.setIsFreeRegistrationsAllowedFromYaml(true)); assertEquals(testSpace.client.getState(contract.getId()).state, ItemState.APPROVED); StateRecord r0 = testSpace.nodes.get(0).node.getLedger().getRecord(contract.getId()); r0.setExpiresAt(r0.getExpiresAt().minusHours(1)); r0.save(); StateRecord r1 = testSpace.nodes.get(1).node.getLedger().getRecord(contract.getId()); r1.setCreatedAt(r1.getCreatedAt().plusHours(1)); r1.save(); Client absentNodeClient = new Client(testSpace.myKey, testSpace.nodes.get(absentNode).myInfo, null); assertEquals(absentNodeClient.getState(contract.getId()).state, ItemState.UNDEFINED); absentNodeClient.resyncItem(contract.getId()); assertEquals(testSpace.client.getState(contract.getId()).state, ItemState.APPROVED); ItemResult rr; while (true) { rr = absentNodeClient.getState(contract.getId()); if (!rr.state.isPending()) break; Thread.sleep(500); } assertEquals(rr.state, ItemState.APPROVED); Average createdAverage = new Average(); Average expiredAverage = new Average(); ItemResult ir0 = testSpace.nodes.get(0).node.checkItem(contract.getId()); ItemResult ir1 = testSpace.nodes.get(1).node.checkItem(contract.getId()); ItemResult ir2 = testSpace.nodes.get(2).node.checkItem(contract.getId()); createdAverage.update(ir0.createdAt.toEpochSecond()); createdAverage.update(ir2.createdAt.toEpochSecond()); expiredAverage.update(ir1.expiresAt.toEpochSecond()); expiredAverage.update(ir2.expiresAt.toEpochSecond()); assertEquals(rr.createdAt.toEpochSecond(), (long) createdAverage.average()); assertEquals(rr.expiresAt.toEpochSecond(), (long) expiredAverage.average()); testSpace.nodes.forEach(x -> x.shutdown()); }
public void shutdown() { try { if (hookThread != null) Runtime.getRuntime().removeShutdownHook(hookThread); ledger.close(); log("shutting down"); network.shutdown(); clientHTTPServer.shutdown(); } catch (Exception e) { } synchronized (parser) { parser.notifyAll(); } try { logger.close(); } catch (Exception e) { e.printStackTrace(); } }
Main { public void shutdown() { try { if (hookThread != null) Runtime.getRuntime().removeShutdownHook(hookThread); ledger.close(); log("shutting down"); network.shutdown(); clientHTTPServer.shutdown(); } catch (Exception e) { } synchronized (parser) { parser.notifyAll(); } try { logger.close(); } catch (Exception e) { e.printStackTrace(); } } }
Main { public void shutdown() { try { if (hookThread != null) Runtime.getRuntime().removeShutdownHook(hookThread); ledger.close(); log("shutting down"); network.shutdown(); clientHTTPServer.shutdown(); } catch (Exception e) { } synchronized (parser) { parser.notifyAll(); } try { logger.close(); } catch (Exception e) { e.printStackTrace(); } } Main(String[] args); }
Main { public void shutdown() { try { if (hookThread != null) Runtime.getRuntime().removeShutdownHook(hookThread); ledger.close(); log("shutting down"); network.shutdown(); clientHTTPServer.shutdown(); } catch (Exception e) { } synchronized (parser) { parser.notifyAll(); } try { logger.close(); } catch (Exception e) { e.printStackTrace(); } } Main(String[] args); static void main(String[] args); void waitReady(); void shutdown(); void setVerboseLevel(int level); void setUDPVerboseLevel(int level); void restartUDPAdapter(); PublicKey getNodePublicKey(); }
Main { public void shutdown() { try { if (hookThread != null) Runtime.getRuntime().removeShutdownHook(hookThread); ledger.close(); log("shutting down"); network.shutdown(); clientHTTPServer.shutdown(); } catch (Exception e) { } synchronized (parser) { parser.notifyAll(); } try { logger.close(); } catch (Exception e) { e.printStackTrace(); } } Main(String[] args); static void main(String[] args); void waitReady(); void shutdown(); void setVerboseLevel(int level); void setUDPVerboseLevel(int level); void restartUDPAdapter(); PublicKey getNodePublicKey(); static final String NODE_VERSION; final Reporter reporter; final BufferedLogger logger; public NetConfig netConfig; public NetworkV2 network; final Config config; public NodeInfo myInfo; public Node node; public ItemCache cache; public ParcelCache parcelCache; public PaidOperationCache paidOperationCache; }
@Test public void freeRegistrationsAllowedFromCoreVersion() throws Exception { List<Main> mm = new ArrayList<>(); for (int i = 0; i < 4; i++) mm.add(createMain("node" + (i + 1), false)); Main main = mm.get(0); Client client = new Client(TestKeys.privateKey(20), main.myInfo, null); Contract contract = new Contract(TestKeys.privateKey(0)); contract.seal(); ItemState expectedState = ItemState.UNDEFINED; if (Core.VERSION.contains("private")) expectedState = ItemState.APPROVED; System.out.println("Core.VERSION: " + Core.VERSION); System.out.println("expectedState: " + expectedState); ItemResult itemResult = client.register(contract.getPackedTransaction(), 5000); System.out.println("itemResult: " + itemResult); assertEquals(expectedState, itemResult.state); mm.forEach(x -> x.shutdown()); }
public void shutdown() { try { if (hookThread != null) Runtime.getRuntime().removeShutdownHook(hookThread); ledger.close(); log("shutting down"); network.shutdown(); clientHTTPServer.shutdown(); } catch (Exception e) { } synchronized (parser) { parser.notifyAll(); } try { logger.close(); } catch (Exception e) { e.printStackTrace(); } }
Main { public void shutdown() { try { if (hookThread != null) Runtime.getRuntime().removeShutdownHook(hookThread); ledger.close(); log("shutting down"); network.shutdown(); clientHTTPServer.shutdown(); } catch (Exception e) { } synchronized (parser) { parser.notifyAll(); } try { logger.close(); } catch (Exception e) { e.printStackTrace(); } } }
Main { public void shutdown() { try { if (hookThread != null) Runtime.getRuntime().removeShutdownHook(hookThread); ledger.close(); log("shutting down"); network.shutdown(); clientHTTPServer.shutdown(); } catch (Exception e) { } synchronized (parser) { parser.notifyAll(); } try { logger.close(); } catch (Exception e) { e.printStackTrace(); } } Main(String[] args); }
Main { public void shutdown() { try { if (hookThread != null) Runtime.getRuntime().removeShutdownHook(hookThread); ledger.close(); log("shutting down"); network.shutdown(); clientHTTPServer.shutdown(); } catch (Exception e) { } synchronized (parser) { parser.notifyAll(); } try { logger.close(); } catch (Exception e) { e.printStackTrace(); } } Main(String[] args); static void main(String[] args); void waitReady(); void shutdown(); void setVerboseLevel(int level); void setUDPVerboseLevel(int level); void restartUDPAdapter(); PublicKey getNodePublicKey(); }
Main { public void shutdown() { try { if (hookThread != null) Runtime.getRuntime().removeShutdownHook(hookThread); ledger.close(); log("shutting down"); network.shutdown(); clientHTTPServer.shutdown(); } catch (Exception e) { } synchronized (parser) { parser.notifyAll(); } try { logger.close(); } catch (Exception e) { e.printStackTrace(); } } Main(String[] args); static void main(String[] args); void waitReady(); void shutdown(); void setVerboseLevel(int level); void setUDPVerboseLevel(int level); void restartUDPAdapter(); PublicKey getNodePublicKey(); static final String NODE_VERSION; final Reporter reporter; final BufferedLogger logger; public NetConfig netConfig; public NetworkV2 network; final Config config; public NodeInfo myInfo; public Node node; public ItemCache cache; public ParcelCache parcelCache; public PaidOperationCache paidOperationCache; }
@Test public void freeRegistrationsAllowedFromConfigOrVersion() throws Exception { List<Main> mm = new ArrayList<>(); for (int i = 0; i < 4; i++) mm.add(createMain("node" + (i + 1), false)); Main main = mm.get(0); main.config.setIsFreeRegistrationsAllowedFromYaml(true); Client client = new Client(TestKeys.privateKey(20), main.myInfo, null); Contract contract = new Contract(TestKeys.privateKey(0)); contract.seal(); ItemState expectedState = ItemState.APPROVED; System.out.println("expectedState: " + expectedState); ItemResult itemResult = client.register(contract.getPackedTransaction(), 5000); System.out.println("itemResult: " + itemResult); assertEquals(expectedState, itemResult.state); main.config.setIsFreeRegistrationsAllowedFromYaml(false); contract = new Contract(TestKeys.privateKey(0)); contract.seal(); expectedState = ItemState.UNDEFINED; if (Core.VERSION.contains("private")) expectedState = ItemState.APPROVED; System.out.println("Core.VERSION: " + Core.VERSION); System.out.println("expectedState: " + expectedState); itemResult = client.register(contract.getPackedTransaction(), 5000); System.out.println("itemResult: " + itemResult); assertEquals(expectedState, itemResult.state); mm.forEach(x -> x.shutdown()); }
public void shutdown() { try { if (hookThread != null) Runtime.getRuntime().removeShutdownHook(hookThread); ledger.close(); log("shutting down"); network.shutdown(); clientHTTPServer.shutdown(); } catch (Exception e) { } synchronized (parser) { parser.notifyAll(); } try { logger.close(); } catch (Exception e) { e.printStackTrace(); } }
Main { public void shutdown() { try { if (hookThread != null) Runtime.getRuntime().removeShutdownHook(hookThread); ledger.close(); log("shutting down"); network.shutdown(); clientHTTPServer.shutdown(); } catch (Exception e) { } synchronized (parser) { parser.notifyAll(); } try { logger.close(); } catch (Exception e) { e.printStackTrace(); } } }
Main { public void shutdown() { try { if (hookThread != null) Runtime.getRuntime().removeShutdownHook(hookThread); ledger.close(); log("shutting down"); network.shutdown(); clientHTTPServer.shutdown(); } catch (Exception e) { } synchronized (parser) { parser.notifyAll(); } try { logger.close(); } catch (Exception e) { e.printStackTrace(); } } Main(String[] args); }
Main { public void shutdown() { try { if (hookThread != null) Runtime.getRuntime().removeShutdownHook(hookThread); ledger.close(); log("shutting down"); network.shutdown(); clientHTTPServer.shutdown(); } catch (Exception e) { } synchronized (parser) { parser.notifyAll(); } try { logger.close(); } catch (Exception e) { e.printStackTrace(); } } Main(String[] args); static void main(String[] args); void waitReady(); void shutdown(); void setVerboseLevel(int level); void setUDPVerboseLevel(int level); void restartUDPAdapter(); PublicKey getNodePublicKey(); }
Main { public void shutdown() { try { if (hookThread != null) Runtime.getRuntime().removeShutdownHook(hookThread); ledger.close(); log("shutting down"); network.shutdown(); clientHTTPServer.shutdown(); } catch (Exception e) { } synchronized (parser) { parser.notifyAll(); } try { logger.close(); } catch (Exception e) { e.printStackTrace(); } } Main(String[] args); static void main(String[] args); void waitReady(); void shutdown(); void setVerboseLevel(int level); void setUDPVerboseLevel(int level); void restartUDPAdapter(); PublicKey getNodePublicKey(); static final String NODE_VERSION; final Reporter reporter; final BufferedLogger logger; public NetConfig netConfig; public NetworkV2 network; final Config config; public NodeInfo myInfo; public Node node; public ItemCache cache; public ParcelCache parcelCache; public PaidOperationCache paidOperationCache; }
@Test public void testTokenContractApi() throws Exception { List<Main> mm = new ArrayList<>(); for (int i = 0; i < 4; i++) mm.add(createMain("node" + (i + 1), false)); Main main = mm.get(0); main.config.setIsFreeRegistrationsAllowedFromYaml(true); Client client = new Client(TestKeys.privateKey(20), main.myInfo, null); Set<PrivateKey> issuerPrivateKeys = new HashSet<>(asList(TestKeys.privateKey(1))); Set<PublicKey> issuerPublicKeys = new HashSet<>(asList(TestKeys.publicKey(1))); Set<PublicKey> ownerPublicKeys = new HashSet<>(asList(TestKeys.publicKey(2))); Contract tokenContract = ContractsService.createTokenContract(issuerPrivateKeys, ownerPublicKeys, new BigDecimal("1000000")); tokenContract.check(); tokenContract.traceErrors(); assertTrue(tokenContract.getOwner().isAllowedForKeys(ownerPublicKeys)); assertTrue(tokenContract.getIssuer().isAllowedForKeys(issuerPrivateKeys)); assertTrue(tokenContract.getCreator().isAllowedForKeys(issuerPrivateKeys)); assertFalse(tokenContract.getOwner().isAllowedForKeys(issuerPrivateKeys)); assertFalse(tokenContract.getIssuer().isAllowedForKeys(ownerPublicKeys)); assertFalse(tokenContract.getCreator().isAllowedForKeys(ownerPublicKeys)); assertTrue(tokenContract.getExpiresAt().isAfter(ZonedDateTime.now().plusMonths(3))); assertTrue(tokenContract.getCreatedAt().isBefore(ZonedDateTime.now())); assertEquals(InnerContractsService.getDecimalField(tokenContract, "amount"), new Decimal(1000000)); assertEquals(tokenContract.getPermissions().get("split_join").size(), 1); Binder splitJoinParams = tokenContract.getPermissions().get("split_join").iterator().next().getParams(); assertEquals(splitJoinParams.get("min_value"), "0.01"); assertEquals(splitJoinParams.get("min_unit"), "0.01"); assertEquals(splitJoinParams.get("field_name"), "amount"); assertTrue(splitJoinParams.get("join_match_fields") instanceof List); assertEquals(((List) splitJoinParams.get("join_match_fields")).get(0), "state.origin"); assertTrue(tokenContract.isPermitted("revoke", ownerPublicKeys)); assertTrue(tokenContract.isPermitted("revoke", issuerPublicKeys)); assertTrue(tokenContract.isPermitted("change_owner", ownerPublicKeys)); assertFalse(tokenContract.isPermitted("change_owner", issuerPublicKeys)); assertTrue(tokenContract.isPermitted("split_join", ownerPublicKeys)); assertFalse(tokenContract.isPermitted("split_join", issuerPublicKeys)); ItemResult itemResult = client.register(tokenContract.getPackedTransaction(), 5000); System.out.println("token contract : " + itemResult); assertEquals(ItemState.APPROVED, itemResult.state); mm.forEach(x -> x.shutdown()); }
public void shutdown() { try { if (hookThread != null) Runtime.getRuntime().removeShutdownHook(hookThread); ledger.close(); log("shutting down"); network.shutdown(); clientHTTPServer.shutdown(); } catch (Exception e) { } synchronized (parser) { parser.notifyAll(); } try { logger.close(); } catch (Exception e) { e.printStackTrace(); } }
Main { public void shutdown() { try { if (hookThread != null) Runtime.getRuntime().removeShutdownHook(hookThread); ledger.close(); log("shutting down"); network.shutdown(); clientHTTPServer.shutdown(); } catch (Exception e) { } synchronized (parser) { parser.notifyAll(); } try { logger.close(); } catch (Exception e) { e.printStackTrace(); } } }
Main { public void shutdown() { try { if (hookThread != null) Runtime.getRuntime().removeShutdownHook(hookThread); ledger.close(); log("shutting down"); network.shutdown(); clientHTTPServer.shutdown(); } catch (Exception e) { } synchronized (parser) { parser.notifyAll(); } try { logger.close(); } catch (Exception e) { e.printStackTrace(); } } Main(String[] args); }
Main { public void shutdown() { try { if (hookThread != null) Runtime.getRuntime().removeShutdownHook(hookThread); ledger.close(); log("shutting down"); network.shutdown(); clientHTTPServer.shutdown(); } catch (Exception e) { } synchronized (parser) { parser.notifyAll(); } try { logger.close(); } catch (Exception e) { e.printStackTrace(); } } Main(String[] args); static void main(String[] args); void waitReady(); void shutdown(); void setVerboseLevel(int level); void setUDPVerboseLevel(int level); void restartUDPAdapter(); PublicKey getNodePublicKey(); }
Main { public void shutdown() { try { if (hookThread != null) Runtime.getRuntime().removeShutdownHook(hookThread); ledger.close(); log("shutting down"); network.shutdown(); clientHTTPServer.shutdown(); } catch (Exception e) { } synchronized (parser) { parser.notifyAll(); } try { logger.close(); } catch (Exception e) { e.printStackTrace(); } } Main(String[] args); static void main(String[] args); void waitReady(); void shutdown(); void setVerboseLevel(int level); void setUDPVerboseLevel(int level); void restartUDPAdapter(); PublicKey getNodePublicKey(); static final String NODE_VERSION; final Reporter reporter; final BufferedLogger logger; public NetConfig netConfig; public NetworkV2 network; final Config config; public NodeInfo myInfo; public Node node; public ItemCache cache; public ParcelCache parcelCache; public PaidOperationCache paidOperationCache; }
@Test public void getDigestByName() throws Exception { Digest dNoDigest1 = RSAOAEPDigestFactory.getDigestByName(""); assertNull(dNoDigest1); Digest dNoDigest2 = RSAOAEPDigestFactory.getDigestByName("Missing hash"); assertNull(dNoDigest2); Digest dSHA1 = RSAOAEPDigestFactory.getDigestByName("SHA-1"); assertArrayEquals( resetAndDigest(dSHA1, "".getBytes()), Hex.decode("da39a3ee5e6b4b0d3255bfef95601890afd80709")); assertArrayEquals( resetAndDigest(dSHA1, "The quick brown fox jumps over the lazy dog".getBytes()), Hex.decode("2fd4e1c67a2d28fced849ee1bb76e7391b93eb12")); Digest dSHA224 = RSAOAEPDigestFactory.getDigestByName("SHA-224"); assertArrayEquals( resetAndDigest(dSHA224, "".getBytes()), Hex.decode("d14a028c2a3a2bc9476102bb288234c415a2b01f828ea62ac5b3e42f")); assertArrayEquals( resetAndDigest(dSHA224, "The quick brown fox jumps over the lazy dog".getBytes()), Hex.decode("730e109bd7a8a32b1cb9d9a09aa2325d2430587ddbc0c38bad911525")); Digest dSHA256 = RSAOAEPDigestFactory.getDigestByName("SHA-256"); assertArrayEquals( resetAndDigest(dSHA256, "".getBytes()), Hex.decode("e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855")); assertArrayEquals( resetAndDigest(dSHA256, "The quick brown fox jumps over the lazy dog".getBytes()), Hex.decode("d7a8fbb307d7809469ca9abcb0082e4f8d5651e46d3cdb762d02d0bf37c9e592")); Digest dSHA384 = RSAOAEPDigestFactory.getDigestByName("SHA-384"); assertArrayEquals( resetAndDigest(dSHA384, "".getBytes()), Hex.decode("38b060a751ac96384cd9327eb1b1e36a21fdb71114be07434c0cc7bf63f6e1da274edebfe76f65fbd51ad2f14898b95b")); assertArrayEquals( resetAndDigest(dSHA384, "The quick brown fox jumps over the lazy dog".getBytes()), Hex.decode("ca737f1014a48f4c0b6dd43cb177b0afd9e5169367544c494011e3317dbf9a509cb1e5dc1e85a941bbee3d7f2afbc9b1")); Digest dSHA512 = RSAOAEPDigestFactory.getDigestByName("SHA-512"); assertArrayEquals( resetAndDigest(dSHA512, "".getBytes()), Hex.decode("cf83e1357eefb8bdf1542850d66d8007d620e4050b5715dc83f4a921d36ce9ce47d0d13c5d85f2b0ff8318d2877eec2f63b931bd47417a81a538327af927da3e")); assertArrayEquals( resetAndDigest(dSHA512, "The quick brown fox jumps over the lazy dog".getBytes()), Hex.decode("07e547d9586f6a73f73fbac0435ed76951218fb7d0c8d788a309d785436bbb642e93a252a954f23912547d1e8a3b5ed6e1bfd7097821233fa0538f3db854fee6")); }
@Nullable public static Digest getDigestByName(String digestName) { Class digestClass = (Class) supportedDigestAlgorithmClassesByName.get(digestName); if (digestClass == null) { return null; } else { try { return (Digest) (digestClass.newInstance()); } catch (InstantiationException | IllegalAccessException e) { return null; } } }
RSAOAEPDigestFactory { @Nullable public static Digest getDigestByName(String digestName) { Class digestClass = (Class) supportedDigestAlgorithmClassesByName.get(digestName); if (digestClass == null) { return null; } else { try { return (Digest) (digestClass.newInstance()); } catch (InstantiationException | IllegalAccessException e) { return null; } } } }
RSAOAEPDigestFactory { @Nullable public static Digest getDigestByName(String digestName) { Class digestClass = (Class) supportedDigestAlgorithmClassesByName.get(digestName); if (digestClass == null) { return null; } else { try { return (Digest) (digestClass.newInstance()); } catch (InstantiationException | IllegalAccessException e) { return null; } } } }
RSAOAEPDigestFactory { @Nullable public static Digest getDigestByName(String digestName) { Class digestClass = (Class) supportedDigestAlgorithmClassesByName.get(digestName); if (digestClass == null) { return null; } else { try { return (Digest) (digestClass.newInstance()); } catch (InstantiationException | IllegalAccessException e) { return null; } } } @Nullable static Digest getDigestByName(String digestName); static Digest cloneDigest(Digest digest); }
RSAOAEPDigestFactory { @Nullable public static Digest getDigestByName(String digestName) { Class digestClass = (Class) supportedDigestAlgorithmClassesByName.get(digestName); if (digestClass == null) { return null; } else { try { return (Digest) (digestClass.newInstance()); } catch (InstantiationException | IllegalAccessException e) { return null; } } } @Nullable static Digest getDigestByName(String digestName); static Digest cloneDigest(Digest digest); }
@Test public void testMintableTokenContractApi() throws Exception { List<Main> mm = new ArrayList<>(); for (int i = 0; i < 4; i++) mm.add(createMain("node" + (i + 1), false)); Main main = mm.get(0); main.config.setIsFreeRegistrationsAllowedFromYaml(true); Client client = new Client(TestKeys.privateKey(20), main.myInfo, null); Set<PrivateKey> issuerPrivateKeys = new HashSet<>(asList(TestKeys.privateKey(1))); Set<PublicKey> issuerPublicKeys = new HashSet<>(asList(TestKeys.publicKey(1))); Set<PublicKey> ownerPublicKeys = new HashSet<>(asList(TestKeys.publicKey(2))); Contract mintableTokenContract = ContractsService.createTokenContractWithEmission(issuerPrivateKeys, ownerPublicKeys, new BigDecimal("300000000000")); mintableTokenContract.check(); mintableTokenContract.traceErrors(); ItemResult itemResult = client.register(mintableTokenContract.getPackedTransaction(), 5000); System.out.println("mintableTokenContract : " + itemResult); assertEquals(ItemState.APPROVED, itemResult.state); Contract emittedContract = ContractsService.createTokenEmission(mintableTokenContract, new BigDecimal("100000000000"), issuerPrivateKeys); emittedContract.check(); emittedContract.traceErrors(); assertEquals(emittedContract.getPermissions().get("split_join").size(), 1); Binder splitJoinParams = emittedContract.getPermissions().get("split_join").iterator().next().getParams(); assertEquals(splitJoinParams.get("min_value"), "0.01"); assertEquals(splitJoinParams.get("min_unit"), "0.01"); assertEquals(splitJoinParams.get("field_name"), "amount"); assertTrue(splitJoinParams.get("join_match_fields") instanceof List); assertEquals(((List) splitJoinParams.get("join_match_fields")).get(0), "state.origin"); assertTrue(emittedContract.isPermitted("revoke", ownerPublicKeys)); assertTrue(emittedContract.isPermitted("revoke", issuerPublicKeys)); assertTrue(emittedContract.isPermitted("change_owner", ownerPublicKeys)); assertFalse(emittedContract.isPermitted("change_owner", issuerPublicKeys)); assertTrue(emittedContract.isPermitted("split_join", ownerPublicKeys)); assertFalse(emittedContract.isPermitted("split_join", issuerPublicKeys)); itemResult = client.register(emittedContract.getPackedTransaction(), 5000); System.out.println("emittedContract : " + itemResult); assertEquals(ItemState.APPROVED, itemResult.state); assertEquals(emittedContract.getStateData().getString("amount"), "400000000000"); assertEquals(ItemState.REVOKED, main.node.waitItem(mintableTokenContract.getId(), 8000).state); mm.forEach(x -> x.shutdown()); }
public void shutdown() { try { if (hookThread != null) Runtime.getRuntime().removeShutdownHook(hookThread); ledger.close(); log("shutting down"); network.shutdown(); clientHTTPServer.shutdown(); } catch (Exception e) { } synchronized (parser) { parser.notifyAll(); } try { logger.close(); } catch (Exception e) { e.printStackTrace(); } }
Main { public void shutdown() { try { if (hookThread != null) Runtime.getRuntime().removeShutdownHook(hookThread); ledger.close(); log("shutting down"); network.shutdown(); clientHTTPServer.shutdown(); } catch (Exception e) { } synchronized (parser) { parser.notifyAll(); } try { logger.close(); } catch (Exception e) { e.printStackTrace(); } } }
Main { public void shutdown() { try { if (hookThread != null) Runtime.getRuntime().removeShutdownHook(hookThread); ledger.close(); log("shutting down"); network.shutdown(); clientHTTPServer.shutdown(); } catch (Exception e) { } synchronized (parser) { parser.notifyAll(); } try { logger.close(); } catch (Exception e) { e.printStackTrace(); } } Main(String[] args); }
Main { public void shutdown() { try { if (hookThread != null) Runtime.getRuntime().removeShutdownHook(hookThread); ledger.close(); log("shutting down"); network.shutdown(); clientHTTPServer.shutdown(); } catch (Exception e) { } synchronized (parser) { parser.notifyAll(); } try { logger.close(); } catch (Exception e) { e.printStackTrace(); } } Main(String[] args); static void main(String[] args); void waitReady(); void shutdown(); void setVerboseLevel(int level); void setUDPVerboseLevel(int level); void restartUDPAdapter(); PublicKey getNodePublicKey(); }
Main { public void shutdown() { try { if (hookThread != null) Runtime.getRuntime().removeShutdownHook(hookThread); ledger.close(); log("shutting down"); network.shutdown(); clientHTTPServer.shutdown(); } catch (Exception e) { } synchronized (parser) { parser.notifyAll(); } try { logger.close(); } catch (Exception e) { e.printStackTrace(); } } Main(String[] args); static void main(String[] args); void waitReady(); void shutdown(); void setVerboseLevel(int level); void setUDPVerboseLevel(int level); void restartUDPAdapter(); PublicKey getNodePublicKey(); static final String NODE_VERSION; final Reporter reporter; final BufferedLogger logger; public NetConfig netConfig; public NetworkV2 network; final Config config; public NodeInfo myInfo; public Node node; public ItemCache cache; public ParcelCache parcelCache; public PaidOperationCache paidOperationCache; }
@Test public void testSplitAndJoinApi() throws Exception { List<Main> mm = new ArrayList<>(); for (int i = 0; i < 4; i++) mm.add(createMain("node" + (i + 1), false)); Main main = mm.get(0); main.config.setIsFreeRegistrationsAllowedFromYaml(true); Client client = new Client(TestKeys.privateKey(20), main.myInfo, null); Set<PrivateKey> issuerPrivateKeys = new HashSet<>(asList(TestKeys.privateKey(1))); Set<PublicKey> ownerPublicKeys = new HashSet<>(asList(TestKeys.publicKey(2))); Set<PrivateKey> issuerPrivateKeys2 = new HashSet<>(asList(TestKeys.privateKey(2))); Contract contractC = ContractsService.createTokenContract(issuerPrivateKeys, ownerPublicKeys, new BigDecimal("100")); contractC.check(); contractC.traceErrors(); ItemResult itemResult = client.register(contractC.getPackedTransaction(), 5000); System.out.println("contractC : " + itemResult); assertEquals(ItemState.APPROVED, itemResult.state); Contract сontractA = ContractsService.createSplit(contractC, new BigDecimal("30"), "amount", issuerPrivateKeys2, true); Contract contractB = сontractA.getNew().get(0); assertEquals("70", сontractA.getStateData().get("amount").toString()); assertEquals("30", contractB.getStateData().get("amount").toString()); itemResult = client.register(сontractA.getPackedTransaction(), 5000); System.out.println("сontractA : " + itemResult); assertEquals(ItemState.APPROVED, itemResult.state); assertEquals("70", сontractA.getStateData().get("amount").toString()); assertEquals("30", contractB.getStateData().get("amount").toString()); assertEquals(ItemState.REVOKED, main.node.waitItem(contractC.getId(), 5000).state); assertEquals(ItemState.APPROVED, main.node.waitItem(сontractA.getId(), 5000).state); assertEquals(ItemState.APPROVED, main.node.waitItem(contractB.getId(), 5000).state); Contract contractC2 = ContractsService.createJoin(сontractA, contractB, "amount", issuerPrivateKeys2); contractC2.check(); contractC2.traceErrors(); assertTrue(contractC2.isOk()); itemResult = client.register(contractC2.getPackedTransaction(), 5000); System.out.println("contractC2 : " + itemResult); assertEquals(ItemState.APPROVED, itemResult.state); assertEquals(new Decimal(100), contractC2.getStateData().get("amount")); assertEquals(ItemState.REVOKED, main.node.waitItem(contractC.getId(), 5000).state); assertEquals(ItemState.REVOKED, main.node.waitItem(сontractA.getId(), 5000).state); assertEquals(ItemState.REVOKED, main.node.waitItem(contractB.getId(), 5000).state); assertEquals(ItemState.APPROVED, main.node.waitItem(contractC2.getId(), 5000).state); mm.forEach(x -> x.shutdown()); }
public void shutdown() { try { if (hookThread != null) Runtime.getRuntime().removeShutdownHook(hookThread); ledger.close(); log("shutting down"); network.shutdown(); clientHTTPServer.shutdown(); } catch (Exception e) { } synchronized (parser) { parser.notifyAll(); } try { logger.close(); } catch (Exception e) { e.printStackTrace(); } }
Main { public void shutdown() { try { if (hookThread != null) Runtime.getRuntime().removeShutdownHook(hookThread); ledger.close(); log("shutting down"); network.shutdown(); clientHTTPServer.shutdown(); } catch (Exception e) { } synchronized (parser) { parser.notifyAll(); } try { logger.close(); } catch (Exception e) { e.printStackTrace(); } } }
Main { public void shutdown() { try { if (hookThread != null) Runtime.getRuntime().removeShutdownHook(hookThread); ledger.close(); log("shutting down"); network.shutdown(); clientHTTPServer.shutdown(); } catch (Exception e) { } synchronized (parser) { parser.notifyAll(); } try { logger.close(); } catch (Exception e) { e.printStackTrace(); } } Main(String[] args); }
Main { public void shutdown() { try { if (hookThread != null) Runtime.getRuntime().removeShutdownHook(hookThread); ledger.close(); log("shutting down"); network.shutdown(); clientHTTPServer.shutdown(); } catch (Exception e) { } synchronized (parser) { parser.notifyAll(); } try { logger.close(); } catch (Exception e) { e.printStackTrace(); } } Main(String[] args); static void main(String[] args); void waitReady(); void shutdown(); void setVerboseLevel(int level); void setUDPVerboseLevel(int level); void restartUDPAdapter(); PublicKey getNodePublicKey(); }
Main { public void shutdown() { try { if (hookThread != null) Runtime.getRuntime().removeShutdownHook(hookThread); ledger.close(); log("shutting down"); network.shutdown(); clientHTTPServer.shutdown(); } catch (Exception e) { } synchronized (parser) { parser.notifyAll(); } try { logger.close(); } catch (Exception e) { e.printStackTrace(); } } Main(String[] args); static void main(String[] args); void waitReady(); void shutdown(); void setVerboseLevel(int level); void setUDPVerboseLevel(int level); void restartUDPAdapter(); PublicKey getNodePublicKey(); static final String NODE_VERSION; final Reporter reporter; final BufferedLogger logger; public NetConfig netConfig; public NetworkV2 network; final Config config; public NodeInfo myInfo; public Node node; public ItemCache cache; public ParcelCache parcelCache; public PaidOperationCache paidOperationCache; }
@Test public void testShareContractApi() throws Exception { List<Main> mm = new ArrayList<>(); for (int i = 0; i < 4; i++) mm.add(createMain("node" + (i + 1), false)); Main main = mm.get(0); main.config.setIsFreeRegistrationsAllowedFromYaml(true); Client client = new Client(TestKeys.privateKey(20), main.myInfo, null); Set<PrivateKey> issuerPrivateKeys = new HashSet<>(asList(TestKeys.privateKey(1))); Set<PublicKey> issuerPublicKeys = new HashSet<>(asList(TestKeys.publicKey(1))); Set<PublicKey> ownerPublicKeys = new HashSet<>(asList(TestKeys.publicKey(2))); Contract shareContract = ContractsService.createShareContract(issuerPrivateKeys, ownerPublicKeys, new BigDecimal("100")); shareContract.check(); shareContract.traceErrors(); assertTrue(shareContract.getOwner().isAllowedForKeys(ownerPublicKeys)); assertTrue(shareContract.getIssuer().isAllowedForKeys(issuerPrivateKeys)); assertTrue(shareContract.getCreator().isAllowedForKeys(issuerPrivateKeys)); assertFalse(shareContract.getOwner().isAllowedForKeys(issuerPrivateKeys)); assertFalse(shareContract.getIssuer().isAllowedForKeys(ownerPublicKeys)); assertFalse(shareContract.getCreator().isAllowedForKeys(ownerPublicKeys)); assertTrue(shareContract.getExpiresAt().isAfter(ZonedDateTime.now().plusMonths(3))); assertTrue(shareContract.getCreatedAt().isBefore(ZonedDateTime.now())); assertEquals(InnerContractsService.getDecimalField(shareContract, "amount"), new Decimal(100)); assertEquals(shareContract.getPermissions().get("split_join").size(), 1); Binder splitJoinParams = shareContract.getPermissions().get("split_join").iterator().next().getParams(); assertEquals(splitJoinParams.get("min_value"), 1); assertEquals(splitJoinParams.get("min_unit"), 1); assertEquals(splitJoinParams.get("field_name"), "amount"); assertTrue(splitJoinParams.get("join_match_fields") instanceof List); assertEquals(((List) splitJoinParams.get("join_match_fields")).get(0), "state.origin"); assertTrue(shareContract.isPermitted("revoke", ownerPublicKeys)); assertTrue(shareContract.isPermitted("revoke", issuerPublicKeys)); assertTrue(shareContract.isPermitted("change_owner", ownerPublicKeys)); assertFalse(shareContract.isPermitted("change_owner", issuerPublicKeys)); assertTrue(shareContract.isPermitted("split_join", ownerPublicKeys)); assertFalse(shareContract.isPermitted("split_join", issuerPublicKeys)); ItemResult itemResult = client.register(shareContract.getPackedTransaction(), 5000); System.out.println("shareContract : " + itemResult); assertEquals(ItemState.APPROVED, itemResult.state); mm.forEach(x -> x.shutdown()); }
public void shutdown() { try { if (hookThread != null) Runtime.getRuntime().removeShutdownHook(hookThread); ledger.close(); log("shutting down"); network.shutdown(); clientHTTPServer.shutdown(); } catch (Exception e) { } synchronized (parser) { parser.notifyAll(); } try { logger.close(); } catch (Exception e) { e.printStackTrace(); } }
Main { public void shutdown() { try { if (hookThread != null) Runtime.getRuntime().removeShutdownHook(hookThread); ledger.close(); log("shutting down"); network.shutdown(); clientHTTPServer.shutdown(); } catch (Exception e) { } synchronized (parser) { parser.notifyAll(); } try { logger.close(); } catch (Exception e) { e.printStackTrace(); } } }
Main { public void shutdown() { try { if (hookThread != null) Runtime.getRuntime().removeShutdownHook(hookThread); ledger.close(); log("shutting down"); network.shutdown(); clientHTTPServer.shutdown(); } catch (Exception e) { } synchronized (parser) { parser.notifyAll(); } try { logger.close(); } catch (Exception e) { e.printStackTrace(); } } Main(String[] args); }
Main { public void shutdown() { try { if (hookThread != null) Runtime.getRuntime().removeShutdownHook(hookThread); ledger.close(); log("shutting down"); network.shutdown(); clientHTTPServer.shutdown(); } catch (Exception e) { } synchronized (parser) { parser.notifyAll(); } try { logger.close(); } catch (Exception e) { e.printStackTrace(); } } Main(String[] args); static void main(String[] args); void waitReady(); void shutdown(); void setVerboseLevel(int level); void setUDPVerboseLevel(int level); void restartUDPAdapter(); PublicKey getNodePublicKey(); }
Main { public void shutdown() { try { if (hookThread != null) Runtime.getRuntime().removeShutdownHook(hookThread); ledger.close(); log("shutting down"); network.shutdown(); clientHTTPServer.shutdown(); } catch (Exception e) { } synchronized (parser) { parser.notifyAll(); } try { logger.close(); } catch (Exception e) { e.printStackTrace(); } } Main(String[] args); static void main(String[] args); void waitReady(); void shutdown(); void setVerboseLevel(int level); void setUDPVerboseLevel(int level); void restartUDPAdapter(); PublicKey getNodePublicKey(); static final String NODE_VERSION; final Reporter reporter; final BufferedLogger logger; public NetConfig netConfig; public NetworkV2 network; final Config config; public NodeInfo myInfo; public Node node; public ItemCache cache; public ParcelCache parcelCache; public PaidOperationCache paidOperationCache; }
@Test public void testNotaryContractApi() throws Exception { List<Main> mm = new ArrayList<>(); for (int i = 0; i < 4; i++) mm.add(createMain("node" + (i + 1), false)); Main main = mm.get(0); main.config.setIsFreeRegistrationsAllowedFromYaml(true); Client client = new Client(TestKeys.privateKey(20), main.myInfo, null); Set<PrivateKey> issuerPrivateKeys = new HashSet<>(asList(TestKeys.privateKey(1))); Set<PublicKey> issuerPublicKeys = new HashSet<>(asList(TestKeys.publicKey(1))); Set<PublicKey> ownerPublicKeys = new HashSet<>(asList(TestKeys.publicKey(2))); Contract notaryContract = ContractsService.createNotaryContract(issuerPrivateKeys, ownerPublicKeys); notaryContract.check(); notaryContract.traceErrors(); assertTrue(notaryContract.getOwner().isAllowedForKeys(ownerPublicKeys)); assertTrue(notaryContract.getIssuer().isAllowedForKeys(issuerPrivateKeys)); assertTrue(notaryContract.getCreator().isAllowedForKeys(issuerPrivateKeys)); assertFalse(notaryContract.getOwner().isAllowedForKeys(issuerPrivateKeys)); assertFalse(notaryContract.getIssuer().isAllowedForKeys(ownerPublicKeys)); assertFalse(notaryContract.getCreator().isAllowedForKeys(ownerPublicKeys)); assertTrue(notaryContract.getExpiresAt().isAfter(ZonedDateTime.now().plusMonths(3))); assertTrue(notaryContract.getCreatedAt().isBefore(ZonedDateTime.now())); assertTrue(notaryContract.isPermitted("revoke", ownerPublicKeys)); assertTrue(notaryContract.isPermitted("revoke", issuerPublicKeys)); assertTrue(notaryContract.isPermitted("change_owner", ownerPublicKeys)); assertFalse(notaryContract.isPermitted("change_owner", issuerPublicKeys)); ItemResult itemResult = client.register(notaryContract.getPackedTransaction(), 5000); System.out.println("notaryContract : " + itemResult); assertEquals(ItemState.APPROVED, itemResult.state); mm.forEach(x -> x.shutdown()); }
public void shutdown() { try { if (hookThread != null) Runtime.getRuntime().removeShutdownHook(hookThread); ledger.close(); log("shutting down"); network.shutdown(); clientHTTPServer.shutdown(); } catch (Exception e) { } synchronized (parser) { parser.notifyAll(); } try { logger.close(); } catch (Exception e) { e.printStackTrace(); } }
Main { public void shutdown() { try { if (hookThread != null) Runtime.getRuntime().removeShutdownHook(hookThread); ledger.close(); log("shutting down"); network.shutdown(); clientHTTPServer.shutdown(); } catch (Exception e) { } synchronized (parser) { parser.notifyAll(); } try { logger.close(); } catch (Exception e) { e.printStackTrace(); } } }
Main { public void shutdown() { try { if (hookThread != null) Runtime.getRuntime().removeShutdownHook(hookThread); ledger.close(); log("shutting down"); network.shutdown(); clientHTTPServer.shutdown(); } catch (Exception e) { } synchronized (parser) { parser.notifyAll(); } try { logger.close(); } catch (Exception e) { e.printStackTrace(); } } Main(String[] args); }
Main { public void shutdown() { try { if (hookThread != null) Runtime.getRuntime().removeShutdownHook(hookThread); ledger.close(); log("shutting down"); network.shutdown(); clientHTTPServer.shutdown(); } catch (Exception e) { } synchronized (parser) { parser.notifyAll(); } try { logger.close(); } catch (Exception e) { e.printStackTrace(); } } Main(String[] args); static void main(String[] args); void waitReady(); void shutdown(); void setVerboseLevel(int level); void setUDPVerboseLevel(int level); void restartUDPAdapter(); PublicKey getNodePublicKey(); }
Main { public void shutdown() { try { if (hookThread != null) Runtime.getRuntime().removeShutdownHook(hookThread); ledger.close(); log("shutting down"); network.shutdown(); clientHTTPServer.shutdown(); } catch (Exception e) { } synchronized (parser) { parser.notifyAll(); } try { logger.close(); } catch (Exception e) { e.printStackTrace(); } } Main(String[] args); static void main(String[] args); void waitReady(); void shutdown(); void setVerboseLevel(int level); void setUDPVerboseLevel(int level); void restartUDPAdapter(); PublicKey getNodePublicKey(); static final String NODE_VERSION; final Reporter reporter; final BufferedLogger logger; public NetConfig netConfig; public NetworkV2 network; final Config config; public NodeInfo myInfo; public Node node; public ItemCache cache; public ParcelCache parcelCache; public PaidOperationCache paidOperationCache; }
@Test public void testTwoSignedContractApi() throws Exception { List<Main> mm = new ArrayList<>(); for (int i = 0; i < 4; i++) mm.add(createMain("node" + (i + 1), false)); Main main = mm.get(0); main.config.setIsFreeRegistrationsAllowedFromYaml(true); Client client = new Client(TestKeys.privateKey(20), main.myInfo, null); Set<PrivateKey> martyPrivateKeys = new HashSet<>(asList(TestKeys.privateKey(1))); Set<PrivateKey> stepaPrivateKeys = new HashSet<>(asList(TestKeys.privateKey(2))); Set<PublicKey> stepaPublicKeys = new HashSet<>(asList(TestKeys.publicKey(2))); Contract baseContract = Contract.fromDslFile(ROOT_PATH + "DeLoreanOwnership.yml"); PrivateKey manufacturePrivateKey = new PrivateKey(Do.read(ROOT_PATH + "_xer0yfe2nn1xthc.private.unikey")); baseContract.addSignerKey(manufacturePrivateKey); baseContract.seal(); baseContract.check(); baseContract.traceErrors(); Contract twoSignContract = ContractsService.createTwoSignedContract(baseContract, martyPrivateKeys, stepaPublicKeys, false); twoSignContract = Contract.fromPackedTransaction(twoSignContract.getPackedTransaction()); twoSignContract.addSignatureToSeal(stepaPrivateKeys); twoSignContract.check(); twoSignContract.traceErrors(); ItemResult itemResult = client.register(twoSignContract.getPackedTransaction(), 5000); System.out.println("twoSignContract : " + itemResult); assertEquals(ItemState.DECLINED, itemResult.state); twoSignContract = Contract.fromPackedTransaction(twoSignContract.getPackedTransaction()); twoSignContract.addSignatureToSeal(martyPrivateKeys); twoSignContract.check(); twoSignContract.traceErrors(); System.out.println("Contract with two signature is valid: " + twoSignContract.isOk()); itemResult = client.register(twoSignContract.getPackedTransaction(), 5000); System.out.println("twoSignContract : " + itemResult); assertEquals(ItemState.APPROVED, itemResult.state); mm.forEach(x -> x.shutdown()); }
public void shutdown() { try { if (hookThread != null) Runtime.getRuntime().removeShutdownHook(hookThread); ledger.close(); log("shutting down"); network.shutdown(); clientHTTPServer.shutdown(); } catch (Exception e) { } synchronized (parser) { parser.notifyAll(); } try { logger.close(); } catch (Exception e) { e.printStackTrace(); } }
Main { public void shutdown() { try { if (hookThread != null) Runtime.getRuntime().removeShutdownHook(hookThread); ledger.close(); log("shutting down"); network.shutdown(); clientHTTPServer.shutdown(); } catch (Exception e) { } synchronized (parser) { parser.notifyAll(); } try { logger.close(); } catch (Exception e) { e.printStackTrace(); } } }
Main { public void shutdown() { try { if (hookThread != null) Runtime.getRuntime().removeShutdownHook(hookThread); ledger.close(); log("shutting down"); network.shutdown(); clientHTTPServer.shutdown(); } catch (Exception e) { } synchronized (parser) { parser.notifyAll(); } try { logger.close(); } catch (Exception e) { e.printStackTrace(); } } Main(String[] args); }
Main { public void shutdown() { try { if (hookThread != null) Runtime.getRuntime().removeShutdownHook(hookThread); ledger.close(); log("shutting down"); network.shutdown(); clientHTTPServer.shutdown(); } catch (Exception e) { } synchronized (parser) { parser.notifyAll(); } try { logger.close(); } catch (Exception e) { e.printStackTrace(); } } Main(String[] args); static void main(String[] args); void waitReady(); void shutdown(); void setVerboseLevel(int level); void setUDPVerboseLevel(int level); void restartUDPAdapter(); PublicKey getNodePublicKey(); }
Main { public void shutdown() { try { if (hookThread != null) Runtime.getRuntime().removeShutdownHook(hookThread); ledger.close(); log("shutting down"); network.shutdown(); clientHTTPServer.shutdown(); } catch (Exception e) { } synchronized (parser) { parser.notifyAll(); } try { logger.close(); } catch (Exception e) { e.printStackTrace(); } } Main(String[] args); static void main(String[] args); void waitReady(); void shutdown(); void setVerboseLevel(int level); void setUDPVerboseLevel(int level); void restartUDPAdapter(); PublicKey getNodePublicKey(); static final String NODE_VERSION; final Reporter reporter; final BufferedLogger logger; public NetConfig netConfig; public NetworkV2 network; final Config config; public NodeInfo myInfo; public Node node; public ItemCache cache; public ParcelCache parcelCache; public PaidOperationCache paidOperationCache; }
@Test public void testRevocationContractsApi() throws Exception { List<Main> mm = new ArrayList<>(); for (int i = 0; i < 4; i++) mm.add(createMain("node" + (i + 1), false)); Main main = mm.get(0); main.config.setIsFreeRegistrationsAllowedFromYaml(true); Client client = new Client(TestKeys.privateKey(20), main.myInfo, null); Set<PrivateKey> issuerPrivateKeys = new HashSet<>(asList(TestKeys.privateKey(1))); Set<PublicKey> ownerPublicKeys = new HashSet<>(asList(TestKeys.publicKey(2))); Contract sourceContract = ContractsService.createShareContract(issuerPrivateKeys, ownerPublicKeys, new BigDecimal("100")); sourceContract.check(); sourceContract.traceErrors(); ItemResult itemResult = client.register(sourceContract.getPackedTransaction(), 5000); System.out.println("sourceContract : " + itemResult); assertEquals(ItemState.APPROVED, client.getState(sourceContract.getId()).state); Contract revokeContract = ContractsService.createRevocation(sourceContract, TestKeys.privateKey(1)); revokeContract.check(); revokeContract.traceErrors(); itemResult = client.register(revokeContract.getPackedTransaction(), 5000); System.out.println("revokeContract : " + itemResult); assertEquals(ItemState.APPROVED, client.getState(revokeContract.getId()).state); assertEquals(ItemState.REVOKED, client.getState(sourceContract.getId()).state); mm.forEach(x -> x.shutdown()); }
public void shutdown() { try { if (hookThread != null) Runtime.getRuntime().removeShutdownHook(hookThread); ledger.close(); log("shutting down"); network.shutdown(); clientHTTPServer.shutdown(); } catch (Exception e) { } synchronized (parser) { parser.notifyAll(); } try { logger.close(); } catch (Exception e) { e.printStackTrace(); } }
Main { public void shutdown() { try { if (hookThread != null) Runtime.getRuntime().removeShutdownHook(hookThread); ledger.close(); log("shutting down"); network.shutdown(); clientHTTPServer.shutdown(); } catch (Exception e) { } synchronized (parser) { parser.notifyAll(); } try { logger.close(); } catch (Exception e) { e.printStackTrace(); } } }
Main { public void shutdown() { try { if (hookThread != null) Runtime.getRuntime().removeShutdownHook(hookThread); ledger.close(); log("shutting down"); network.shutdown(); clientHTTPServer.shutdown(); } catch (Exception e) { } synchronized (parser) { parser.notifyAll(); } try { logger.close(); } catch (Exception e) { e.printStackTrace(); } } Main(String[] args); }
Main { public void shutdown() { try { if (hookThread != null) Runtime.getRuntime().removeShutdownHook(hookThread); ledger.close(); log("shutting down"); network.shutdown(); clientHTTPServer.shutdown(); } catch (Exception e) { } synchronized (parser) { parser.notifyAll(); } try { logger.close(); } catch (Exception e) { e.printStackTrace(); } } Main(String[] args); static void main(String[] args); void waitReady(); void shutdown(); void setVerboseLevel(int level); void setUDPVerboseLevel(int level); void restartUDPAdapter(); PublicKey getNodePublicKey(); }
Main { public void shutdown() { try { if (hookThread != null) Runtime.getRuntime().removeShutdownHook(hookThread); ledger.close(); log("shutting down"); network.shutdown(); clientHTTPServer.shutdown(); } catch (Exception e) { } synchronized (parser) { parser.notifyAll(); } try { logger.close(); } catch (Exception e) { e.printStackTrace(); } } Main(String[] args); static void main(String[] args); void waitReady(); void shutdown(); void setVerboseLevel(int level); void setUDPVerboseLevel(int level); void restartUDPAdapter(); PublicKey getNodePublicKey(); static final String NODE_VERSION; final Reporter reporter; final BufferedLogger logger; public NetConfig netConfig; public NetworkV2 network; final Config config; public NodeInfo myInfo; public Node node; public ItemCache cache; public ParcelCache parcelCache; public PaidOperationCache paidOperationCache; }
@Test public void testSwapContractsApi() throws Exception { List<Main> mm = new ArrayList<>(); for (int i = 0; i < 4; i++) mm.add(createMain("node" + (i + 1), false)); Main main = mm.get(0); main.config.setIsFreeRegistrationsAllowedFromYaml(true); Client client = new Client(TestKeys.privateKey(20), main.myInfo, null); Set<PrivateKey> martyPrivateKeys = new HashSet<>(asList(TestKeys.privateKey(1))); Set<PrivateKey> stepaPrivateKeys = new HashSet<>(asList(TestKeys.privateKey(2))); Set<PublicKey> martyPublicKeys = new HashSet<>(asList(TestKeys.publicKey(1))); Set<PublicKey> stepaPublicKeys = new HashSet<>(asList(TestKeys.publicKey(2))); Contract delorean = ContractsService.createTokenContract(martyPrivateKeys, martyPublicKeys, new BigDecimal("100"), new BigDecimal("0.0001")); delorean.seal(); delorean.check(); delorean.traceErrors(); ItemResult itemResult = client.register(delorean.getPackedTransaction(), 5000); assertEquals(ItemState.APPROVED, itemResult.state); Contract lamborghini = ContractsService.createTokenContract(stepaPrivateKeys, stepaPublicKeys, new BigDecimal("100"), new BigDecimal("0.0001")); lamborghini.seal(); lamborghini.check(); lamborghini.traceErrors(); itemResult = client.register(lamborghini.getPackedTransaction(), 5000); assertEquals(ItemState.APPROVED, itemResult.state); System.out.println("--- register swapped contracts using ContractsService ---"); Contract swapContract; swapContract = ContractsService.startSwap(delorean, lamborghini, martyPrivateKeys, stepaPublicKeys); swapContract = Contract.fromPackedTransaction(swapContract.getPackedTransaction()); ContractsService.signPresentedSwap(swapContract, stepaPrivateKeys); swapContract = Contract.fromPackedTransaction(swapContract.getPackedTransaction()); ContractsService.finishSwap(swapContract, martyPrivateKeys); swapContract.check(); swapContract.traceErrors(); System.out.println("Transaction contract for swapping is valid: " + swapContract.isOk()); itemResult = client.register(swapContract.getPackedTransaction(), 10000); assertEquals(ItemState.APPROVED, itemResult.state); System.out.println("--- check old revisions for ownership contracts ---"); ItemResult deloreanResult = main.node.waitItem(delorean.getId(), 5000); System.out.println("DeLorean revoked ownership contract revision " + delorean.getRevision() + " is " + deloreanResult + " by Network"); System.out.println("DeLorean revoked ownership was belongs to Marty: " + delorean.getOwner().isAllowedForKeys(martyPublicKeys)); assertEquals(ItemState.REVOKED, deloreanResult.state); ItemResult lamborghiniResult = main.node.waitItem(lamborghini.getId(), 5000); System.out.println("Lamborghini revoked ownership contract revision " + lamborghini.getRevision() + " is " + lamborghiniResult + " by Network"); System.out.println("Lamborghini revoked ownership was belongs to Stepa: " + lamborghini.getOwner().isAllowedForKeys(stepaPublicKeys)); assertEquals(ItemState.REVOKED, lamborghiniResult.state); System.out.println("--- check new revisions for ownership contracts ---"); Contract newDelorean = null; Contract newLamborghini = null; for (Contract c : swapContract.getNew()) { if (c.getParent().equals(delorean.getId())) { newDelorean = c; } if (c.getParent().equals(lamborghini.getId())) { newLamborghini = c; } } deloreanResult = main.node.waitItem(newDelorean.getId(), 5000); System.out.println("DeLorean ownership contract revision " + newDelorean.getRevision() + " is " + deloreanResult + " by Network"); System.out.println("DeLorean ownership is now belongs to Stepa: " + newDelorean.getOwner().isAllowedForKeys(stepaPublicKeys)); assertEquals(ItemState.APPROVED, deloreanResult.state); assertTrue(newDelorean.getOwner().isAllowedForKeys(stepaPublicKeys)); lamborghiniResult = main.node.waitItem(newLamborghini.getId(), 5000); System.out.println("Lamborghini ownership contract revision " + newLamborghini.getRevision() + " is " + lamborghiniResult + " by Network"); System.out.println("Lamborghini ownership is now belongs to Marty: " + newLamborghini.getOwner().isAllowedForKeys(martyPublicKeys)); assertEquals(ItemState.APPROVED, lamborghiniResult.state); assertTrue(newLamborghini.getOwner().isAllowedForKeys(martyPublicKeys)); mm.forEach(x -> x.shutdown()); }
public void shutdown() { try { if (hookThread != null) Runtime.getRuntime().removeShutdownHook(hookThread); ledger.close(); log("shutting down"); network.shutdown(); clientHTTPServer.shutdown(); } catch (Exception e) { } synchronized (parser) { parser.notifyAll(); } try { logger.close(); } catch (Exception e) { e.printStackTrace(); } }
Main { public void shutdown() { try { if (hookThread != null) Runtime.getRuntime().removeShutdownHook(hookThread); ledger.close(); log("shutting down"); network.shutdown(); clientHTTPServer.shutdown(); } catch (Exception e) { } synchronized (parser) { parser.notifyAll(); } try { logger.close(); } catch (Exception e) { e.printStackTrace(); } } }
Main { public void shutdown() { try { if (hookThread != null) Runtime.getRuntime().removeShutdownHook(hookThread); ledger.close(); log("shutting down"); network.shutdown(); clientHTTPServer.shutdown(); } catch (Exception e) { } synchronized (parser) { parser.notifyAll(); } try { logger.close(); } catch (Exception e) { e.printStackTrace(); } } Main(String[] args); }
Main { public void shutdown() { try { if (hookThread != null) Runtime.getRuntime().removeShutdownHook(hookThread); ledger.close(); log("shutting down"); network.shutdown(); clientHTTPServer.shutdown(); } catch (Exception e) { } synchronized (parser) { parser.notifyAll(); } try { logger.close(); } catch (Exception e) { e.printStackTrace(); } } Main(String[] args); static void main(String[] args); void waitReady(); void shutdown(); void setVerboseLevel(int level); void setUDPVerboseLevel(int level); void restartUDPAdapter(); PublicKey getNodePublicKey(); }
Main { public void shutdown() { try { if (hookThread != null) Runtime.getRuntime().removeShutdownHook(hookThread); ledger.close(); log("shutting down"); network.shutdown(); clientHTTPServer.shutdown(); } catch (Exception e) { } synchronized (parser) { parser.notifyAll(); } try { logger.close(); } catch (Exception e) { e.printStackTrace(); } } Main(String[] args); static void main(String[] args); void waitReady(); void shutdown(); void setVerboseLevel(int level); void setUDPVerboseLevel(int level); void restartUDPAdapter(); PublicKey getNodePublicKey(); static final String NODE_VERSION; final Reporter reporter; final BufferedLogger logger; public NetConfig netConfig; public NetworkV2 network; final Config config; public NodeInfo myInfo; public Node node; public ItemCache cache; public ParcelCache parcelCache; public PaidOperationCache paidOperationCache; }
@Test public void testSwapSplitJoin_Api2() throws Exception { List<Main> mm = new ArrayList<>(); for (int i = 0; i < 4; i++) mm.add(createMain("node" + (i + 1), false)); Main main = mm.get(0); main.config.setIsFreeRegistrationsAllowedFromYaml(true); Client client = new Client(TestKeys.privateKey(20), main.myInfo, null); Set<PrivateKey> user1PrivateKeySet = new HashSet<>(asList(TestKeys.privateKey(1))); Set<PrivateKey> user2PrivateKeySet = new HashSet<>(asList(TestKeys.privateKey(2))); Set<PublicKey> user1PublicKeySet = user1PrivateKeySet.stream().map(prv -> prv.getPublicKey()).collect(Collectors.toSet()); Set<PublicKey> user2PublicKeySet = user2PrivateKeySet.stream().map(prv -> prv.getPublicKey()).collect(Collectors.toSet()); Contract contractTOK92 = ContractsService.createTokenContract(user1PrivateKeySet, user1PublicKeySet, new BigDecimal("100"), new BigDecimal("0.0001")); Contract contractTOK93 = ContractsService.createTokenContract(user2PrivateKeySet, user2PublicKeySet, new BigDecimal("100"), new BigDecimal("0.001")); contractTOK92.seal(); contractTOK92.check(); contractTOK92.traceErrors(); ItemResult itemResult = client.register(contractTOK92.getPackedTransaction(), 5000); assertEquals(ItemState.APPROVED, itemResult.state); contractTOK93.seal(); contractTOK93.check(); contractTOK93.traceErrors(); itemResult = client.register(contractTOK93.getPackedTransaction(), 5000); assertEquals(ItemState.APPROVED, itemResult.state); System.out.println("--- tokens created ---"); Contract user1CoinsSplit = ContractsService.createSplit(contractTOK92, new BigDecimal("8.02"), "amount", user1PrivateKeySet); Contract user1CoinsSplitToUser2 = user1CoinsSplit.getNew().get(0); Contract user2CoinsSplit = ContractsService.createSplit(contractTOK93, new BigDecimal("10.01"), "amount", user2PrivateKeySet); Contract user2CoinsSplitToUser1 = user2CoinsSplit.getNew().get(0); user1CoinsSplitToUser2.check(); user1CoinsSplitToUser2.traceErrors(); user2CoinsSplitToUser1.check(); user2CoinsSplitToUser1.traceErrors(); System.out.println("--- procedure for exchange of contracts ---"); Contract swapContract; swapContract = ContractsService.startSwap(user1CoinsSplitToUser2, user2CoinsSplitToUser1, user1PrivateKeySet, user2PublicKeySet, false); ContractsService.signPresentedSwap(swapContract, user2PrivateKeySet); ContractsService.finishSwap(swapContract, user1PrivateKeySet); user1CoinsSplit.seal(); user2CoinsSplit.seal(); swapContract.getNewItems().clear(); swapContract.addNewItems(user1CoinsSplit, user2CoinsSplit); swapContract.seal(); swapContract.check(); swapContract.traceErrors(); System.out.println("Transaction contract for swapping is valid: " + swapContract.isOk()); swapContract = Contract.fromPackedTransaction(swapContract.getPackedTransaction()); main.node.registerItem(swapContract); assertEquals(ItemState.APPROVED, main.node.waitItem(swapContract.getId(), 5000).state); assertEquals(ItemState.APPROVED, main.node.waitItem(user1CoinsSplit.getId(), 5000).state); assertEquals(ItemState.APPROVED, main.node.waitItem(user2CoinsSplit.getId(), 5000).state); assertEquals(ItemState.APPROVED, main.node.waitItem(user1CoinsSplitToUser2.getId(), 5000).state); assertEquals(ItemState.APPROVED, main.node.waitItem(user2CoinsSplitToUser1.getId(), 5000).state); assertEquals(ItemState.REVOKED, main.node.waitItem(contractTOK92.getId(), 5000).state); assertEquals(ItemState.REVOKED, main.node.waitItem(contractTOK93.getId(), 5000).state); assertEquals("8.02", user1CoinsSplitToUser2.getStateData().getStringOrThrow("amount")); assertEquals("10.01", user2CoinsSplitToUser1.getStateData().getStringOrThrow("amount")); assertFalse(user1CoinsSplitToUser2.getOwner().isAllowedForKeys(user1PublicKeySet)); assertTrue(user1CoinsSplitToUser2.getOwner().isAllowedForKeys(user2PublicKeySet)); assertTrue(user2CoinsSplitToUser1.getOwner().isAllowedForKeys(user1PublicKeySet)); assertFalse(user2CoinsSplitToUser1.getOwner().isAllowedForKeys(user2PublicKeySet)); mm.forEach(x -> x.shutdown()); }
public void shutdown() { try { if (hookThread != null) Runtime.getRuntime().removeShutdownHook(hookThread); ledger.close(); log("shutting down"); network.shutdown(); clientHTTPServer.shutdown(); } catch (Exception e) { } synchronized (parser) { parser.notifyAll(); } try { logger.close(); } catch (Exception e) { e.printStackTrace(); } }
Main { public void shutdown() { try { if (hookThread != null) Runtime.getRuntime().removeShutdownHook(hookThread); ledger.close(); log("shutting down"); network.shutdown(); clientHTTPServer.shutdown(); } catch (Exception e) { } synchronized (parser) { parser.notifyAll(); } try { logger.close(); } catch (Exception e) { e.printStackTrace(); } } }
Main { public void shutdown() { try { if (hookThread != null) Runtime.getRuntime().removeShutdownHook(hookThread); ledger.close(); log("shutting down"); network.shutdown(); clientHTTPServer.shutdown(); } catch (Exception e) { } synchronized (parser) { parser.notifyAll(); } try { logger.close(); } catch (Exception e) { e.printStackTrace(); } } Main(String[] args); }
Main { public void shutdown() { try { if (hookThread != null) Runtime.getRuntime().removeShutdownHook(hookThread); ledger.close(); log("shutting down"); network.shutdown(); clientHTTPServer.shutdown(); } catch (Exception e) { } synchronized (parser) { parser.notifyAll(); } try { logger.close(); } catch (Exception e) { e.printStackTrace(); } } Main(String[] args); static void main(String[] args); void waitReady(); void shutdown(); void setVerboseLevel(int level); void setUDPVerboseLevel(int level); void restartUDPAdapter(); PublicKey getNodePublicKey(); }
Main { public void shutdown() { try { if (hookThread != null) Runtime.getRuntime().removeShutdownHook(hookThread); ledger.close(); log("shutting down"); network.shutdown(); clientHTTPServer.shutdown(); } catch (Exception e) { } synchronized (parser) { parser.notifyAll(); } try { logger.close(); } catch (Exception e) { e.printStackTrace(); } } Main(String[] args); static void main(String[] args); void waitReady(); void shutdown(); void setVerboseLevel(int level); void setUDPVerboseLevel(int level); void restartUDPAdapter(); PublicKey getNodePublicKey(); static final String NODE_VERSION; final Reporter reporter; final BufferedLogger logger; public NetConfig netConfig; public NetworkV2 network; final Config config; public NodeInfo myInfo; public Node node; public ItemCache cache; public ParcelCache parcelCache; public PaidOperationCache paidOperationCache; }
@Test public void testAddReferenceApi() throws Exception { List<Main> mm = new ArrayList<>(); for (int i = 0; i < 4; i++) mm.add(createMain("node" + (i + 1), false)); Main main = mm.get(0); main.config.setIsFreeRegistrationsAllowedFromYaml(true); Client client = new Client(TestKeys.privateKey(20), main.myInfo, null); Set<PrivateKey> stepaPrivateKeys = new HashSet<>(); Set<PrivateKey> llcPrivateKeys = new HashSet<>(); Set<PrivateKey> thirdPartyPrivateKeys = new HashSet<>(); llcPrivateKeys.add(new PrivateKey(Do.read(ROOT_PATH + "_xer0yfe2nn1xthc.private.unikey"))); stepaPrivateKeys.add(new PrivateKey(Do.read(ROOT_PATH + "keys/stepan_mamontov.private.unikey"))); thirdPartyPrivateKeys.add(new PrivateKey(Do.read(ROOT_PATH + "keys/marty_mcfly.private.unikey"))); Set<PublicKey> stepaPublicKeys = new HashSet<>(); for (PrivateKey pk : stepaPrivateKeys) { stepaPublicKeys.add(pk.getPublicKey()); } Set<PublicKey> thirdPartyPublicKeys = new HashSet<>(); for (PrivateKey pk : thirdPartyPrivateKeys) { thirdPartyPublicKeys.add(pk.getPublicKey()); } Contract jobCertificate = new Contract(llcPrivateKeys.iterator().next()); jobCertificate.setOwnerKeys(stepaPublicKeys); jobCertificate.getDefinition().getData().set("issuer", "ApricoT"); jobCertificate.getDefinition().getData().set("type", "chief accountant assignment"); jobCertificate.seal(); jobCertificate.check(); jobCertificate.traceErrors(); ItemResult itemResult = client.register(jobCertificate.getPackedTransaction(), 5000); System.out.println("sourceContract : " + itemResult); assertEquals(ItemState.APPROVED, client.getState(jobCertificate.getId()).state); Contract llcProperty = ContractsService.createNotaryContract(llcPrivateKeys, stepaPublicKeys); List<String> listConditions = new ArrayList<>(); listConditions.add("ref.definition.issuer == \"HggcAQABxAACzHE9ibWlnK4RzpgFIB4jIg3WcXZSKXNAqOTYUtGXY03xJSwpqE+y/HbqqE0WsmcAt5\n" + " a0F5H7bz87Uy8Me1UdIDcOJgP8HMF2M0I/kkT6d59ZhYH/TlpDcpLvnJWElZAfOytaICE01bkOkf6M\n" + " z5egpToDEEPZH/RXigj9wkSXkk43WZSxVY5f2zaVmibUZ9VLoJlmjNTZ+utJUZi66iu9e0SXupOr/+\n" + " BJL1Gm595w32Fd0141kBvAHYDHz2K3x4m1oFAcElJ83ahSl1u85/naIaf2yuxiQNz3uFMTn0IpULCM\n" + " vLMvmE+L9io7+KWXld2usujMXI1ycDRw85h6IJlPcKHVQKnJ/4wNBUveBDLFLlOcMpCzWlO/D7M2Iy\n" + " Na8XEvwPaFJlN1UN/9eVpaRUBEfDq6zi+RC8MaVWzFbNi913suY0Q8F7ejKR6aQvQPuNN6bK6iRYZc\n" + " hxe/FwWIXOr0C0yA3NFgxKLiKZjkd5eJ84GLy+iD00Rzjom+GG4FDQKr2HxYZDdDuLE4PEpYSzEB/8\n" + " LyIqeM7dSyaHFTBII/sLuFru6ffoKxBNk/cwAGZqOwD3fkJjNq1R3h6QylWXI/cSO9yRnRMmMBJwal\n" + " MexOc3/kPEEdfjH/GcJU0Mw6DgoY8QgfaNwXcFbBUvf3TwZ5Mysf21OLHH13g8gzREm+h8c=\""); listConditions.add("ref.definition.data.issuer == \"ApricoT\""); listConditions.add("ref.definition.data.type == \"chief accountant assignment\""); ContractsService.addReferenceToContract(llcProperty, jobCertificate, "certification_contract", Reference.TYPE_EXISTING_DEFINITION, listConditions, true); llcProperty.check(); llcProperty.traceErrors(); itemResult = client.register(llcProperty.getPackedTransaction(), 5000); System.out.println("sourceContract : " + itemResult); assertEquals(ItemState.APPROVED, client.getState(llcProperty.getId()).state); mm.forEach(x -> x.shutdown()); }
public void shutdown() { try { if (hookThread != null) Runtime.getRuntime().removeShutdownHook(hookThread); ledger.close(); log("shutting down"); network.shutdown(); clientHTTPServer.shutdown(); } catch (Exception e) { } synchronized (parser) { parser.notifyAll(); } try { logger.close(); } catch (Exception e) { e.printStackTrace(); } }
Main { public void shutdown() { try { if (hookThread != null) Runtime.getRuntime().removeShutdownHook(hookThread); ledger.close(); log("shutting down"); network.shutdown(); clientHTTPServer.shutdown(); } catch (Exception e) { } synchronized (parser) { parser.notifyAll(); } try { logger.close(); } catch (Exception e) { e.printStackTrace(); } } }
Main { public void shutdown() { try { if (hookThread != null) Runtime.getRuntime().removeShutdownHook(hookThread); ledger.close(); log("shutting down"); network.shutdown(); clientHTTPServer.shutdown(); } catch (Exception e) { } synchronized (parser) { parser.notifyAll(); } try { logger.close(); } catch (Exception e) { e.printStackTrace(); } } Main(String[] args); }
Main { public void shutdown() { try { if (hookThread != null) Runtime.getRuntime().removeShutdownHook(hookThread); ledger.close(); log("shutting down"); network.shutdown(); clientHTTPServer.shutdown(); } catch (Exception e) { } synchronized (parser) { parser.notifyAll(); } try { logger.close(); } catch (Exception e) { e.printStackTrace(); } } Main(String[] args); static void main(String[] args); void waitReady(); void shutdown(); void setVerboseLevel(int level); void setUDPVerboseLevel(int level); void restartUDPAdapter(); PublicKey getNodePublicKey(); }
Main { public void shutdown() { try { if (hookThread != null) Runtime.getRuntime().removeShutdownHook(hookThread); ledger.close(); log("shutting down"); network.shutdown(); clientHTTPServer.shutdown(); } catch (Exception e) { } synchronized (parser) { parser.notifyAll(); } try { logger.close(); } catch (Exception e) { e.printStackTrace(); } } Main(String[] args); static void main(String[] args); void waitReady(); void shutdown(); void setVerboseLevel(int level); void setUDPVerboseLevel(int level); void restartUDPAdapter(); PublicKey getNodePublicKey(); static final String NODE_VERSION; final Reporter reporter; final BufferedLogger logger; public NetConfig netConfig; public NetworkV2 network; final Config config; public NodeInfo myInfo; public Node node; public ItemCache cache; public ParcelCache parcelCache; public PaidOperationCache paidOperationCache; }
@Test public void paymentTest1() throws Exception { List<Main> mm = new ArrayList<>(); for (int i = 0; i < 4; i++) mm.add(createMain("node" + (i + 1), false)); Main main = mm.get(0); main.config.setIsFreeRegistrationsAllowedFromYaml(true); Client client = new Client(TestKeys.privateKey(20), main.myInfo, null); Contract simpleContract = new Contract(TestKeys.privateKey(1)); simpleContract.seal(); Contract stepaU = InnerContractsService.createFreshU(100000000, new HashSet<>(asList(TestKeys.publicKey(1)))); ItemResult itemResult = client.register(stepaU.getPackedTransaction(), 5000); System.out.println("stepaU itemResult: " + itemResult); assertEquals(ItemState.APPROVED, itemResult.state); main.config.setIsFreeRegistrationsAllowedFromYaml(false); Parcel parcel = ContractsService.createParcel(simpleContract, stepaU, 1, new HashSet<>(asList(TestKeys.privateKey(1))), false); client.registerParcelWithState(parcel.pack(), 5000); assertEquals(ItemState.APPROVED, client.getState(simpleContract.getId()).state); mm.forEach(x -> x.shutdown()); }
public void shutdown() { try { if (hookThread != null) Runtime.getRuntime().removeShutdownHook(hookThread); ledger.close(); log("shutting down"); network.shutdown(); clientHTTPServer.shutdown(); } catch (Exception e) { } synchronized (parser) { parser.notifyAll(); } try { logger.close(); } catch (Exception e) { e.printStackTrace(); } }
Main { public void shutdown() { try { if (hookThread != null) Runtime.getRuntime().removeShutdownHook(hookThread); ledger.close(); log("shutting down"); network.shutdown(); clientHTTPServer.shutdown(); } catch (Exception e) { } synchronized (parser) { parser.notifyAll(); } try { logger.close(); } catch (Exception e) { e.printStackTrace(); } } }
Main { public void shutdown() { try { if (hookThread != null) Runtime.getRuntime().removeShutdownHook(hookThread); ledger.close(); log("shutting down"); network.shutdown(); clientHTTPServer.shutdown(); } catch (Exception e) { } synchronized (parser) { parser.notifyAll(); } try { logger.close(); } catch (Exception e) { e.printStackTrace(); } } Main(String[] args); }
Main { public void shutdown() { try { if (hookThread != null) Runtime.getRuntime().removeShutdownHook(hookThread); ledger.close(); log("shutting down"); network.shutdown(); clientHTTPServer.shutdown(); } catch (Exception e) { } synchronized (parser) { parser.notifyAll(); } try { logger.close(); } catch (Exception e) { e.printStackTrace(); } } Main(String[] args); static void main(String[] args); void waitReady(); void shutdown(); void setVerboseLevel(int level); void setUDPVerboseLevel(int level); void restartUDPAdapter(); PublicKey getNodePublicKey(); }
Main { public void shutdown() { try { if (hookThread != null) Runtime.getRuntime().removeShutdownHook(hookThread); ledger.close(); log("shutting down"); network.shutdown(); clientHTTPServer.shutdown(); } catch (Exception e) { } synchronized (parser) { parser.notifyAll(); } try { logger.close(); } catch (Exception e) { e.printStackTrace(); } } Main(String[] args); static void main(String[] args); void waitReady(); void shutdown(); void setVerboseLevel(int level); void setUDPVerboseLevel(int level); void restartUDPAdapter(); PublicKey getNodePublicKey(); static final String NODE_VERSION; final Reporter reporter; final BufferedLogger logger; public NetConfig netConfig; public NetworkV2 network; final Config config; public NodeInfo myInfo; public Node node; public ItemCache cache; public ParcelCache parcelCache; public PaidOperationCache paidOperationCache; }
@Test public void cloneDigest() throws Exception { Digest d1Orig = new SHA512Digest(); Digest d1Clone = RSAOAEPDigestFactory.cloneDigest(d1Orig); assertTrue(d1Clone instanceof SHA512Digest); assertNotEquals(d1Orig, d1Clone); }
public static Digest cloneDigest(Digest digest) { try { return digest.getClass().newInstance(); } catch (InstantiationException | IllegalAccessException exc) { exc.printStackTrace(); return digest; } }
RSAOAEPDigestFactory { public static Digest cloneDigest(Digest digest) { try { return digest.getClass().newInstance(); } catch (InstantiationException | IllegalAccessException exc) { exc.printStackTrace(); return digest; } } }
RSAOAEPDigestFactory { public static Digest cloneDigest(Digest digest) { try { return digest.getClass().newInstance(); } catch (InstantiationException | IllegalAccessException exc) { exc.printStackTrace(); return digest; } } }
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); }
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); }
@Test public void concurrentResyncTest() throws Exception { boolean doShutdown = true; PrivateKey issuerKey = new PrivateKey(Do.read("./src/test_contracts/keys/reconfig_key.private.unikey")); TestSpace testSpace = prepareTestSpace(issuerKey); testSpace.nodes.forEach(n -> n.config.setIsFreeRegistrationsAllowedFromYaml(true)); Set<PrivateKey> issuerKeys = new HashSet<>(); Set<PublicKey> ownerKeys = new HashSet<>(); issuerKeys.add(issuerKey); ownerKeys.add(issuerKey.getPublicKey()); ArrayList<Contract> contractsToJoin = new ArrayList<>(); for (int k = 0; k < 4; k++) { if (doShutdown) { if (k < 3) { int absentNode = k + 1; testSpace.nodes.get(absentNode).shutdown(); testSpace.nodes.remove(absentNode); } } Contract contract = new Contract(issuerKey); contract.getDefinition().getData().set("test", "test1"); contract.getStateData().set("amount", "100"); Binder params = Binder.of("field_name", "amount", "join_match_fields", asList("definition.issuer")); Role ownerLink = new RoleLink("@owner_link", "owner"); contract.registerRole(ownerLink); SplitJoinPermission splitJoinPermission = new SplitJoinPermission(ownerLink, params); contract.addPermission(splitJoinPermission); contract.seal(); testSpace.client.register(contract.getPackedTransaction(), 1500); assertEquals(testSpace.client.getState(contract.getId()).state, ItemState.APPROVED); if (doShutdown) { testSpace.nodes.forEach(n -> n.shutdown()); Thread.sleep(2000); testSpace = prepareTestSpace(issuerKey); testSpace.nodes.forEach(n -> n.config.setIsFreeRegistrationsAllowedFromYaml(true)); } contractsToJoin.add(contract); } TestSpace finalTestSpace = testSpace; contractsToJoin.forEach(c -> { int count = 0; for (Main main : finalTestSpace.nodes) { try { if (main.node.waitItem(c.getId(), 4000).state != ItemState.APPROVED) { count++; } } catch (TimeoutException e) { e.printStackTrace(); } catch (InterruptedException e) { e.printStackTrace(); } } System.out.println("Contract " + c.getId() + " is unknown to " + count + "node(s)"); }); Contract c = contractsToJoin.remove(Do.randomInt(contractsToJoin.size())); Contract main = c.createRevision(issuerKey); main.getStateData().set("amount", "400"); main.addRevokingItems(contractsToJoin.get(0), contractsToJoin.get(1), contractsToJoin.get(2)); main.addSignerKey(issuerKey); main.seal(); contractsToJoin.add(c); testSpace.client.register(main.getPackedTransaction(), 1500); ItemResult ir; do { ir = testSpace.client.getState(main.getId()); System.out.println(ir); Thread.sleep(1000); } while (ir.state.isPending()); contractsToJoin.forEach(c1 -> { int count = 0; for (Main main1 : finalTestSpace.nodes) { try { if (main1.node.waitItem(c1.getId(), 4000).state != ItemState.APPROVED) { count++; } } catch (TimeoutException e) { e.printStackTrace(); } catch (InterruptedException e) { e.printStackTrace(); } } System.out.println("Contract " + c.getId() + " is unknown to " + count + "node(s)"); }); assertEquals(ir.state, ItemState.APPROVED); testSpace.nodes.forEach(x -> x.shutdown()); }
public void shutdown() { try { if (hookThread != null) Runtime.getRuntime().removeShutdownHook(hookThread); ledger.close(); log("shutting down"); network.shutdown(); clientHTTPServer.shutdown(); } catch (Exception e) { } synchronized (parser) { parser.notifyAll(); } try { logger.close(); } catch (Exception e) { e.printStackTrace(); } }
Main { public void shutdown() { try { if (hookThread != null) Runtime.getRuntime().removeShutdownHook(hookThread); ledger.close(); log("shutting down"); network.shutdown(); clientHTTPServer.shutdown(); } catch (Exception e) { } synchronized (parser) { parser.notifyAll(); } try { logger.close(); } catch (Exception e) { e.printStackTrace(); } } }
Main { public void shutdown() { try { if (hookThread != null) Runtime.getRuntime().removeShutdownHook(hookThread); ledger.close(); log("shutting down"); network.shutdown(); clientHTTPServer.shutdown(); } catch (Exception e) { } synchronized (parser) { parser.notifyAll(); } try { logger.close(); } catch (Exception e) { e.printStackTrace(); } } Main(String[] args); }
Main { public void shutdown() { try { if (hookThread != null) Runtime.getRuntime().removeShutdownHook(hookThread); ledger.close(); log("shutting down"); network.shutdown(); clientHTTPServer.shutdown(); } catch (Exception e) { } synchronized (parser) { parser.notifyAll(); } try { logger.close(); } catch (Exception e) { e.printStackTrace(); } } Main(String[] args); static void main(String[] args); void waitReady(); void shutdown(); void setVerboseLevel(int level); void setUDPVerboseLevel(int level); void restartUDPAdapter(); PublicKey getNodePublicKey(); }
Main { public void shutdown() { try { if (hookThread != null) Runtime.getRuntime().removeShutdownHook(hookThread); ledger.close(); log("shutting down"); network.shutdown(); clientHTTPServer.shutdown(); } catch (Exception e) { } synchronized (parser) { parser.notifyAll(); } try { logger.close(); } catch (Exception e) { e.printStackTrace(); } } Main(String[] args); static void main(String[] args); void waitReady(); void shutdown(); void setVerboseLevel(int level); void setUDPVerboseLevel(int level); void restartUDPAdapter(); PublicKey getNodePublicKey(); static final String NODE_VERSION; final Reporter reporter; final BufferedLogger logger; public NetConfig netConfig; public NetworkV2 network; final Config config; public NodeInfo myInfo; public Node node; public ItemCache cache; public ParcelCache parcelCache; public PaidOperationCache paidOperationCache; }
@Test public void tttt() throws Exception { boolean refAsNew = true; PrivateKey key = TestKeys.privateKey(1); TestSpace testSpace = prepareTestSpace(key); testSpace.nodes.forEach(m -> { m.config.setIsFreeRegistrationsAllowedFromYaml(true); }); Contract contractMark = new Contract(key); contractMark.seal(); HashId origin = contractMark.getId(); Contract contractMark2 = new Contract(key); contractMark2.seal(); HashId origin2 = contractMark2.getId(); Contract contract = new Contract(key); SimpleRole issuer = new SimpleRole("issuer"); issuer.addKeyRecord(new KeyRecord(key.getPublicKey())); Reference ref = new Reference(contract); ref.type = Reference.TYPE_EXISTING_STATE; ref.setName(origin.toString()); List<Object> conditionsList = new ArrayList<>(); conditionsList.add(REFERENCE_CONDITION_PREFIX + "\"" + origin.toBase64String() + "\""); conditionsList.add(REFERENCE_CONDITION2); Binder conditions = Binder.of(Reference.conditionsModeType.all_of.name(), conditionsList); ref.setConditions(conditions); Reference ref2 = new Reference(contract); ref2.type = Reference.TYPE_EXISTING_STATE; ref2.setName(origin2.toString()); List<Object> conditionsList2 = new ArrayList<>(); conditionsList2.add(REFERENCE_CONDITION_PREFIX + "\"" + origin2.toBase64String() + "\""); conditionsList2.add(REFERENCE_CONDITION2); Binder conditions2 = Binder.of(Reference.conditionsModeType.all_of.name(), conditionsList2); ref2.setConditions(conditions2); contract.addReference(ref); issuer.addRequiredReference(ref, Role.RequiredMode.ALL_OF); contract.addReference(ref2); issuer.addRequiredReference(ref2, Role.RequiredMode.ALL_OF); contract.registerRole(issuer); contract.setOwnerKeys(key); contract.seal(); ItemResult ir = testSpace.client.register(contract.getPackedTransaction(), 5000); assertEquals(ir.state, ItemState.DECLINED); contract.seal(); contract.getTransactionPack().addReferencedItem(contractMark); contract.getTransactionPack().addReferencedItem(contractMark2); ir = testSpace.client.register(contract.getPackedTransaction(), 5000); assertEquals(ir.state, ItemState.DECLINED); if (refAsNew) { contract.addNewItems(contractMark); contract.addNewItems(contractMark2); } else { testSpace.client.register(contractMark.getPackedTransaction(), 5000); testSpace.client.register(contractMark2.getPackedTransaction(), 5000); } contract.seal(); if (!refAsNew) { contract.getTransactionPack().addReferencedItem(contractMark); contract.getTransactionPack().addReferencedItem(contractMark2); } ir = testSpace.client.register(contract.getPackedTransaction(), 5000); assertEquals(ir.state, ItemState.APPROVED); contract = contract.createRevision(key); contract.addSignerKey(key); contract.setOwnerKeys(TestKeys.privateKey(2).getPublicKey()); contract.seal(); ir = testSpace.client.register(contract.getPackedTransaction(), 5000); assertEquals(ir.state, ItemState.APPROVED); testSpace.nodes.forEach(n -> n.shutdown()); }
public void shutdown() { try { if (hookThread != null) Runtime.getRuntime().removeShutdownHook(hookThread); ledger.close(); log("shutting down"); network.shutdown(); clientHTTPServer.shutdown(); } catch (Exception e) { } synchronized (parser) { parser.notifyAll(); } try { logger.close(); } catch (Exception e) { e.printStackTrace(); } }
Main { public void shutdown() { try { if (hookThread != null) Runtime.getRuntime().removeShutdownHook(hookThread); ledger.close(); log("shutting down"); network.shutdown(); clientHTTPServer.shutdown(); } catch (Exception e) { } synchronized (parser) { parser.notifyAll(); } try { logger.close(); } catch (Exception e) { e.printStackTrace(); } } }
Main { public void shutdown() { try { if (hookThread != null) Runtime.getRuntime().removeShutdownHook(hookThread); ledger.close(); log("shutting down"); network.shutdown(); clientHTTPServer.shutdown(); } catch (Exception e) { } synchronized (parser) { parser.notifyAll(); } try { logger.close(); } catch (Exception e) { e.printStackTrace(); } } Main(String[] args); }
Main { public void shutdown() { try { if (hookThread != null) Runtime.getRuntime().removeShutdownHook(hookThread); ledger.close(); log("shutting down"); network.shutdown(); clientHTTPServer.shutdown(); } catch (Exception e) { } synchronized (parser) { parser.notifyAll(); } try { logger.close(); } catch (Exception e) { e.printStackTrace(); } } Main(String[] args); static void main(String[] args); void waitReady(); void shutdown(); void setVerboseLevel(int level); void setUDPVerboseLevel(int level); void restartUDPAdapter(); PublicKey getNodePublicKey(); }
Main { public void shutdown() { try { if (hookThread != null) Runtime.getRuntime().removeShutdownHook(hookThread); ledger.close(); log("shutting down"); network.shutdown(); clientHTTPServer.shutdown(); } catch (Exception e) { } synchronized (parser) { parser.notifyAll(); } try { logger.close(); } catch (Exception e) { e.printStackTrace(); } } Main(String[] args); static void main(String[] args); void waitReady(); void shutdown(); void setVerboseLevel(int level); void setUDPVerboseLevel(int level); void restartUDPAdapter(); PublicKey getNodePublicKey(); static final String NODE_VERSION; final Reporter reporter; final BufferedLogger logger; public NetConfig netConfig; public NetworkV2 network; final Config config; public NodeInfo myInfo; public Node node; public ItemCache cache; public ParcelCache parcelCache; public PaidOperationCache paidOperationCache; }
@Test public void testMarkReferences5() throws Exception { PrivateKey key = TestKeys.privateKey(1); TestSpace testSpace = prepareTestSpace(key); testSpace.nodes.forEach(m -> { m.config.setIsFreeRegistrationsAllowedFromYaml(true); }); Contract contractMark = new Contract(key); contractMark.seal(); HashId origin = contractMark.getId(); Contract contractMark2 = new Contract(key); contractMark2.seal(); HashId origin2 = contractMark2.getId(); Contract contractMark3 = new Contract(key); contractMark3.seal(); HashId origin3 = contractMark3.getId(); Contract contractMark4 = new Contract(key); contractMark4.seal(); HashId origin4 = contractMark4.getId(); Contract contractMark5 = new Contract(key); contractMark5.seal(); HashId origin5 = contractMark5.getId(); Contract contract = new Contract(key); SimpleRole issuer = new SimpleRole("issuer"); issuer.addKeyRecord(new KeyRecord(key.getPublicKey())); Reference ref = new Reference(contract); ref.type = Reference.TYPE_EXISTING_STATE; ref.setName(origin.toString()); List<Object> conditionsList = new ArrayList<>(); conditionsList.add(REFERENCE_CONDITION_PREFIX + "\"" + origin.toBase64String() + "\""); conditionsList.add(REFERENCE_CONDITION2); Binder conditions = Binder.of(Reference.conditionsModeType.all_of.name(), conditionsList); ref.setConditions(conditions); contract.addReference(ref); issuer.addRequiredReference(ref, Role.RequiredMode.ALL_OF); Reference ref2 = new Reference(contract); ref2.type = Reference.TYPE_EXISTING_STATE; ref2.setName(origin2.toString()); List<Object> conditionsList2 = new ArrayList<>(); conditionsList2.add(REFERENCE_CONDITION_PREFIX + "\"" + origin2.toBase64String() + "\""); conditionsList2.add(REFERENCE_CONDITION2); Binder conditions2 = Binder.of(Reference.conditionsModeType.all_of.name(), conditionsList2); ref2.setConditions(conditions2); contract.addReference(ref2); issuer.addRequiredReference(ref2, Role.RequiredMode.ALL_OF); Reference ref3 = new Reference(contract); ref3.type = Reference.TYPE_EXISTING_STATE; ref3.setName(origin3.toString()); List<Object> conditionsList3 = new ArrayList<>(); conditionsList3.add(REFERENCE_CONDITION_PREFIX + "\"" + origin3.toBase64String() + "\""); conditionsList3.add(REFERENCE_CONDITION2); Binder conditions3 = Binder.of(Reference.conditionsModeType.all_of.name(), conditionsList3); ref3.setConditions(conditions3); contract.addReference(ref3); issuer.addRequiredReference(ref3, Role.RequiredMode.ALL_OF); Reference ref4 = new Reference(contract); ref4.type = Reference.TYPE_EXISTING_STATE; ref4.setName(origin4.toString()); List<Object> conditionsList4 = new ArrayList<>(); conditionsList4.add(REFERENCE_CONDITION_PREFIX + "\"" + origin4.toBase64String() + "\""); conditionsList4.add(REFERENCE_CONDITION2); Binder conditions4 = Binder.of(Reference.conditionsModeType.all_of.name(), conditionsList4); ref4.setConditions(conditions4); contract.addReference(ref4); issuer.addRequiredReference(ref4, Role.RequiredMode.ALL_OF); Reference ref5 = new Reference(contract); ref5.type = Reference.TYPE_EXISTING_STATE; ref5.setName(origin5.toString()); List<Object> conditionsList5 = new ArrayList<>(); conditionsList5.add(REFERENCE_CONDITION_PREFIX + "\"" + origin5.toBase64String() + "\""); conditionsList5.add(REFERENCE_CONDITION2); Binder conditions5 = Binder.of(Reference.conditionsModeType.all_of.name(), conditionsList5); ref5.setConditions(conditions5); contract.addReference(ref5); issuer.addRequiredReference(ref5, Role.RequiredMode.ALL_OF); contract.registerRole(issuer); contract.setOwnerKeys(key); contract.seal(); ItemResult ir = testSpace.client.register(contract.getPackedTransaction(), 5000); assertEquals(ir.state, ItemState.DECLINED); contract.seal(); contract.getTransactionPack().addReferencedItem(contractMark); contract.getTransactionPack().addReferencedItem(contractMark2); ir = testSpace.client.register(contract.getPackedTransaction(), 5000); assertEquals(ir.state, ItemState.DECLINED); contract.addNewItems(contractMark); contract.addNewItems(contractMark2); contract.addNewItems(contractMark3); testSpace.client.register(contractMark4.getPackedTransaction(), 5000); testSpace.client.register(contractMark5.getPackedTransaction(), 5000); contract.seal(); contract.getTransactionPack().addReferencedItem(contractMark4); contract.getTransactionPack().addReferencedItem(contractMark5); ir = testSpace.client.register(contract.getPackedTransaction(), 5000); assertEquals(ir.state, ItemState.APPROVED); contract = contract.createRevision(key); contract.addSignerKey(key); contract.setOwnerKeys(TestKeys.privateKey(2).getPublicKey()); contract.seal(); ir = testSpace.client.register(contract.getPackedTransaction(), 5000); assertEquals(ir.state, ItemState.APPROVED); testSpace.nodes.forEach(n -> n.shutdown()); }
public void shutdown() { try { if (hookThread != null) Runtime.getRuntime().removeShutdownHook(hookThread); ledger.close(); log("shutting down"); network.shutdown(); clientHTTPServer.shutdown(); } catch (Exception e) { } synchronized (parser) { parser.notifyAll(); } try { logger.close(); } catch (Exception e) { e.printStackTrace(); } }
Main { public void shutdown() { try { if (hookThread != null) Runtime.getRuntime().removeShutdownHook(hookThread); ledger.close(); log("shutting down"); network.shutdown(); clientHTTPServer.shutdown(); } catch (Exception e) { } synchronized (parser) { parser.notifyAll(); } try { logger.close(); } catch (Exception e) { e.printStackTrace(); } } }
Main { public void shutdown() { try { if (hookThread != null) Runtime.getRuntime().removeShutdownHook(hookThread); ledger.close(); log("shutting down"); network.shutdown(); clientHTTPServer.shutdown(); } catch (Exception e) { } synchronized (parser) { parser.notifyAll(); } try { logger.close(); } catch (Exception e) { e.printStackTrace(); } } Main(String[] args); }
Main { public void shutdown() { try { if (hookThread != null) Runtime.getRuntime().removeShutdownHook(hookThread); ledger.close(); log("shutting down"); network.shutdown(); clientHTTPServer.shutdown(); } catch (Exception e) { } synchronized (parser) { parser.notifyAll(); } try { logger.close(); } catch (Exception e) { e.printStackTrace(); } } Main(String[] args); static void main(String[] args); void waitReady(); void shutdown(); void setVerboseLevel(int level); void setUDPVerboseLevel(int level); void restartUDPAdapter(); PublicKey getNodePublicKey(); }
Main { public void shutdown() { try { if (hookThread != null) Runtime.getRuntime().removeShutdownHook(hookThread); ledger.close(); log("shutting down"); network.shutdown(); clientHTTPServer.shutdown(); } catch (Exception e) { } synchronized (parser) { parser.notifyAll(); } try { logger.close(); } catch (Exception e) { e.printStackTrace(); } } Main(String[] args); static void main(String[] args); void waitReady(); void shutdown(); void setVerboseLevel(int level); void setUDPVerboseLevel(int level); void restartUDPAdapter(); PublicKey getNodePublicKey(); static final String NODE_VERSION; final Reporter reporter; final BufferedLogger logger; public NetConfig netConfig; public NetworkV2 network; final Config config; public NodeInfo myInfo; public Node node; public ItemCache cache; public ParcelCache parcelCache; public PaidOperationCache paidOperationCache; }
@Test public void conversionSchemeUtoUTN() throws Exception { PrivateKey universaAdminKey = TestKeys.privateKey(10); PrivateKey utnIssuerKey = TestKeys.privateKey(11); PrivateKey uIssuerKey = new PrivateKey(Do.read(Config.uKeyPath)); PrivateKey userKey = TestKeys.privateKey(12); Set<PrivateKey> userKeys = new HashSet<>(); userKeys.add(userKey); SimpleRole universaAdmin = new SimpleRole("universa_admin"); universaAdmin.addKeyRecord(new KeyRecord(universaAdminKey.getPublicKey())); TestSpace testSpace = prepareTestSpace(userKey); testSpace.nodes.forEach(n -> n.config.setIsFreeRegistrationsAllowedFromYaml(true)); Set<PrivateKey> utnIssuer = new HashSet<>(); utnIssuer.add(utnIssuerKey); Set<PublicKey> ownerKeys = new HashSet<>(); ownerKeys.add(userKey.getPublicKey()); Contract utnContract = ContractsService.createTokenContract(utnIssuer, ownerKeys, new BigDecimal("100000")); @NonNull ItemResult ir = testSpace.client.register(utnContract.getPackedTransaction()); while (ir.state.isPending()) { Thread.sleep(500); ir = testSpace.client.getState(utnContract.getId()); } assertEquals(ir.state, ItemState.APPROVED); Contract compound = ContractsService.createSplit(utnContract, new BigDecimal("150"), "amount", new HashSet<>(), true); Contract paymentInUTNs = (Contract) compound.getNewItems().iterator().next(); paymentInUTNs.setOwnerKeys(universaAdminKey); BigDecimal utnsPayed = new BigDecimal(paymentInUTNs.getStateData().getString("amount")); int unitsToIssue = utnsPayed.intValue() * 100; Contract uContract = InnerContractsService.createFreshU(unitsToIssue, ownerKeys); Contract consent = ContractsService.addConsent(uContract, universaAdminKey.getPublicKey().getLongAddress()); uContract.seal(); compound.addNewItems(uContract); consent.addSignerKey(universaAdminKey); consent.seal(); compound.seal(); compound.addSignatureToSeal(userKeys); ir = testSpace.client.register(compound.getPackedTransaction()); while (ir.state.isPending()) { Thread.sleep(500); ir = testSpace.client.getState(compound.getId()); } assertEquals(ir.state, ItemState.DECLINED); compound.seal(); compound.addSignatureToSeal(userKeys); Contract batch = ContractsService.createBatch(userKeys, compound, consent); ir = testSpace.client.register(batch.getPackedTransaction()); while (ir.state.isPending()) { Thread.sleep(500); ir = testSpace.client.getState(batch.getId()); } assertEquals(ir.state, ItemState.APPROVED); Contract sampleContract = new Contract(userKey); sampleContract.seal(); Parcel parcel = ContractsService.createParcel(sampleContract, uContract, 1, userKeys); testSpace.client.registerParcelWithState(parcel.pack(), 5000); do { Thread.sleep(500); ir = testSpace.client.getState(sampleContract.getId()); } while (ir.state.isPending()); ItemResult pr = testSpace.client.getState(parcel.getPaymentContract().getId()); assertEquals(pr.state, ItemState.APPROVED); assertEquals(ir.state, ItemState.APPROVED); uContract = parcel.getPaymentContract(); Contract revocation = ContractsService.createRevocation(consent, universaAdminKey); ir = testSpace.client.register(revocation.getPackedTransaction()); while (ir.state.isPending()) { Thread.sleep(500); ir = testSpace.client.getState(revocation.getId()); } assertEquals(ir.state, ItemState.APPROVED); sampleContract = new Contract(userKey); sampleContract.seal(); parcel = ContractsService.createParcel(sampleContract, uContract, 1, userKeys); testSpace.client.registerParcelWithState(parcel.pack(), 5000); do { Thread.sleep(500); ir = testSpace.client.getState(sampleContract.getId()); } while (ir.state.isPending()); assertEquals(ir.state, ItemState.APPROVED); testSpace.nodes.forEach(n -> n.shutdown()); }
public void shutdown() { try { if (hookThread != null) Runtime.getRuntime().removeShutdownHook(hookThread); ledger.close(); log("shutting down"); network.shutdown(); clientHTTPServer.shutdown(); } catch (Exception e) { } synchronized (parser) { parser.notifyAll(); } try { logger.close(); } catch (Exception e) { e.printStackTrace(); } }
Main { public void shutdown() { try { if (hookThread != null) Runtime.getRuntime().removeShutdownHook(hookThread); ledger.close(); log("shutting down"); network.shutdown(); clientHTTPServer.shutdown(); } catch (Exception e) { } synchronized (parser) { parser.notifyAll(); } try { logger.close(); } catch (Exception e) { e.printStackTrace(); } } }
Main { public void shutdown() { try { if (hookThread != null) Runtime.getRuntime().removeShutdownHook(hookThread); ledger.close(); log("shutting down"); network.shutdown(); clientHTTPServer.shutdown(); } catch (Exception e) { } synchronized (parser) { parser.notifyAll(); } try { logger.close(); } catch (Exception e) { e.printStackTrace(); } } Main(String[] args); }
Main { public void shutdown() { try { if (hookThread != null) Runtime.getRuntime().removeShutdownHook(hookThread); ledger.close(); log("shutting down"); network.shutdown(); clientHTTPServer.shutdown(); } catch (Exception e) { } synchronized (parser) { parser.notifyAll(); } try { logger.close(); } catch (Exception e) { e.printStackTrace(); } } Main(String[] args); static void main(String[] args); void waitReady(); void shutdown(); void setVerboseLevel(int level); void setUDPVerboseLevel(int level); void restartUDPAdapter(); PublicKey getNodePublicKey(); }
Main { public void shutdown() { try { if (hookThread != null) Runtime.getRuntime().removeShutdownHook(hookThread); ledger.close(); log("shutting down"); network.shutdown(); clientHTTPServer.shutdown(); } catch (Exception e) { } synchronized (parser) { parser.notifyAll(); } try { logger.close(); } catch (Exception e) { e.printStackTrace(); } } Main(String[] args); static void main(String[] args); void waitReady(); void shutdown(); void setVerboseLevel(int level); void setUDPVerboseLevel(int level); void restartUDPAdapter(); PublicKey getNodePublicKey(); static final String NODE_VERSION; final Reporter reporter; final BufferedLogger logger; public NetConfig netConfig; public NetworkV2 network; final Config config; public NodeInfo myInfo; public Node node; public ItemCache cache; public ParcelCache parcelCache; public PaidOperationCache paidOperationCache; }
@Test public void refTest() throws Exception { PrivateKey key = TestKeys.privateKey(0); Contract contract1 = new Contract(key); Contract contract2 = new Contract(key); Contract contract3 = new Contract(key); Contract contract4 = new Contract(key); contract4.seal(); contract1.addNewItems(contract2); contract3.addNewItems(contract4); Reference reference = new Reference(contract2); reference.name = "consent_" + contract4.getId(); reference.type = Reference.TYPE_EXISTING_STATE; List<Object> conditionsList = new ArrayList<>(); conditionsList.add(REFERENCE_CONDITION_PREFIX + "\"" + contract4.getId().toBase64String() + "\""); conditionsList.add(REFERENCE_CONDITION2); Binder conditions = Binder.of(Reference.conditionsModeType.all_of.name(), conditionsList); reference.setConditions(conditions); contract2.addReference(reference); contract2.getIssuer().addRequiredReference(reference, Role.RequiredMode.ALL_OF); contract3.seal(); contract2.seal(); contract1.seal(); Contract c = ContractsService.createBatch(Do.listOf(key), contract1, contract3); TestSpace testSpace = prepareTestSpace(); testSpace.nodes.forEach(n -> n.config.setIsFreeRegistrationsAllowedFromYaml(true)); ItemResult ir = testSpace.client.register(c.getPackedTransaction(), 10000); while (ir.state.isPending()) { ir = testSpace.client.getState(c.getId()); } assertEquals(ir.state, ItemState.APPROVED); testSpace.nodes.forEach(n -> n.shutdown()); }
public void shutdown() { try { if (hookThread != null) Runtime.getRuntime().removeShutdownHook(hookThread); ledger.close(); log("shutting down"); network.shutdown(); clientHTTPServer.shutdown(); } catch (Exception e) { } synchronized (parser) { parser.notifyAll(); } try { logger.close(); } catch (Exception e) { e.printStackTrace(); } }
Main { public void shutdown() { try { if (hookThread != null) Runtime.getRuntime().removeShutdownHook(hookThread); ledger.close(); log("shutting down"); network.shutdown(); clientHTTPServer.shutdown(); } catch (Exception e) { } synchronized (parser) { parser.notifyAll(); } try { logger.close(); } catch (Exception e) { e.printStackTrace(); } } }
Main { public void shutdown() { try { if (hookThread != null) Runtime.getRuntime().removeShutdownHook(hookThread); ledger.close(); log("shutting down"); network.shutdown(); clientHTTPServer.shutdown(); } catch (Exception e) { } synchronized (parser) { parser.notifyAll(); } try { logger.close(); } catch (Exception e) { e.printStackTrace(); } } Main(String[] args); }
Main { public void shutdown() { try { if (hookThread != null) Runtime.getRuntime().removeShutdownHook(hookThread); ledger.close(); log("shutting down"); network.shutdown(); clientHTTPServer.shutdown(); } catch (Exception e) { } synchronized (parser) { parser.notifyAll(); } try { logger.close(); } catch (Exception e) { e.printStackTrace(); } } Main(String[] args); static void main(String[] args); void waitReady(); void shutdown(); void setVerboseLevel(int level); void setUDPVerboseLevel(int level); void restartUDPAdapter(); PublicKey getNodePublicKey(); }
Main { public void shutdown() { try { if (hookThread != null) Runtime.getRuntime().removeShutdownHook(hookThread); ledger.close(); log("shutting down"); network.shutdown(); clientHTTPServer.shutdown(); } catch (Exception e) { } synchronized (parser) { parser.notifyAll(); } try { logger.close(); } catch (Exception e) { e.printStackTrace(); } } Main(String[] args); static void main(String[] args); void waitReady(); void shutdown(); void setVerboseLevel(int level); void setUDPVerboseLevel(int level); void restartUDPAdapter(); PublicKey getNodePublicKey(); static final String NODE_VERSION; final Reporter reporter; final BufferedLogger logger; public NetConfig netConfig; public NetworkV2 network; final Config config; public NodeInfo myInfo; public Node node; public ItemCache cache; public ParcelCache parcelCache; public PaidOperationCache paidOperationCache; }
@Test public void randomReferences() throws Exception { Random random = new Random(); TestSpace testSpace = prepareTestSpace(); testSpace.nodes.forEach(n -> n.config.setIsFreeRegistrationsAllowedFromYaml(true)); final int CONTRACTS_IN_BATCH = 20; final int REFS_COUNT = 1000; List<PrivateKey> keys100 = new ArrayList<>(); for (int i = 0; i < CONTRACTS_IN_BATCH; ++i) keys100.add(new PrivateKey(2048)); List<Contract> contracts100 = new ArrayList<>(); for (int i = 0; i < CONTRACTS_IN_BATCH; ++i) { Contract c = new Contract(keys100.get(i)); c.getStateData().put("some_value", 9000 + random.nextInt(1000)); contracts100.add(c); } Map<Integer, Integer> refsCasesCounter = new HashMap<>(); for (int i = 1; i < REFS_COUNT; ++i) { int refForContract = random.nextInt(keys100.size()); int refCase = random.nextInt(4); refsCasesCounter.put(refCase, refsCasesCounter.getOrDefault(refCase, 0) + 1); Reference ref = new Reference(contracts100.get(refForContract)); switch (refCase) { case 0: ref.type = Reference.TYPE_EXISTING_STATE; ref.setConditions(Binder.of(Reference.conditionsModeType.all_of.name(), asList("ref.issuer==" + keys100.get(random.nextInt(keys100.size())).getPublicKey().getShortAddress()))); break; case 1: ref.type = Reference.TYPE_EXISTING_DEFINITION; ref.setConditions(Binder.of(Reference.conditionsModeType.all_of.name(), asList("ref.owner==" + keys100.get(random.nextInt(keys100.size())).getPublicKey().getLongAddress()))); break; case 2: ref.type = Reference.TYPE_EXISTING_STATE; ref.setConditions(Binder.of( Reference.conditionsModeType.all_of.name(), asList( "ref.state.data.some_value==" + contracts100.get(random.nextInt(contracts100.size())).getStateData().getStringOrThrow("some_value") ))); break; case 3: ref.type = Reference.TYPE_EXISTING_STATE; ref.setConditions(Binder.of( Reference.conditionsModeType.all_of.name(), asList("ref.state.data.some_value<=1000"))); break; } contracts100.get(refForContract).addReference(ref); } System.out.println("\nrefs cases:"); refsCasesCounter.forEach((k, v) -> System.out.println(" case " + k + ": " + v)); Contract batch = new Contract(new PrivateKey(2048)); for (int i = 0; i < keys100.size(); ++i) batch.addNewItems(contracts100.get(i)); batch.seal(); ItemResult ir = testSpace.client.register(batch.getPackedTransaction(), 30000); if (ir.errors.size() > 0) { System.out.println("\n\nerrors:"); ir.errors.forEach(e -> System.out.println(" " + e)); System.out.println(); } assertEquals(ItemState.DECLINED, ir.state); testSpace.nodes.forEach(n -> n.shutdown()); }
public void shutdown() { try { if (hookThread != null) Runtime.getRuntime().removeShutdownHook(hookThread); ledger.close(); log("shutting down"); network.shutdown(); clientHTTPServer.shutdown(); } catch (Exception e) { } synchronized (parser) { parser.notifyAll(); } try { logger.close(); } catch (Exception e) { e.printStackTrace(); } }
Main { public void shutdown() { try { if (hookThread != null) Runtime.getRuntime().removeShutdownHook(hookThread); ledger.close(); log("shutting down"); network.shutdown(); clientHTTPServer.shutdown(); } catch (Exception e) { } synchronized (parser) { parser.notifyAll(); } try { logger.close(); } catch (Exception e) { e.printStackTrace(); } } }
Main { public void shutdown() { try { if (hookThread != null) Runtime.getRuntime().removeShutdownHook(hookThread); ledger.close(); log("shutting down"); network.shutdown(); clientHTTPServer.shutdown(); } catch (Exception e) { } synchronized (parser) { parser.notifyAll(); } try { logger.close(); } catch (Exception e) { e.printStackTrace(); } } Main(String[] args); }
Main { public void shutdown() { try { if (hookThread != null) Runtime.getRuntime().removeShutdownHook(hookThread); ledger.close(); log("shutting down"); network.shutdown(); clientHTTPServer.shutdown(); } catch (Exception e) { } synchronized (parser) { parser.notifyAll(); } try { logger.close(); } catch (Exception e) { e.printStackTrace(); } } Main(String[] args); static void main(String[] args); void waitReady(); void shutdown(); void setVerboseLevel(int level); void setUDPVerboseLevel(int level); void restartUDPAdapter(); PublicKey getNodePublicKey(); }
Main { public void shutdown() { try { if (hookThread != null) Runtime.getRuntime().removeShutdownHook(hookThread); ledger.close(); log("shutting down"); network.shutdown(); clientHTTPServer.shutdown(); } catch (Exception e) { } synchronized (parser) { parser.notifyAll(); } try { logger.close(); } catch (Exception e) { e.printStackTrace(); } } Main(String[] args); static void main(String[] args); void waitReady(); void shutdown(); void setVerboseLevel(int level); void setUDPVerboseLevel(int level); void restartUDPAdapter(); PublicKey getNodePublicKey(); static final String NODE_VERSION; final Reporter reporter; final BufferedLogger logger; public NetConfig netConfig; public NetworkV2 network; final Config config; public NodeInfo myInfo; public Node node; public ItemCache cache; public ParcelCache parcelCache; public PaidOperationCache paidOperationCache; }
@Test public void getStateWithNoLedgerCache() throws Exception { TestSpace testSpace = prepareTestSpace(TestKeys.privateKey(0)); testSpace.nodes.forEach(m -> m.config.setIsFreeRegistrationsAllowedFromYaml(true)); testSpace.nodes.forEach(m -> ((PostgresLedger) m.node.getLedger()).enableCache(false)); testSpace.nodes.remove(testSpace.nodes.size() - 1).shutdown(); Thread.sleep(4000); Contract rev1 = new Contract(TestKeys.privateKey(0)); rev1.getStateData().set("field1", 33); Permission permission = new ChangeNumberPermission(rev1.getOwner(), Binder.of("field_name", "field1")); rev1.addPermission(permission); rev1.seal(); ItemResult ir1 = testSpace.client.register(rev1.getPackedTransaction(), 5000); assertEquals(ItemState.APPROVED, ir1.state); Contract rev2 = rev1.createRevision(); rev2.getStateData().set("field1", 34); rev2.addSignerKey(TestKeys.privateKey(0)); rev2.seal(); ItemResult ir2 = testSpace.client.register(rev2.getPackedTransaction(), 5000); assertEquals(ItemState.APPROVED, ir2.state); ir1 = testSpace.client.register(rev1.getPackedTransaction(), 5000); assertEquals(ItemState.REVOKED, ir1.state); testSpace.nodes.forEach(m -> m.shutdown()); }
public void shutdown() { try { if (hookThread != null) Runtime.getRuntime().removeShutdownHook(hookThread); ledger.close(); log("shutting down"); network.shutdown(); clientHTTPServer.shutdown(); } catch (Exception e) { } synchronized (parser) { parser.notifyAll(); } try { logger.close(); } catch (Exception e) { e.printStackTrace(); } }
Main { public void shutdown() { try { if (hookThread != null) Runtime.getRuntime().removeShutdownHook(hookThread); ledger.close(); log("shutting down"); network.shutdown(); clientHTTPServer.shutdown(); } catch (Exception e) { } synchronized (parser) { parser.notifyAll(); } try { logger.close(); } catch (Exception e) { e.printStackTrace(); } } }
Main { public void shutdown() { try { if (hookThread != null) Runtime.getRuntime().removeShutdownHook(hookThread); ledger.close(); log("shutting down"); network.shutdown(); clientHTTPServer.shutdown(); } catch (Exception e) { } synchronized (parser) { parser.notifyAll(); } try { logger.close(); } catch (Exception e) { e.printStackTrace(); } } Main(String[] args); }
Main { public void shutdown() { try { if (hookThread != null) Runtime.getRuntime().removeShutdownHook(hookThread); ledger.close(); log("shutting down"); network.shutdown(); clientHTTPServer.shutdown(); } catch (Exception e) { } synchronized (parser) { parser.notifyAll(); } try { logger.close(); } catch (Exception e) { e.printStackTrace(); } } Main(String[] args); static void main(String[] args); void waitReady(); void shutdown(); void setVerboseLevel(int level); void setUDPVerboseLevel(int level); void restartUDPAdapter(); PublicKey getNodePublicKey(); }
Main { public void shutdown() { try { if (hookThread != null) Runtime.getRuntime().removeShutdownHook(hookThread); ledger.close(); log("shutting down"); network.shutdown(); clientHTTPServer.shutdown(); } catch (Exception e) { } synchronized (parser) { parser.notifyAll(); } try { logger.close(); } catch (Exception e) { e.printStackTrace(); } } Main(String[] args); static void main(String[] args); void waitReady(); void shutdown(); void setVerboseLevel(int level); void setUDPVerboseLevel(int level); void restartUDPAdapter(); PublicKey getNodePublicKey(); static final String NODE_VERSION; final Reporter reporter; final BufferedLogger logger; public NetConfig netConfig; public NetworkV2 network; final Config config; public NodeInfo myInfo; public Node node; public ItemCache cache; public ParcelCache parcelCache; public PaidOperationCache paidOperationCache; }
@Test public void checkWhiteListKey() throws Exception { List<Main> mm = new ArrayList<>(); for (int i = 0; i < 3; i++) { mm.add(createMain("node" + (i + 1), false)); } Main main = mm.get(0); PrivateKey myKey = TestKeys.privateKey(3); Client client = null; try { client = new Client(myKey, main.myInfo, null); } catch (Exception e) { System.out.println("prepareClient exception: " + e.toString()); } Contract testContract = new Contract(myKey); for (int i = 0; i < 10; i++) { Contract nc = new Contract(myKey); nc.seal(); testContract.addNewItems(nc); } testContract.seal(); assertTrue(testContract.isOk()); Parcel parcel = createParcelWithFreshU(client, testContract, Do.listOf(myKey)); ItemResult itemResult = client.registerParcelWithState(parcel.pack(), 15000); System.out.println(">> state: " + itemResult); assertEquals(ItemState.APPROVED, itemResult.state); mm.forEach(x -> x.shutdown()); }
public void shutdown() { try { if (hookThread != null) Runtime.getRuntime().removeShutdownHook(hookThread); ledger.close(); log("shutting down"); network.shutdown(); clientHTTPServer.shutdown(); } catch (Exception e) { } synchronized (parser) { parser.notifyAll(); } try { logger.close(); } catch (Exception e) { e.printStackTrace(); } }
Main { public void shutdown() { try { if (hookThread != null) Runtime.getRuntime().removeShutdownHook(hookThread); ledger.close(); log("shutting down"); network.shutdown(); clientHTTPServer.shutdown(); } catch (Exception e) { } synchronized (parser) { parser.notifyAll(); } try { logger.close(); } catch (Exception e) { e.printStackTrace(); } } }
Main { public void shutdown() { try { if (hookThread != null) Runtime.getRuntime().removeShutdownHook(hookThread); ledger.close(); log("shutting down"); network.shutdown(); clientHTTPServer.shutdown(); } catch (Exception e) { } synchronized (parser) { parser.notifyAll(); } try { logger.close(); } catch (Exception e) { e.printStackTrace(); } } Main(String[] args); }
Main { public void shutdown() { try { if (hookThread != null) Runtime.getRuntime().removeShutdownHook(hookThread); ledger.close(); log("shutting down"); network.shutdown(); clientHTTPServer.shutdown(); } catch (Exception e) { } synchronized (parser) { parser.notifyAll(); } try { logger.close(); } catch (Exception e) { e.printStackTrace(); } } Main(String[] args); static void main(String[] args); void waitReady(); void shutdown(); void setVerboseLevel(int level); void setUDPVerboseLevel(int level); void restartUDPAdapter(); PublicKey getNodePublicKey(); }
Main { public void shutdown() { try { if (hookThread != null) Runtime.getRuntime().removeShutdownHook(hookThread); ledger.close(); log("shutting down"); network.shutdown(); clientHTTPServer.shutdown(); } catch (Exception e) { } synchronized (parser) { parser.notifyAll(); } try { logger.close(); } catch (Exception e) { e.printStackTrace(); } } Main(String[] args); static void main(String[] args); void waitReady(); void shutdown(); void setVerboseLevel(int level); void setUDPVerboseLevel(int level); void restartUDPAdapter(); PublicKey getNodePublicKey(); static final String NODE_VERSION; final Reporter reporter; final BufferedLogger logger; public NetConfig netConfig; public NetworkV2 network; final Config config; public NodeInfo myInfo; public Node node; public ItemCache cache; public ParcelCache parcelCache; public PaidOperationCache paidOperationCache; }
@Test public void checkNotWhiteListKey() throws Exception { List<Main> mm = new ArrayList<>(); for (int i = 0; i < 3; i++) { mm.add(createMain("node" + (i + 1), false)); } mm.forEach(x -> { x.config.getKeysWhiteList().clear(); x.config.getAddressesWhiteList().clear(); }); Main main = mm.get(0); PrivateKey myKey = TestKeys.privateKey(3); Client client = null; try { client = new Client(myKey, main.myInfo, null); } catch (Exception e) { System.out.println("prepareClient exception: " + e.toString()); } Contract testContract = new Contract(myKey); for (int i = 0; i < 10; i++) { Contract nc = new Contract(myKey); nc.seal(); testContract.addNewItems(nc); } testContract.seal(); assertTrue(testContract.isOk()); Set<PublicKey> ownerKeys = new HashSet(); Collection<PrivateKey> keys = Do.listOf(myKey); keys.stream().forEach(key -> ownerKeys.add(key.getPublicKey())); Contract stepaU = InnerContractsService.createFreshU(100000000, ownerKeys); stepaU.check(); stepaU.traceErrors(); PrivateKey clientPrivateKey = client.getSession().getPrivateKey(); PrivateKey newPrivateKey = new PrivateKey(Do.read("./src/test_contracts/keys/u_key.private.unikey")); client.getSession().setPrivateKey(newPrivateKey); client.restart(); ItemResult itemResult = client.register(stepaU.getPackedTransaction(), 5000); client.getSession().setPrivateKey(clientPrivateKey); client.restart(); assertEquals(itemResult.errors.size(), 1); assertEquals(itemResult.errors.get(0).getMessage(), "command needs client key from whitelist"); assertEquals(ItemState.UNDEFINED, itemResult.state); Set<PrivateKey> keySet = new HashSet<>(); keySet.addAll(keys); Parcel parcel = ContractsService.createParcel(testContract, stepaU, 150, keySet); client.registerParcelWithState(parcel.pack(), 15000); itemResult = client.getState(parcel.getPayloadContract().getId()); System.out.println(">> state: " + itemResult); assertEquals(ItemState.UNDEFINED, itemResult.state); mm.forEach(x -> x.shutdown()); }
public void shutdown() { try { if (hookThread != null) Runtime.getRuntime().removeShutdownHook(hookThread); ledger.close(); log("shutting down"); network.shutdown(); clientHTTPServer.shutdown(); } catch (Exception e) { } synchronized (parser) { parser.notifyAll(); } try { logger.close(); } catch (Exception e) { e.printStackTrace(); } }
Main { public void shutdown() { try { if (hookThread != null) Runtime.getRuntime().removeShutdownHook(hookThread); ledger.close(); log("shutting down"); network.shutdown(); clientHTTPServer.shutdown(); } catch (Exception e) { } synchronized (parser) { parser.notifyAll(); } try { logger.close(); } catch (Exception e) { e.printStackTrace(); } } }
Main { public void shutdown() { try { if (hookThread != null) Runtime.getRuntime().removeShutdownHook(hookThread); ledger.close(); log("shutting down"); network.shutdown(); clientHTTPServer.shutdown(); } catch (Exception e) { } synchronized (parser) { parser.notifyAll(); } try { logger.close(); } catch (Exception e) { e.printStackTrace(); } } Main(String[] args); }
Main { public void shutdown() { try { if (hookThread != null) Runtime.getRuntime().removeShutdownHook(hookThread); ledger.close(); log("shutting down"); network.shutdown(); clientHTTPServer.shutdown(); } catch (Exception e) { } synchronized (parser) { parser.notifyAll(); } try { logger.close(); } catch (Exception e) { e.printStackTrace(); } } Main(String[] args); static void main(String[] args); void waitReady(); void shutdown(); void setVerboseLevel(int level); void setUDPVerboseLevel(int level); void restartUDPAdapter(); PublicKey getNodePublicKey(); }
Main { public void shutdown() { try { if (hookThread != null) Runtime.getRuntime().removeShutdownHook(hookThread); ledger.close(); log("shutting down"); network.shutdown(); clientHTTPServer.shutdown(); } catch (Exception e) { } synchronized (parser) { parser.notifyAll(); } try { logger.close(); } catch (Exception e) { e.printStackTrace(); } } Main(String[] args); static void main(String[] args); void waitReady(); void shutdown(); void setVerboseLevel(int level); void setUDPVerboseLevel(int level); void restartUDPAdapter(); PublicKey getNodePublicKey(); static final String NODE_VERSION; final Reporter reporter; final BufferedLogger logger; public NetConfig netConfig; public NetworkV2 network; final Config config; public NodeInfo myInfo; public Node node; public ItemCache cache; public ParcelCache parcelCache; public PaidOperationCache paidOperationCache; }
@Test public void checkWhiteListAddress() throws Exception { List<Main> mm = new ArrayList<>(); for (int i = 0; i < 3; i++) { mm.add(createMain("node" + (i + 1), false)); } PrivateKey newPrivateKey = new PrivateKey(Do.read("./src/test_contracts/keys/u_key.private.unikey")); mm.forEach(x -> { x.config.getKeysWhiteList().clear(); x.config.getAddressesWhiteList().clear(); }); mm.forEach(x -> x.config.getAddressesWhiteList().add(new KeyAddress(newPrivateKey.getPublicKey(), 0, true))); Main main = mm.get(0); PrivateKey myKey = TestKeys.privateKey(3); Client client = null; try { client = new Client(myKey, main.myInfo, null); } catch (Exception e) { System.out.println("prepareClient exception: " + e.toString()); } Contract testContract = new Contract(myKey); for (int i = 0; i < 10; i++) { Contract nc = new Contract(myKey); nc.seal(); testContract.addNewItems(nc); } testContract.seal(); assertTrue(testContract.isOk()); Set<PublicKey> ownerKeys = new HashSet(); Collection<PrivateKey> keys = Do.listOf(myKey); keys.stream().forEach(key -> ownerKeys.add(key.getPublicKey())); Contract stepaU = InnerContractsService.createFreshU(100000000, ownerKeys); stepaU.check(); stepaU.traceErrors(); PrivateKey clientPrivateKey = client.getSession().getPrivateKey(); client.getSession().setPrivateKey(newPrivateKey); client.restart(); ItemResult itemResult = client.register(stepaU.getPackedTransaction(), 5000); client.getSession().setPrivateKey(clientPrivateKey); client.restart(); assertEquals(ItemState.APPROVED, itemResult.state); Set<PrivateKey> keySet = new HashSet<>(); keySet.addAll(keys); Parcel parcel = ContractsService.createParcel(testContract, stepaU, 150, keySet); client.registerParcelWithState(parcel.pack(), 15000); itemResult = client.getState(parcel.getPayloadContract().getId()); System.out.println(">> state: " + itemResult); assertEquals(ItemState.APPROVED, itemResult.state); mm.forEach(x -> x.shutdown()); }
public void shutdown() { try { if (hookThread != null) Runtime.getRuntime().removeShutdownHook(hookThread); ledger.close(); log("shutting down"); network.shutdown(); clientHTTPServer.shutdown(); } catch (Exception e) { } synchronized (parser) { parser.notifyAll(); } try { logger.close(); } catch (Exception e) { e.printStackTrace(); } }
Main { public void shutdown() { try { if (hookThread != null) Runtime.getRuntime().removeShutdownHook(hookThread); ledger.close(); log("shutting down"); network.shutdown(); clientHTTPServer.shutdown(); } catch (Exception e) { } synchronized (parser) { parser.notifyAll(); } try { logger.close(); } catch (Exception e) { e.printStackTrace(); } } }
Main { public void shutdown() { try { if (hookThread != null) Runtime.getRuntime().removeShutdownHook(hookThread); ledger.close(); log("shutting down"); network.shutdown(); clientHTTPServer.shutdown(); } catch (Exception e) { } synchronized (parser) { parser.notifyAll(); } try { logger.close(); } catch (Exception e) { e.printStackTrace(); } } Main(String[] args); }
Main { public void shutdown() { try { if (hookThread != null) Runtime.getRuntime().removeShutdownHook(hookThread); ledger.close(); log("shutting down"); network.shutdown(); clientHTTPServer.shutdown(); } catch (Exception e) { } synchronized (parser) { parser.notifyAll(); } try { logger.close(); } catch (Exception e) { e.printStackTrace(); } } Main(String[] args); static void main(String[] args); void waitReady(); void shutdown(); void setVerboseLevel(int level); void setUDPVerboseLevel(int level); void restartUDPAdapter(); PublicKey getNodePublicKey(); }
Main { public void shutdown() { try { if (hookThread != null) Runtime.getRuntime().removeShutdownHook(hookThread); ledger.close(); log("shutting down"); network.shutdown(); clientHTTPServer.shutdown(); } catch (Exception e) { } synchronized (parser) { parser.notifyAll(); } try { logger.close(); } catch (Exception e) { e.printStackTrace(); } } Main(String[] args); static void main(String[] args); void waitReady(); void shutdown(); void setVerboseLevel(int level); void setUDPVerboseLevel(int level); void restartUDPAdapter(); PublicKey getNodePublicKey(); static final String NODE_VERSION; final Reporter reporter; final BufferedLogger logger; public NetConfig netConfig; public NetworkV2 network; final Config config; public NodeInfo myInfo; public Node node; public ItemCache cache; public ParcelCache parcelCache; public PaidOperationCache paidOperationCache; }
@Test public void encrypt() throws Exception { AbstractPublicKey rsaPublicKey = oaepSpec.getPublicKey(); ((RSAOAEPPublicKey) rsaPublicKey).resetEncryptor(); assertArrayEquals(rsaPublicKey.encrypt(oaepSpec.M), oaepSpec.C); }
@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 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 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); }
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); }
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; }
@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); }
public String returnMessage() { return message; }
StandaloneBean { public String returnMessage() { return message; } }
StandaloneBean { public String returnMessage() { return message; } }
StandaloneBean { public String returnMessage() { return message; } String returnMessage(); }
StandaloneBean { public String returnMessage() { return message; } String returnMessage(); }
@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()); }
@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; }
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; } }
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; } }
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(); }
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(); }
@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)")); } }
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 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 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(); }
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); }
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); }
@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()); }
@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; }
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; } }
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; } }
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(); }
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(); }
@Test void testAddedOrTerm1() { MetalNamesConfig.Builder builder = new MetalNamesConfig.Builder(); builder.metalWords(Arrays.asList("hetfield", "metallica", "pantera")); MetalNamesConfig config = new MetalNamesConfig(builder); Chain<Searcher> myChain = new Chain<>(new MinimalQueryInserter(), new MetalSearcher(config)); Execution.Context context = Execution.Context.createContextStub(); Execution execution = new Execution(myChain, context); Result result = execution.search(metalQuery); System.out.println(result.getContext(false).getTrace()); assertAddedOrTerm(metalQuery.getModel().getQueryTree().getRoot()); }
@Override public Result search(Query query, Execution execution) { QueryTree tree = query.getModel().getQueryTree(); if (isMetalQuery(tree)) { OrItem orItem = new OrItem(); orItem.addItem(tree.getRoot()); orItem.addItem(new WordItem("metal", "album")); tree.setRoot(orItem); query.trace("Metal added", true, 2); } return execution.search(query); }
MetalSearcher extends Searcher { @Override public Result search(Query query, Execution execution) { QueryTree tree = query.getModel().getQueryTree(); if (isMetalQuery(tree)) { OrItem orItem = new OrItem(); orItem.addItem(tree.getRoot()); orItem.addItem(new WordItem("metal", "album")); tree.setRoot(orItem); query.trace("Metal added", true, 2); } return execution.search(query); } }
MetalSearcher extends Searcher { @Override public Result search(Query query, Execution execution) { QueryTree tree = query.getModel().getQueryTree(); if (isMetalQuery(tree)) { OrItem orItem = new OrItem(); orItem.addItem(tree.getRoot()); orItem.addItem(new WordItem("metal", "album")); tree.setRoot(orItem); query.trace("Metal added", true, 2); } return execution.search(query); } @Inject MetalSearcher(MetalNamesConfig config); MetalSearcher(); }
MetalSearcher extends Searcher { @Override public Result search(Query query, Execution execution) { QueryTree tree = query.getModel().getQueryTree(); if (isMetalQuery(tree)) { OrItem orItem = new OrItem(); orItem.addItem(tree.getRoot()); orItem.addItem(new WordItem("metal", "album")); tree.setRoot(orItem); query.trace("Metal added", true, 2); } return execution.search(query); } @Inject MetalSearcher(MetalNamesConfig config); MetalSearcher(); @Override Result search(Query query, Execution execution); }
MetalSearcher extends Searcher { @Override public Result search(Query query, Execution execution) { QueryTree tree = query.getModel().getQueryTree(); if (isMetalQuery(tree)) { OrItem orItem = new OrItem(); orItem.addItem(tree.getRoot()); orItem.addItem(new WordItem("metal", "album")); tree.setRoot(orItem); query.trace("Metal added", true, 2); } return execution.search(query); } @Inject MetalSearcher(MetalNamesConfig config); MetalSearcher(); @Override Result search(Query query, Execution execution); }
@Test void testAddedOrTerm2() { try (Application app = Application.fromApplicationPackage( FileSystems.getDefault().getPath("src/main/application"), Networking.disable)) { Search search = app.getJDisc("default").search(); Result result = search.process(ComponentSpecification.fromString("metalchain"), metalQuery); System.out.println(result.getContext(false).getTrace()); assertAddedOrTerm(metalQuery.getModel().getQueryTree().getRoot()); } }
@Override public Result search(Query query, Execution execution) { QueryTree tree = query.getModel().getQueryTree(); if (isMetalQuery(tree)) { OrItem orItem = new OrItem(); orItem.addItem(tree.getRoot()); orItem.addItem(new WordItem("metal", "album")); tree.setRoot(orItem); query.trace("Metal added", true, 2); } return execution.search(query); }
MetalSearcher extends Searcher { @Override public Result search(Query query, Execution execution) { QueryTree tree = query.getModel().getQueryTree(); if (isMetalQuery(tree)) { OrItem orItem = new OrItem(); orItem.addItem(tree.getRoot()); orItem.addItem(new WordItem("metal", "album")); tree.setRoot(orItem); query.trace("Metal added", true, 2); } return execution.search(query); } }
MetalSearcher extends Searcher { @Override public Result search(Query query, Execution execution) { QueryTree tree = query.getModel().getQueryTree(); if (isMetalQuery(tree)) { OrItem orItem = new OrItem(); orItem.addItem(tree.getRoot()); orItem.addItem(new WordItem("metal", "album")); tree.setRoot(orItem); query.trace("Metal added", true, 2); } return execution.search(query); } @Inject MetalSearcher(MetalNamesConfig config); MetalSearcher(); }
MetalSearcher extends Searcher { @Override public Result search(Query query, Execution execution) { QueryTree tree = query.getModel().getQueryTree(); if (isMetalQuery(tree)) { OrItem orItem = new OrItem(); orItem.addItem(tree.getRoot()); orItem.addItem(new WordItem("metal", "album")); tree.setRoot(orItem); query.trace("Metal added", true, 2); } return execution.search(query); } @Inject MetalSearcher(MetalNamesConfig config); MetalSearcher(); @Override Result search(Query query, Execution execution); }
MetalSearcher extends Searcher { @Override public Result search(Query query, Execution execution) { QueryTree tree = query.getModel().getQueryTree(); if (isMetalQuery(tree)) { OrItem orItem = new OrItem(); orItem.addItem(tree.getRoot()); orItem.addItem(new WordItem("metal", "album")); tree.setRoot(orItem); query.trace("Metal added", true, 2); } return execution.search(query); } @Inject MetalSearcher(MetalNamesConfig config); MetalSearcher(); @Override Result search(Query query, Execution execution); }
@Test void testWithMockBackendProducingHits() { DocumentSourceSearcher docSource = new DocumentSourceSearcher(); Query testQuery = new Query(); testQuery.setTraceLevel(6); testQuery.getModel().getQueryTree().setRoot(new WordItem("drum","album")); Result mockResult = new Result(testQuery); mockResult.hits().add(new Hit("hit:1", 0.9)); mockResult.hits().add(new Hit("hit:2", 0.8)); docSource.addResult(testQuery, mockResult); Chain<Searcher> myChain = new Chain<>(new MetalSearcher(), docSource); Execution.Context context = Execution.Context.createContextStub(); Execution execution = new Execution(myChain, context); Result result = execution.search(testQuery); System.out.println(result.getContext(false).getTrace()); assertEquals(2, result.hits().size()); }
@Override public Result search(Query query, Execution execution) { QueryTree tree = query.getModel().getQueryTree(); if (isMetalQuery(tree)) { OrItem orItem = new OrItem(); orItem.addItem(tree.getRoot()); orItem.addItem(new WordItem("metal", "album")); tree.setRoot(orItem); query.trace("Metal added", true, 2); } return execution.search(query); }
MetalSearcher extends Searcher { @Override public Result search(Query query, Execution execution) { QueryTree tree = query.getModel().getQueryTree(); if (isMetalQuery(tree)) { OrItem orItem = new OrItem(); orItem.addItem(tree.getRoot()); orItem.addItem(new WordItem("metal", "album")); tree.setRoot(orItem); query.trace("Metal added", true, 2); } return execution.search(query); } }
MetalSearcher extends Searcher { @Override public Result search(Query query, Execution execution) { QueryTree tree = query.getModel().getQueryTree(); if (isMetalQuery(tree)) { OrItem orItem = new OrItem(); orItem.addItem(tree.getRoot()); orItem.addItem(new WordItem("metal", "album")); tree.setRoot(orItem); query.trace("Metal added", true, 2); } return execution.search(query); } @Inject MetalSearcher(MetalNamesConfig config); MetalSearcher(); }
MetalSearcher extends Searcher { @Override public Result search(Query query, Execution execution) { QueryTree tree = query.getModel().getQueryTree(); if (isMetalQuery(tree)) { OrItem orItem = new OrItem(); orItem.addItem(tree.getRoot()); orItem.addItem(new WordItem("metal", "album")); tree.setRoot(orItem); query.trace("Metal added", true, 2); } return execution.search(query); } @Inject MetalSearcher(MetalNamesConfig config); MetalSearcher(); @Override Result search(Query query, Execution execution); }
MetalSearcher extends Searcher { @Override public Result search(Query query, Execution execution) { QueryTree tree = query.getModel().getQueryTree(); if (isMetalQuery(tree)) { OrItem orItem = new OrItem(); orItem.addItem(tree.getRoot()); orItem.addItem(new WordItem("metal", "album")); tree.setRoot(orItem); query.trace("Metal added", true, 2); } return execution.search(query); } @Inject MetalSearcher(MetalNamesConfig config); MetalSearcher(); @Override Result search(Query query, Execution execution); }
@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()); } }
@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); }
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); } }
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); } }
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); }
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); }
@Test public void requireThatTensorExpressionCanBeEvaluated() throws ParseException { MapContext context = new MapContext(); context.put("t1", new TensorValue(Tensor.from("tensor(x{}):{{x:0}:1,{x:1}:2}"))); context.put("t2", new TensorValue(Tensor.from("tensor(x{}):{{x:0}:2,{x:1}:3}"))); Value v = ExpressionEvaluator.evaluate("t1 * t2", context); assertTrue(v instanceof TensorValue); assertEquals("tensor(x{})", v.asTensor().type().toString()); assertEquals("tensor(x{}):{0:2.0,1:6.0}", v.toString()); }
public static String evaluate(String json) throws IOException { ObjectMapper m = new ObjectMapper(); JsonNode root = m.readTree(json); if (root == null) { return error("Could not parse json to evaluate"); } if (!root.has("expression")) { return error("Required field missing: expression"); } String expression = root.get("expression").asText(); try { MapContext context = new MapContext(); if (root.has("arguments")) { JsonNode arguments = root.get("arguments"); if (!arguments.isArray()) { return error("Invalid JSON format: arguments must be an array"); } for (JsonNode argument : arguments) { if (!argument.isObject()) { return error("Invalid JSON format: argument must be an object"); } if (!argument.has("name")) { return error("Invalid JSON format: argument must have a name"); } if (!argument.has("type")) { return error("Invalid JSON format: argument must have a type"); } if (!argument.has("value")) { return error("Invalid JSON format: argument must have a value"); } String name = argument.get("name").asText(); String type = argument.get("type").asText(); Value value; if ("string".equalsIgnoreCase(type)) { value = new StringValue(argument.get("value").asText()); } else if ("double".equalsIgnoreCase(type)) { value = new DoubleValue(argument.get("value").asDouble()); } else if ("boolean".equalsIgnoreCase(type)) { value = new BooleanValue(argument.get("value").asBoolean()); } else if (type.toLowerCase().startsWith("tensor(")) { value = new TensorValue(Tensor.from(type + ":" + argument.get("value").asText())); } else { return error("Unknown argument type: " + type); } context.put(name, value); } } Value value = evaluate(expression, context); String valueType = valueType(value); if (valueType.equals("unknown")) { return error("Evaluation of ranking expression returned unknown value type"); } return String.join("\n", "{", " \"type\": \"" + valueType + "\",", " \"value\": " + valueValue(value), "}"); } catch (ParseException e) { return error("Could not parse expression: " + expression); } catch (IllegalArgumentException e) { return error(e.getMessage()); } }
ExpressionEvaluator { public static String evaluate(String json) throws IOException { ObjectMapper m = new ObjectMapper(); JsonNode root = m.readTree(json); if (root == null) { return error("Could not parse json to evaluate"); } if (!root.has("expression")) { return error("Required field missing: expression"); } String expression = root.get("expression").asText(); try { MapContext context = new MapContext(); if (root.has("arguments")) { JsonNode arguments = root.get("arguments"); if (!arguments.isArray()) { return error("Invalid JSON format: arguments must be an array"); } for (JsonNode argument : arguments) { if (!argument.isObject()) { return error("Invalid JSON format: argument must be an object"); } if (!argument.has("name")) { return error("Invalid JSON format: argument must have a name"); } if (!argument.has("type")) { return error("Invalid JSON format: argument must have a type"); } if (!argument.has("value")) { return error("Invalid JSON format: argument must have a value"); } String name = argument.get("name").asText(); String type = argument.get("type").asText(); Value value; if ("string".equalsIgnoreCase(type)) { value = new StringValue(argument.get("value").asText()); } else if ("double".equalsIgnoreCase(type)) { value = new DoubleValue(argument.get("value").asDouble()); } else if ("boolean".equalsIgnoreCase(type)) { value = new BooleanValue(argument.get("value").asBoolean()); } else if (type.toLowerCase().startsWith("tensor(")) { value = new TensorValue(Tensor.from(type + ":" + argument.get("value").asText())); } else { return error("Unknown argument type: " + type); } context.put(name, value); } } Value value = evaluate(expression, context); String valueType = valueType(value); if (valueType.equals("unknown")) { return error("Evaluation of ranking expression returned unknown value type"); } return String.join("\n", "{", " \"type\": \"" + valueType + "\",", " \"value\": " + valueValue(value), "}"); } catch (ParseException e) { return error("Could not parse expression: " + expression); } catch (IllegalArgumentException e) { return error(e.getMessage()); } } }
ExpressionEvaluator { public static String evaluate(String json) throws IOException { ObjectMapper m = new ObjectMapper(); JsonNode root = m.readTree(json); if (root == null) { return error("Could not parse json to evaluate"); } if (!root.has("expression")) { return error("Required field missing: expression"); } String expression = root.get("expression").asText(); try { MapContext context = new MapContext(); if (root.has("arguments")) { JsonNode arguments = root.get("arguments"); if (!arguments.isArray()) { return error("Invalid JSON format: arguments must be an array"); } for (JsonNode argument : arguments) { if (!argument.isObject()) { return error("Invalid JSON format: argument must be an object"); } if (!argument.has("name")) { return error("Invalid JSON format: argument must have a name"); } if (!argument.has("type")) { return error("Invalid JSON format: argument must have a type"); } if (!argument.has("value")) { return error("Invalid JSON format: argument must have a value"); } String name = argument.get("name").asText(); String type = argument.get("type").asText(); Value value; if ("string".equalsIgnoreCase(type)) { value = new StringValue(argument.get("value").asText()); } else if ("double".equalsIgnoreCase(type)) { value = new DoubleValue(argument.get("value").asDouble()); } else if ("boolean".equalsIgnoreCase(type)) { value = new BooleanValue(argument.get("value").asBoolean()); } else if (type.toLowerCase().startsWith("tensor(")) { value = new TensorValue(Tensor.from(type + ":" + argument.get("value").asText())); } else { return error("Unknown argument type: " + type); } context.put(name, value); } } Value value = evaluate(expression, context); String valueType = valueType(value); if (valueType.equals("unknown")) { return error("Evaluation of ranking expression returned unknown value type"); } return String.join("\n", "{", " \"type\": \"" + valueType + "\",", " \"value\": " + valueValue(value), "}"); } catch (ParseException e) { return error("Could not parse expression: " + expression); } catch (IllegalArgumentException e) { return error(e.getMessage()); } } }
ExpressionEvaluator { public static String evaluate(String json) throws IOException { ObjectMapper m = new ObjectMapper(); JsonNode root = m.readTree(json); if (root == null) { return error("Could not parse json to evaluate"); } if (!root.has("expression")) { return error("Required field missing: expression"); } String expression = root.get("expression").asText(); try { MapContext context = new MapContext(); if (root.has("arguments")) { JsonNode arguments = root.get("arguments"); if (!arguments.isArray()) { return error("Invalid JSON format: arguments must be an array"); } for (JsonNode argument : arguments) { if (!argument.isObject()) { return error("Invalid JSON format: argument must be an object"); } if (!argument.has("name")) { return error("Invalid JSON format: argument must have a name"); } if (!argument.has("type")) { return error("Invalid JSON format: argument must have a type"); } if (!argument.has("value")) { return error("Invalid JSON format: argument must have a value"); } String name = argument.get("name").asText(); String type = argument.get("type").asText(); Value value; if ("string".equalsIgnoreCase(type)) { value = new StringValue(argument.get("value").asText()); } else if ("double".equalsIgnoreCase(type)) { value = new DoubleValue(argument.get("value").asDouble()); } else if ("boolean".equalsIgnoreCase(type)) { value = new BooleanValue(argument.get("value").asBoolean()); } else if (type.toLowerCase().startsWith("tensor(")) { value = new TensorValue(Tensor.from(type + ":" + argument.get("value").asText())); } else { return error("Unknown argument type: " + type); } context.put(name, value); } } Value value = evaluate(expression, context); String valueType = valueType(value); if (valueType.equals("unknown")) { return error("Evaluation of ranking expression returned unknown value type"); } return String.join("\n", "{", " \"type\": \"" + valueType + "\",", " \"value\": " + valueValue(value), "}"); } catch (ParseException e) { return error("Could not parse expression: " + expression); } catch (IllegalArgumentException e) { return error(e.getMessage()); } } static String evaluate(String json); static Value evaluate(String expressionString, Context context); }
ExpressionEvaluator { public static String evaluate(String json) throws IOException { ObjectMapper m = new ObjectMapper(); JsonNode root = m.readTree(json); if (root == null) { return error("Could not parse json to evaluate"); } if (!root.has("expression")) { return error("Required field missing: expression"); } String expression = root.get("expression").asText(); try { MapContext context = new MapContext(); if (root.has("arguments")) { JsonNode arguments = root.get("arguments"); if (!arguments.isArray()) { return error("Invalid JSON format: arguments must be an array"); } for (JsonNode argument : arguments) { if (!argument.isObject()) { return error("Invalid JSON format: argument must be an object"); } if (!argument.has("name")) { return error("Invalid JSON format: argument must have a name"); } if (!argument.has("type")) { return error("Invalid JSON format: argument must have a type"); } if (!argument.has("value")) { return error("Invalid JSON format: argument must have a value"); } String name = argument.get("name").asText(); String type = argument.get("type").asText(); Value value; if ("string".equalsIgnoreCase(type)) { value = new StringValue(argument.get("value").asText()); } else if ("double".equalsIgnoreCase(type)) { value = new DoubleValue(argument.get("value").asDouble()); } else if ("boolean".equalsIgnoreCase(type)) { value = new BooleanValue(argument.get("value").asBoolean()); } else if (type.toLowerCase().startsWith("tensor(")) { value = new TensorValue(Tensor.from(type + ":" + argument.get("value").asText())); } else { return error("Unknown argument type: " + type); } context.put(name, value); } } Value value = evaluate(expression, context); String valueType = valueType(value); if (valueType.equals("unknown")) { return error("Evaluation of ranking expression returned unknown value type"); } return String.join("\n", "{", " \"type\": \"" + valueType + "\",", " \"value\": " + valueValue(value), "}"); } catch (ParseException e) { return error("Could not parse expression: " + expression); } catch (IllegalArgumentException e) { return error(e.getMessage()); } } static String evaluate(String json); static Value evaluate(String expressionString, Context context); }
@Test public void requireThatNonTensorExpressionsCanBeEvaluated() throws ParseException { MapContext context = new MapContext(); context.put("d1", new DoubleValue(3.0)); context.put("d2", new DoubleValue(4.0)); Value v = ExpressionEvaluator.evaluate("d1 * d2", context); assertTrue(v instanceof DoubleValue); assertEquals("12.0", v.toString()); }
public static String evaluate(String json) throws IOException { ObjectMapper m = new ObjectMapper(); JsonNode root = m.readTree(json); if (root == null) { return error("Could not parse json to evaluate"); } if (!root.has("expression")) { return error("Required field missing: expression"); } String expression = root.get("expression").asText(); try { MapContext context = new MapContext(); if (root.has("arguments")) { JsonNode arguments = root.get("arguments"); if (!arguments.isArray()) { return error("Invalid JSON format: arguments must be an array"); } for (JsonNode argument : arguments) { if (!argument.isObject()) { return error("Invalid JSON format: argument must be an object"); } if (!argument.has("name")) { return error("Invalid JSON format: argument must have a name"); } if (!argument.has("type")) { return error("Invalid JSON format: argument must have a type"); } if (!argument.has("value")) { return error("Invalid JSON format: argument must have a value"); } String name = argument.get("name").asText(); String type = argument.get("type").asText(); Value value; if ("string".equalsIgnoreCase(type)) { value = new StringValue(argument.get("value").asText()); } else if ("double".equalsIgnoreCase(type)) { value = new DoubleValue(argument.get("value").asDouble()); } else if ("boolean".equalsIgnoreCase(type)) { value = new BooleanValue(argument.get("value").asBoolean()); } else if (type.toLowerCase().startsWith("tensor(")) { value = new TensorValue(Tensor.from(type + ":" + argument.get("value").asText())); } else { return error("Unknown argument type: " + type); } context.put(name, value); } } Value value = evaluate(expression, context); String valueType = valueType(value); if (valueType.equals("unknown")) { return error("Evaluation of ranking expression returned unknown value type"); } return String.join("\n", "{", " \"type\": \"" + valueType + "\",", " \"value\": " + valueValue(value), "}"); } catch (ParseException e) { return error("Could not parse expression: " + expression); } catch (IllegalArgumentException e) { return error(e.getMessage()); } }
ExpressionEvaluator { public static String evaluate(String json) throws IOException { ObjectMapper m = new ObjectMapper(); JsonNode root = m.readTree(json); if (root == null) { return error("Could not parse json to evaluate"); } if (!root.has("expression")) { return error("Required field missing: expression"); } String expression = root.get("expression").asText(); try { MapContext context = new MapContext(); if (root.has("arguments")) { JsonNode arguments = root.get("arguments"); if (!arguments.isArray()) { return error("Invalid JSON format: arguments must be an array"); } for (JsonNode argument : arguments) { if (!argument.isObject()) { return error("Invalid JSON format: argument must be an object"); } if (!argument.has("name")) { return error("Invalid JSON format: argument must have a name"); } if (!argument.has("type")) { return error("Invalid JSON format: argument must have a type"); } if (!argument.has("value")) { return error("Invalid JSON format: argument must have a value"); } String name = argument.get("name").asText(); String type = argument.get("type").asText(); Value value; if ("string".equalsIgnoreCase(type)) { value = new StringValue(argument.get("value").asText()); } else if ("double".equalsIgnoreCase(type)) { value = new DoubleValue(argument.get("value").asDouble()); } else if ("boolean".equalsIgnoreCase(type)) { value = new BooleanValue(argument.get("value").asBoolean()); } else if (type.toLowerCase().startsWith("tensor(")) { value = new TensorValue(Tensor.from(type + ":" + argument.get("value").asText())); } else { return error("Unknown argument type: " + type); } context.put(name, value); } } Value value = evaluate(expression, context); String valueType = valueType(value); if (valueType.equals("unknown")) { return error("Evaluation of ranking expression returned unknown value type"); } return String.join("\n", "{", " \"type\": \"" + valueType + "\",", " \"value\": " + valueValue(value), "}"); } catch (ParseException e) { return error("Could not parse expression: " + expression); } catch (IllegalArgumentException e) { return error(e.getMessage()); } } }
ExpressionEvaluator { public static String evaluate(String json) throws IOException { ObjectMapper m = new ObjectMapper(); JsonNode root = m.readTree(json); if (root == null) { return error("Could not parse json to evaluate"); } if (!root.has("expression")) { return error("Required field missing: expression"); } String expression = root.get("expression").asText(); try { MapContext context = new MapContext(); if (root.has("arguments")) { JsonNode arguments = root.get("arguments"); if (!arguments.isArray()) { return error("Invalid JSON format: arguments must be an array"); } for (JsonNode argument : arguments) { if (!argument.isObject()) { return error("Invalid JSON format: argument must be an object"); } if (!argument.has("name")) { return error("Invalid JSON format: argument must have a name"); } if (!argument.has("type")) { return error("Invalid JSON format: argument must have a type"); } if (!argument.has("value")) { return error("Invalid JSON format: argument must have a value"); } String name = argument.get("name").asText(); String type = argument.get("type").asText(); Value value; if ("string".equalsIgnoreCase(type)) { value = new StringValue(argument.get("value").asText()); } else if ("double".equalsIgnoreCase(type)) { value = new DoubleValue(argument.get("value").asDouble()); } else if ("boolean".equalsIgnoreCase(type)) { value = new BooleanValue(argument.get("value").asBoolean()); } else if (type.toLowerCase().startsWith("tensor(")) { value = new TensorValue(Tensor.from(type + ":" + argument.get("value").asText())); } else { return error("Unknown argument type: " + type); } context.put(name, value); } } Value value = evaluate(expression, context); String valueType = valueType(value); if (valueType.equals("unknown")) { return error("Evaluation of ranking expression returned unknown value type"); } return String.join("\n", "{", " \"type\": \"" + valueType + "\",", " \"value\": " + valueValue(value), "}"); } catch (ParseException e) { return error("Could not parse expression: " + expression); } catch (IllegalArgumentException e) { return error(e.getMessage()); } } }
ExpressionEvaluator { public static String evaluate(String json) throws IOException { ObjectMapper m = new ObjectMapper(); JsonNode root = m.readTree(json); if (root == null) { return error("Could not parse json to evaluate"); } if (!root.has("expression")) { return error("Required field missing: expression"); } String expression = root.get("expression").asText(); try { MapContext context = new MapContext(); if (root.has("arguments")) { JsonNode arguments = root.get("arguments"); if (!arguments.isArray()) { return error("Invalid JSON format: arguments must be an array"); } for (JsonNode argument : arguments) { if (!argument.isObject()) { return error("Invalid JSON format: argument must be an object"); } if (!argument.has("name")) { return error("Invalid JSON format: argument must have a name"); } if (!argument.has("type")) { return error("Invalid JSON format: argument must have a type"); } if (!argument.has("value")) { return error("Invalid JSON format: argument must have a value"); } String name = argument.get("name").asText(); String type = argument.get("type").asText(); Value value; if ("string".equalsIgnoreCase(type)) { value = new StringValue(argument.get("value").asText()); } else if ("double".equalsIgnoreCase(type)) { value = new DoubleValue(argument.get("value").asDouble()); } else if ("boolean".equalsIgnoreCase(type)) { value = new BooleanValue(argument.get("value").asBoolean()); } else if (type.toLowerCase().startsWith("tensor(")) { value = new TensorValue(Tensor.from(type + ":" + argument.get("value").asText())); } else { return error("Unknown argument type: " + type); } context.put(name, value); } } Value value = evaluate(expression, context); String valueType = valueType(value); if (valueType.equals("unknown")) { return error("Evaluation of ranking expression returned unknown value type"); } return String.join("\n", "{", " \"type\": \"" + valueType + "\",", " \"value\": " + valueValue(value), "}"); } catch (ParseException e) { return error("Could not parse expression: " + expression); } catch (IllegalArgumentException e) { return error(e.getMessage()); } } static String evaluate(String json); static Value evaluate(String expressionString, Context context); }
ExpressionEvaluator { public static String evaluate(String json) throws IOException { ObjectMapper m = new ObjectMapper(); JsonNode root = m.readTree(json); if (root == null) { return error("Could not parse json to evaluate"); } if (!root.has("expression")) { return error("Required field missing: expression"); } String expression = root.get("expression").asText(); try { MapContext context = new MapContext(); if (root.has("arguments")) { JsonNode arguments = root.get("arguments"); if (!arguments.isArray()) { return error("Invalid JSON format: arguments must be an array"); } for (JsonNode argument : arguments) { if (!argument.isObject()) { return error("Invalid JSON format: argument must be an object"); } if (!argument.has("name")) { return error("Invalid JSON format: argument must have a name"); } if (!argument.has("type")) { return error("Invalid JSON format: argument must have a type"); } if (!argument.has("value")) { return error("Invalid JSON format: argument must have a value"); } String name = argument.get("name").asText(); String type = argument.get("type").asText(); Value value; if ("string".equalsIgnoreCase(type)) { value = new StringValue(argument.get("value").asText()); } else if ("double".equalsIgnoreCase(type)) { value = new DoubleValue(argument.get("value").asDouble()); } else if ("boolean".equalsIgnoreCase(type)) { value = new BooleanValue(argument.get("value").asBoolean()); } else if (type.toLowerCase().startsWith("tensor(")) { value = new TensorValue(Tensor.from(type + ":" + argument.get("value").asText())); } else { return error("Unknown argument type: " + type); } context.put(name, value); } } Value value = evaluate(expression, context); String valueType = valueType(value); if (valueType.equals("unknown")) { return error("Evaluation of ranking expression returned unknown value type"); } return String.join("\n", "{", " \"type\": \"" + valueType + "\",", " \"value\": " + valueValue(value), "}"); } catch (ParseException e) { return error("Could not parse expression: " + expression); } catch (IllegalArgumentException e) { return error(e.getMessage()); } } static String evaluate(String json); static Value evaluate(String expressionString, Context context); }
@Test public void requireThatJsonFormatCanBeEvaluated() throws IOException { String evaluateJson = String.join("\n", "{", " \"expression\": \"t1 * t2\",", " \"arguments\": [", " {", " \"name\": \"t1\",", " \"type\": \"tensor(x[])\",", " \"value\": \"{{x:0}:1,{x:1}:2}\"", " },", " {", " \"name\": \"t2\",", " \"type\": \"tensor(x[])\",", " \"value\": \"{{x:0}:2,{x:1}:3}\"", " }", " ]", "}"); String expectedJson = String.join("\n", "{", " \"type\": \"tensor(x[])\",", " \"value\": {", " \"literal\": \"tensor(x[]):{0:2.0,1:6.0}\",", " \"cells\": [{\"address\":{\"x\":\"0\"},\"value\":2.0},{\"address\":{\"x\":\"1\"},\"value\":6.0}]", " }", "}"); String resultJson = ExpressionEvaluator.evaluate(evaluateJson); ObjectMapper m = new ObjectMapper(); JsonNode result = m.readTree(resultJson); JsonNode expected = m.readTree(expectedJson); assertEquals(expected.get("type").asText(), result.get("type").asText()); assertEquals(expected.get("value").get("literal").asText(), result.get("value").get("literal").asText()); }
public static String evaluate(String json) throws IOException { ObjectMapper m = new ObjectMapper(); JsonNode root = m.readTree(json); if (root == null) { return error("Could not parse json to evaluate"); } if (!root.has("expression")) { return error("Required field missing: expression"); } String expression = root.get("expression").asText(); try { MapContext context = new MapContext(); if (root.has("arguments")) { JsonNode arguments = root.get("arguments"); if (!arguments.isArray()) { return error("Invalid JSON format: arguments must be an array"); } for (JsonNode argument : arguments) { if (!argument.isObject()) { return error("Invalid JSON format: argument must be an object"); } if (!argument.has("name")) { return error("Invalid JSON format: argument must have a name"); } if (!argument.has("type")) { return error("Invalid JSON format: argument must have a type"); } if (!argument.has("value")) { return error("Invalid JSON format: argument must have a value"); } String name = argument.get("name").asText(); String type = argument.get("type").asText(); Value value; if ("string".equalsIgnoreCase(type)) { value = new StringValue(argument.get("value").asText()); } else if ("double".equalsIgnoreCase(type)) { value = new DoubleValue(argument.get("value").asDouble()); } else if ("boolean".equalsIgnoreCase(type)) { value = new BooleanValue(argument.get("value").asBoolean()); } else if (type.toLowerCase().startsWith("tensor(")) { value = new TensorValue(Tensor.from(type + ":" + argument.get("value").asText())); } else { return error("Unknown argument type: " + type); } context.put(name, value); } } Value value = evaluate(expression, context); String valueType = valueType(value); if (valueType.equals("unknown")) { return error("Evaluation of ranking expression returned unknown value type"); } return String.join("\n", "{", " \"type\": \"" + valueType + "\",", " \"value\": " + valueValue(value), "}"); } catch (ParseException e) { return error("Could not parse expression: " + expression); } catch (IllegalArgumentException e) { return error(e.getMessage()); } }
ExpressionEvaluator { public static String evaluate(String json) throws IOException { ObjectMapper m = new ObjectMapper(); JsonNode root = m.readTree(json); if (root == null) { return error("Could not parse json to evaluate"); } if (!root.has("expression")) { return error("Required field missing: expression"); } String expression = root.get("expression").asText(); try { MapContext context = new MapContext(); if (root.has("arguments")) { JsonNode arguments = root.get("arguments"); if (!arguments.isArray()) { return error("Invalid JSON format: arguments must be an array"); } for (JsonNode argument : arguments) { if (!argument.isObject()) { return error("Invalid JSON format: argument must be an object"); } if (!argument.has("name")) { return error("Invalid JSON format: argument must have a name"); } if (!argument.has("type")) { return error("Invalid JSON format: argument must have a type"); } if (!argument.has("value")) { return error("Invalid JSON format: argument must have a value"); } String name = argument.get("name").asText(); String type = argument.get("type").asText(); Value value; if ("string".equalsIgnoreCase(type)) { value = new StringValue(argument.get("value").asText()); } else if ("double".equalsIgnoreCase(type)) { value = new DoubleValue(argument.get("value").asDouble()); } else if ("boolean".equalsIgnoreCase(type)) { value = new BooleanValue(argument.get("value").asBoolean()); } else if (type.toLowerCase().startsWith("tensor(")) { value = new TensorValue(Tensor.from(type + ":" + argument.get("value").asText())); } else { return error("Unknown argument type: " + type); } context.put(name, value); } } Value value = evaluate(expression, context); String valueType = valueType(value); if (valueType.equals("unknown")) { return error("Evaluation of ranking expression returned unknown value type"); } return String.join("\n", "{", " \"type\": \"" + valueType + "\",", " \"value\": " + valueValue(value), "}"); } catch (ParseException e) { return error("Could not parse expression: " + expression); } catch (IllegalArgumentException e) { return error(e.getMessage()); } } }
ExpressionEvaluator { public static String evaluate(String json) throws IOException { ObjectMapper m = new ObjectMapper(); JsonNode root = m.readTree(json); if (root == null) { return error("Could not parse json to evaluate"); } if (!root.has("expression")) { return error("Required field missing: expression"); } String expression = root.get("expression").asText(); try { MapContext context = new MapContext(); if (root.has("arguments")) { JsonNode arguments = root.get("arguments"); if (!arguments.isArray()) { return error("Invalid JSON format: arguments must be an array"); } for (JsonNode argument : arguments) { if (!argument.isObject()) { return error("Invalid JSON format: argument must be an object"); } if (!argument.has("name")) { return error("Invalid JSON format: argument must have a name"); } if (!argument.has("type")) { return error("Invalid JSON format: argument must have a type"); } if (!argument.has("value")) { return error("Invalid JSON format: argument must have a value"); } String name = argument.get("name").asText(); String type = argument.get("type").asText(); Value value; if ("string".equalsIgnoreCase(type)) { value = new StringValue(argument.get("value").asText()); } else if ("double".equalsIgnoreCase(type)) { value = new DoubleValue(argument.get("value").asDouble()); } else if ("boolean".equalsIgnoreCase(type)) { value = new BooleanValue(argument.get("value").asBoolean()); } else if (type.toLowerCase().startsWith("tensor(")) { value = new TensorValue(Tensor.from(type + ":" + argument.get("value").asText())); } else { return error("Unknown argument type: " + type); } context.put(name, value); } } Value value = evaluate(expression, context); String valueType = valueType(value); if (valueType.equals("unknown")) { return error("Evaluation of ranking expression returned unknown value type"); } return String.join("\n", "{", " \"type\": \"" + valueType + "\",", " \"value\": " + valueValue(value), "}"); } catch (ParseException e) { return error("Could not parse expression: " + expression); } catch (IllegalArgumentException e) { return error(e.getMessage()); } } }
ExpressionEvaluator { public static String evaluate(String json) throws IOException { ObjectMapper m = new ObjectMapper(); JsonNode root = m.readTree(json); if (root == null) { return error("Could not parse json to evaluate"); } if (!root.has("expression")) { return error("Required field missing: expression"); } String expression = root.get("expression").asText(); try { MapContext context = new MapContext(); if (root.has("arguments")) { JsonNode arguments = root.get("arguments"); if (!arguments.isArray()) { return error("Invalid JSON format: arguments must be an array"); } for (JsonNode argument : arguments) { if (!argument.isObject()) { return error("Invalid JSON format: argument must be an object"); } if (!argument.has("name")) { return error("Invalid JSON format: argument must have a name"); } if (!argument.has("type")) { return error("Invalid JSON format: argument must have a type"); } if (!argument.has("value")) { return error("Invalid JSON format: argument must have a value"); } String name = argument.get("name").asText(); String type = argument.get("type").asText(); Value value; if ("string".equalsIgnoreCase(type)) { value = new StringValue(argument.get("value").asText()); } else if ("double".equalsIgnoreCase(type)) { value = new DoubleValue(argument.get("value").asDouble()); } else if ("boolean".equalsIgnoreCase(type)) { value = new BooleanValue(argument.get("value").asBoolean()); } else if (type.toLowerCase().startsWith("tensor(")) { value = new TensorValue(Tensor.from(type + ":" + argument.get("value").asText())); } else { return error("Unknown argument type: " + type); } context.put(name, value); } } Value value = evaluate(expression, context); String valueType = valueType(value); if (valueType.equals("unknown")) { return error("Evaluation of ranking expression returned unknown value type"); } return String.join("\n", "{", " \"type\": \"" + valueType + "\",", " \"value\": " + valueValue(value), "}"); } catch (ParseException e) { return error("Could not parse expression: " + expression); } catch (IllegalArgumentException e) { return error(e.getMessage()); } } static String evaluate(String json); static Value evaluate(String expressionString, Context context); }
ExpressionEvaluator { public static String evaluate(String json) throws IOException { ObjectMapper m = new ObjectMapper(); JsonNode root = m.readTree(json); if (root == null) { return error("Could not parse json to evaluate"); } if (!root.has("expression")) { return error("Required field missing: expression"); } String expression = root.get("expression").asText(); try { MapContext context = new MapContext(); if (root.has("arguments")) { JsonNode arguments = root.get("arguments"); if (!arguments.isArray()) { return error("Invalid JSON format: arguments must be an array"); } for (JsonNode argument : arguments) { if (!argument.isObject()) { return error("Invalid JSON format: argument must be an object"); } if (!argument.has("name")) { return error("Invalid JSON format: argument must have a name"); } if (!argument.has("type")) { return error("Invalid JSON format: argument must have a type"); } if (!argument.has("value")) { return error("Invalid JSON format: argument must have a value"); } String name = argument.get("name").asText(); String type = argument.get("type").asText(); Value value; if ("string".equalsIgnoreCase(type)) { value = new StringValue(argument.get("value").asText()); } else if ("double".equalsIgnoreCase(type)) { value = new DoubleValue(argument.get("value").asDouble()); } else if ("boolean".equalsIgnoreCase(type)) { value = new BooleanValue(argument.get("value").asBoolean()); } else if (type.toLowerCase().startsWith("tensor(")) { value = new TensorValue(Tensor.from(type + ":" + argument.get("value").asText())); } else { return error("Unknown argument type: " + type); } context.put(name, value); } } Value value = evaluate(expression, context); String valueType = valueType(value); if (valueType.equals("unknown")) { return error("Evaluation of ranking expression returned unknown value type"); } return String.join("\n", "{", " \"type\": \"" + valueType + "\",", " \"value\": " + valueValue(value), "}"); } catch (ParseException e) { return error("Could not parse expression: " + expression); } catch (IllegalArgumentException e) { return error(e.getMessage()); } } static String evaluate(String json); static Value evaluate(String expressionString, Context context); }
@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()); }
@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; }
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; } }
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); }
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); }
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); }
@Test public void testOutTraversal() { Out out = Out.of(sanFrancisco); traverse(out); verify(traversal, times(1)).out("City"); assertEquals(sanFrancisco.label(), out.label()); }
@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)); }
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)); } }
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)); } }
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); }
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); }
@Test public void testIsSet() { assertTrue(isSet(new HashSet<>())); assertFalse(isSet(Person.class)); }
public static boolean isSet(Object object) { return object != null && isSet(object.getClass()); }
Classes { public static boolean isSet(Object object) { return object != null && isSet(object.getClass()); } }
Classes { public static boolean isSet(Object object) { return object != null && isSet(object.getClass()); } private Classes(); }
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); }
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); }
@Test public void testIsCollection() { assertTrue(isCollection(new ArrayList<>())); assertFalse(isCollection(new PriorityQueue<>())); assertFalse(isCollection(Person.class)); }
public static boolean isCollection(Object object) { return object != null && isCollection(object.getClass()); }
Classes { public static boolean isCollection(Object object) { return object != null && isCollection(object.getClass()); } }
Classes { public static boolean isCollection(Object object) { return object != null && isCollection(object.getClass()); } private Classes(); }
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); }
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); }
@Test public void testIsFunctional() { assertTrue(isFunctional(HasKeys.class)); assertFalse(isFunctional(Person.class)); }
public static boolean isFunctional(Class<?> type) { return is(type, Function.class); }
Classes { public static boolean isFunctional(Class<?> type) { return is(type, Function.class); } }
Classes { public static boolean isFunctional(Class<?> type) { return is(type, Function.class); } private Classes(); }
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); }
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); }
@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)); }
@SuppressWarnings({"PMD.ShortMethodName"}) public static boolean is(Class<?> type, Object that) { return that != null && is(type, that.getClass()); }
Classes { @SuppressWarnings({"PMD.ShortMethodName"}) public static boolean is(Class<?> type, Object that) { return that != null && is(type, that.getClass()); } }
Classes { @SuppressWarnings({"PMD.ShortMethodName"}) public static boolean is(Class<?> type, Object that) { return that != null && is(type, that.getClass()); } private Classes(); }
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); }
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); }
@Test public void testVertexLabelWithAlias() { assertEquals("person", of(Person.class)); assertEquals("person", of(marko)); }
@SuppressWarnings("PMD.ShortMethodName") public static String of(Element element) { return of(element.getClass()); }
Label { @SuppressWarnings("PMD.ShortMethodName") public static String of(Element element) { return of(element.getClass()); } }
Label { @SuppressWarnings("PMD.ShortMethodName") public static String of(Element element) { return of(element.getClass()); } private Label(); }
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); }
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); }
@Test public void testEdgeLabelWithoutAlias() { assertEquals("develops", of(Develops.class)); assertEquals("develops", of(develops)); }
@SuppressWarnings("PMD.ShortMethodName") public static String of(Element element) { return of(element.getClass()); }
Label { @SuppressWarnings("PMD.ShortMethodName") public static String of(Element element) { return of(element.getClass()); } }
Label { @SuppressWarnings("PMD.ShortMethodName") public static String of(Element element) { return of(element.getClass()); } private Label(); }
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); }
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); }
@Test public void testVertexLabelWithoutAlias() { assertEquals("City", of(City.class)); }
@SuppressWarnings("PMD.ShortMethodName") public static String of(Element element) { return of(element.getClass()); }
Label { @SuppressWarnings("PMD.ShortMethodName") public static String of(Element element) { return of(element.getClass()); } }
Label { @SuppressWarnings("PMD.ShortMethodName") public static String of(Element element) { return of(element.getClass()); } private Label(); }
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); }
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); }
@Test public void testIsPrimitiveType() { assertTrue(isPrimitive(String.class)); assertTrue(isPrimitive(Graph.Should.class)); assertFalse(isPrimitive(Set.class)); }
public static boolean isPrimitive(Field field) { return isPrimitive(field.getType()); }
Primitives { public static boolean isPrimitive(Field field) { return isPrimitive(field.getType()); } }
Primitives { public static boolean isPrimitive(Field field) { return isPrimitive(field.getType()); } private Primitives(); }
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); }
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; }
@Test public void testIsTimeType() { assertTrue(isTimeType(Instant.class)); assertFalse(isTimeType(Integer.class)); }
public static boolean isTimeType(Class clazz) { return clazz.equals(Date.class) || clazz.equals(Instant.class) || clazz.equals(Long.class); }
Primitives { public static boolean isTimeType(Class clazz) { return clazz.equals(Date.class) || clazz.equals(Instant.class) || clazz.equals(Long.class); } }
Primitives { public static boolean isTimeType(Class clazz) { return clazz.equals(Date.class) || clazz.equals(Instant.class) || clazz.equals(Long.class); } private Primitives(); }
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); }
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; }
@Test public void testToDateTime() { assertEquals(Date.from(now), toTimeType(now, Date.class)); assertEquals(Date.from(now), toTimeType(now.toEpochMilli(), Date.class)); }
@SuppressWarnings("unchecked") public static <T> T toTimeType(Object timeValue, Class<T> targetTimeType) { Class valueClass = timeValue.getClass(); Function<Object, Object> timeConverter = TIME_CONVERTERS.get(new Pair(valueClass, targetTimeType)); if (timeConverter == null) { throw Element.Exceptions.invalidTimeType(targetTimeType, timeValue); } return (T) timeConverter.apply(timeValue); }
Primitives { @SuppressWarnings("unchecked") public static <T> T toTimeType(Object timeValue, Class<T> targetTimeType) { Class valueClass = timeValue.getClass(); Function<Object, Object> timeConverter = TIME_CONVERTERS.get(new Pair(valueClass, targetTimeType)); if (timeConverter == null) { throw Element.Exceptions.invalidTimeType(targetTimeType, timeValue); } return (T) timeConverter.apply(timeValue); } }
Primitives { @SuppressWarnings("unchecked") public static <T> T toTimeType(Object timeValue, Class<T> targetTimeType) { Class valueClass = timeValue.getClass(); Function<Object, Object> timeConverter = TIME_CONVERTERS.get(new Pair(valueClass, targetTimeType)); if (timeConverter == null) { throw Element.Exceptions.invalidTimeType(targetTimeType, timeValue); } return (T) timeConverter.apply(timeValue); } private Primitives(); }
Primitives { @SuppressWarnings("unchecked") public static <T> T toTimeType(Object timeValue, Class<T> targetTimeType) { Class valueClass = timeValue.getClass(); Function<Object, Object> timeConverter = TIME_CONVERTERS.get(new Pair(valueClass, targetTimeType)); if (timeConverter == null) { throw Element.Exceptions.invalidTimeType(targetTimeType, timeValue); } return (T) timeConverter.apply(timeValue); } 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); }
Primitives { @SuppressWarnings("unchecked") public static <T> T toTimeType(Object timeValue, Class<T> targetTimeType) { Class valueClass = timeValue.getClass(); Function<Object, Object> timeConverter = TIME_CONVERTERS.get(new Pair(valueClass, targetTimeType)); if (timeConverter == null) { throw Element.Exceptions.invalidTimeType(targetTimeType, timeValue); } return (T) timeConverter.apply(timeValue); } 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; }
@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()); }
@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(); }
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(); } }
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(); } }
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); }
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); }
@Test public void testToInstantTime() { assertEquals(now, toTimeType(Date.from(now), Instant.class)); assertEquals(now, toTimeType(now.toEpochMilli(), Instant.class)); }
@SuppressWarnings("unchecked") public static <T> T toTimeType(Object timeValue, Class<T> targetTimeType) { Class valueClass = timeValue.getClass(); Function<Object, Object> timeConverter = TIME_CONVERTERS.get(new Pair(valueClass, targetTimeType)); if (timeConverter == null) { throw Element.Exceptions.invalidTimeType(targetTimeType, timeValue); } return (T) timeConverter.apply(timeValue); }
Primitives { @SuppressWarnings("unchecked") public static <T> T toTimeType(Object timeValue, Class<T> targetTimeType) { Class valueClass = timeValue.getClass(); Function<Object, Object> timeConverter = TIME_CONVERTERS.get(new Pair(valueClass, targetTimeType)); if (timeConverter == null) { throw Element.Exceptions.invalidTimeType(targetTimeType, timeValue); } return (T) timeConverter.apply(timeValue); } }
Primitives { @SuppressWarnings("unchecked") public static <T> T toTimeType(Object timeValue, Class<T> targetTimeType) { Class valueClass = timeValue.getClass(); Function<Object, Object> timeConverter = TIME_CONVERTERS.get(new Pair(valueClass, targetTimeType)); if (timeConverter == null) { throw Element.Exceptions.invalidTimeType(targetTimeType, timeValue); } return (T) timeConverter.apply(timeValue); } private Primitives(); }
Primitives { @SuppressWarnings("unchecked") public static <T> T toTimeType(Object timeValue, Class<T> targetTimeType) { Class valueClass = timeValue.getClass(); Function<Object, Object> timeConverter = TIME_CONVERTERS.get(new Pair(valueClass, targetTimeType)); if (timeConverter == null) { throw Element.Exceptions.invalidTimeType(targetTimeType, timeValue); } return (T) timeConverter.apply(timeValue); } 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); }
Primitives { @SuppressWarnings("unchecked") public static <T> T toTimeType(Object timeValue, Class<T> targetTimeType) { Class valueClass = timeValue.getClass(); Function<Object, Object> timeConverter = TIME_CONVERTERS.get(new Pair(valueClass, targetTimeType)); if (timeConverter == null) { throw Element.Exceptions.invalidTimeType(targetTimeType, timeValue); } return (T) timeConverter.apply(timeValue); } 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; }
@Test public void testToEpochTime() { assertEquals(Long.valueOf(now.toEpochMilli()), toTimeType(now, Long.class)); assertEquals(Long.valueOf(now.toEpochMilli()), toTimeType(Date.from(now), Long.class)); }
@SuppressWarnings("unchecked") public static <T> T toTimeType(Object timeValue, Class<T> targetTimeType) { Class valueClass = timeValue.getClass(); Function<Object, Object> timeConverter = TIME_CONVERTERS.get(new Pair(valueClass, targetTimeType)); if (timeConverter == null) { throw Element.Exceptions.invalidTimeType(targetTimeType, timeValue); } return (T) timeConverter.apply(timeValue); }
Primitives { @SuppressWarnings("unchecked") public static <T> T toTimeType(Object timeValue, Class<T> targetTimeType) { Class valueClass = timeValue.getClass(); Function<Object, Object> timeConverter = TIME_CONVERTERS.get(new Pair(valueClass, targetTimeType)); if (timeConverter == null) { throw Element.Exceptions.invalidTimeType(targetTimeType, timeValue); } return (T) timeConverter.apply(timeValue); } }
Primitives { @SuppressWarnings("unchecked") public static <T> T toTimeType(Object timeValue, Class<T> targetTimeType) { Class valueClass = timeValue.getClass(); Function<Object, Object> timeConverter = TIME_CONVERTERS.get(new Pair(valueClass, targetTimeType)); if (timeConverter == null) { throw Element.Exceptions.invalidTimeType(targetTimeType, timeValue); } return (T) timeConverter.apply(timeValue); } private Primitives(); }
Primitives { @SuppressWarnings("unchecked") public static <T> T toTimeType(Object timeValue, Class<T> targetTimeType) { Class valueClass = timeValue.getClass(); Function<Object, Object> timeConverter = TIME_CONVERTERS.get(new Pair(valueClass, targetTimeType)); if (timeConverter == null) { throw Element.Exceptions.invalidTimeType(targetTimeType, timeValue); } return (T) timeConverter.apply(timeValue); } 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); }
Primitives { @SuppressWarnings("unchecked") public static <T> T toTimeType(Object timeValue, Class<T> targetTimeType) { Class valueClass = timeValue.getClass(); Function<Object, Object> timeConverter = TIME_CONVERTERS.get(new Pair(valueClass, targetTimeType)); if (timeConverter == null) { throw Element.Exceptions.invalidTimeType(targetTimeType, timeValue); } return (T) timeConverter.apply(timeValue); } 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; }
@Test public void testIsPropertyValue() { assertTrue(isPropertyValue(field(location, "name"))); assertFalse(isPropertyValue(field(marko, "age"))); }
public static boolean isPropertyValue(Field field) { return has(field, PropertyValue.class); }
Parser { public static boolean isPropertyValue(Field field) { return has(field, PropertyValue.class); } }
Parser { public static boolean isPropertyValue(Field field) { return has(field, PropertyValue.class); } private Parser(); }
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); }
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); }
@Test public void testAsEnum() { assertEquals(MERGE, as("MERGE", Should.class)); }
@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); }
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); } }
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(); }
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); }
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); }
@Test public void testAsItself() { assertEquals(MERGE, as(MERGE, Should.class)); }
@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); }
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); } }
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(); }
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); }
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); }
@Test(expected = ClassCastException.class) public void testAsUnhandled() { assertEquals(Collections.emptyList(), as(new ArrayList<>(), Person.class)); }
@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); }
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); } }
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(); }
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); }
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); }
@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)); }
@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); }
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); } }
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(); }
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); }
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); }
@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)); }
@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); }
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); } }
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(); }
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); }
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); }
@Test public void testHasAnnotation() { assertTrue(has(name, PrimaryKey.class)); assertFalse(has(name, OrderingKey.class)); }
public static boolean has(Field field, Class<? extends Annotation> annotationType) { return field.getAnnotation(annotationType) != null; }
Fields { public static boolean has(Field field, Class<? extends Annotation> annotationType) { return field.getAnnotation(annotationType) != null; } }
Fields { public static boolean has(Field field, Class<? extends Annotation> annotationType) { return field.getAnnotation(annotationType) != null; } private Fields(); }
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); }
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; }
@Test public void testAliasProperty() { assertEquals("person", alias(Person.class, Alias::label)); assertNull(alias(locations, Alias::key)); }
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; }
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; } }
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(); }
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); }
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; }
@Test(expected = IllegalArgumentException.class) public void testNullPrimaryKeyTraversal() { sanFrancisco.setName(null); HasKeys hasKeys = HasKeys.of(sanFrancisco); traverse(hasKeys); }
@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(); }
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(); } }
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(); } }
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); }
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); }
@Test public void testPropertyKey() { assertEquals("name", propertyKey(name)); }
public static String propertyKey(Field field) { String key = alias(field, Alias::key); return key != null ? key : field.getName(); }
Fields { public static String propertyKey(Field field) { String key = alias(field, Alias::key); return key != null ? key : field.getName(); } }
Fields { public static String propertyKey(Field field) { String key = alias(field, Alias::key); return key != null ? key : field.getName(); } private Fields(); }
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); }
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; }
@Test public void testPropertyValue() { assertEquals("marko", propertyValue(name, marko)); }
@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; }
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; } }
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(); }
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); }
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; }
@Test public void testGetField() { assertEquals("age", field(marko, "age").getName()); }
public static <E extends Element> Field field(E element, String fieldName) { return field(element.getClass(), fieldName); }
Fields { public static <E extends Element> Field field(E element, String fieldName) { return field(element.getClass(), fieldName); } }
Fields { public static <E extends Element> Field field(E element, String fieldName) { return field(element.getClass(), fieldName); } private Fields(); }
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); }
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; }
@Test public void testGetAllFields() { assertEquals( Arrays.asList("name", "age", "locations", "titles"), fields(marko).stream().map(Field::getName).collect(Collectors.toList())); }
private Fields() {}
Fields { private Fields() {} }
Fields { private Fields() {} private Fields(); }
Fields { private Fields() {} 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); }
Fields { private Fields() {} 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; }
@Test public void testFieldCacheEnabled() { assertEquals(fields(marko), fields(marko)); List<Field> first = fields(marko); List<Field> second = fields(marko); assertEquals(first.size(), second.size()); for (int index = 0; index < first.size(); index++) { assertTrue(first.get(index) == second.get(index)); } }
private Fields() {}
Fields { private Fields() {} }
Fields { private Fields() {} private Fields(); }
Fields { private Fields() {} 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); }
Fields { private Fields() {} 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; }
@Test public void testFieldCacheDisabled() { try { Fields.elementCacheSize = 0; List<Field> first = fields(marko); List<Field> second = fields(marko); assertEquals(first.size(), second.size()); for (int index = 0; index < first.size(); index++) { assertFalse(first.get(index) == second.get(index)); } } finally { Fields.elementCacheSize = 100L; } }
private Fields() {}
Fields { private Fields() {} }
Fields { private Fields() {} private Fields(); }
Fields { private Fields() {} 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); }
Fields { private Fields() {} 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; }
@Test public void testGetPrimaryKeyFields() { assertEquals( Arrays.asList("name"), fields(marko, Keys::isPrimaryKey).stream() .map(Field::getName).collect(Collectors.toList())); }
private Fields() {}
Fields { private Fields() {} }
Fields { private Fields() {} private Fields(); }
Fields { private Fields() {} 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); }
Fields { private Fields() {} 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; }
@Test public void testGetNonKeyFields() { assertEquals( Arrays.asList("locations", "titles"), fields(marko, field -> !Keys.isKey(field)).stream() .map(Field::getName).collect(Collectors.toList())); }
private Fields() {}
Fields { private Fields() {} }
Fields { private Fields() {} private Fields(); }
Fields { private Fields() {} 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); }
Fields { private Fields() {} 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; }
@Test public void testPropertyId() { assertArrayEquals(new Object[] {"name", "marko", "age", 29}, id(marko)); assertArrayEquals(new Object[] {}, id(develops)); }
@SuppressWarnings({"PMD.ShortMethodName"}) public static <E extends Element> Object[] id(E element) { return of(element, Keys::isKey); }
Properties { @SuppressWarnings({"PMD.ShortMethodName"}) public static <E extends Element> Object[] id(E element) { return of(element, Keys::isKey); } }
Properties { @SuppressWarnings({"PMD.ShortMethodName"}) public static <E extends Element> Object[] id(E element) { return of(element, Keys::isKey); } private Properties(); }
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); }
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); }
@Test public void testPropertyAll() { assertArrayEquals(new Object[] {"name", "marko", "age", 29}, all(marko)); assertArrayEquals(new Object[] {"since", year(2000)}, all(develops)); }
@SuppressWarnings({"PMD.ShortMethodName"}) public static <E extends Element> Object[] all(E element) { return of(element, field -> true); }
Properties { @SuppressWarnings({"PMD.ShortMethodName"}) public static <E extends Element> Object[] all(E element) { return of(element, field -> true); } }
Properties { @SuppressWarnings({"PMD.ShortMethodName"}) public static <E extends Element> Object[] all(E element) { return of(element, field -> true); } private Properties(); }
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); }
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); }
@Test public void testHasLabelTraversal() { HasLabel hasLabel = HasLabel.of(sanFrancisco); traverse(hasLabel); verify(traversal, times(1)).hasLabel("City"); assertEquals(Label.of(sanFrancisco), hasLabel.label()); }
@SuppressWarnings("PMD.ShortMethodName") public static HasLabel of(org.apache.tinkerpop.gremlin.object.structure.Element element) { return of(element.getClass()); }
HasLabel implements ElementTo.Element { @SuppressWarnings("PMD.ShortMethodName") public static HasLabel of(org.apache.tinkerpop.gremlin.object.structure.Element element) { return of(element.getClass()); } }
HasLabel implements ElementTo.Element { @SuppressWarnings("PMD.ShortMethodName") public static HasLabel of(org.apache.tinkerpop.gremlin.object.structure.Element element) { return of(element.getClass()); } }
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); }
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); }
@Test public void testPropertyOf() { assertArrayEquals(new Object[] {}, of(marko)); assertArrayEquals(new Object[] {"since", year(2000)}, of(develops)); }
@SuppressWarnings({"PMD.ShortMethodName"}) public static <V extends Vertex> Object[] of(V vertex) { return of(vertex, field -> !isKey(field)); }
Properties { @SuppressWarnings({"PMD.ShortMethodName"}) public static <V extends Vertex> Object[] of(V vertex) { return of(vertex, field -> !isKey(field)); } }
Properties { @SuppressWarnings({"PMD.ShortMethodName"}) public static <V extends Vertex> Object[] of(V vertex) { return of(vertex, field -> !isKey(field)); } private Properties(); }
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); }
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); }
@Test public void testPropertyNames() { assertEquals(Arrays.asList("name", "age", "locations", "titles"), names(marko)); assertEquals(Arrays.asList("since"), names(develops)); }
public static <E extends Element> List<String> names(E element) { return names(element, field -> true); }
Properties { public static <E extends Element> List<String> names(E element) { return names(element, field -> true); } }
Properties { public static <E extends Element> List<String> names(E element) { return names(element, field -> true); } private Properties(); }
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); }
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); }
@Test public void testPropertyValues() { assertEquals(Arrays.asList("san diego", "startTime", year(2000)), values(location)); assertEquals(Arrays.asList("since", year(2000)), values(develops)); }
@SneakyThrows @SuppressWarnings("unchecked") public static List<Object> values(Object object) { List<Object> properties = new ArrayList<>(); Class<?> objectClass = object.getClass(); if (isPrimitive(objectClass)) { properties.add(object); } else if (isElement(objectClass)) { for (Field field : fields((Class<? extends Element>) objectClass)) { Object value = propertyValue(field, object); if (isMissing(value)) { continue; } String propertyName = propertyKey(field); if (isPropertyValue(field)) { properties.add(0, value); } else { properties.add(propertyName); properties.add(value); } } } return properties; }
Properties { @SneakyThrows @SuppressWarnings("unchecked") public static List<Object> values(Object object) { List<Object> properties = new ArrayList<>(); Class<?> objectClass = object.getClass(); if (isPrimitive(objectClass)) { properties.add(object); } else if (isElement(objectClass)) { for (Field field : fields((Class<? extends Element>) objectClass)) { Object value = propertyValue(field, object); if (isMissing(value)) { continue; } String propertyName = propertyKey(field); if (isPropertyValue(field)) { properties.add(0, value); } else { properties.add(propertyName); properties.add(value); } } } return properties; } }
Properties { @SneakyThrows @SuppressWarnings("unchecked") public static List<Object> values(Object object) { List<Object> properties = new ArrayList<>(); Class<?> objectClass = object.getClass(); if (isPrimitive(objectClass)) { properties.add(object); } else if (isElement(objectClass)) { for (Field field : fields((Class<? extends Element>) objectClass)) { Object value = propertyValue(field, object); if (isMissing(value)) { continue; } String propertyName = propertyKey(field); if (isPropertyValue(field)) { properties.add(0, value); } else { properties.add(propertyName); properties.add(value); } } } return properties; } private Properties(); }
Properties { @SneakyThrows @SuppressWarnings("unchecked") public static List<Object> values(Object object) { List<Object> properties = new ArrayList<>(); Class<?> objectClass = object.getClass(); if (isPrimitive(objectClass)) { properties.add(object); } else if (isElement(objectClass)) { for (Field field : fields((Class<? extends Element>) objectClass)) { Object value = propertyValue(field, object); if (isMissing(value)) { continue; } String propertyName = propertyKey(field); if (isPropertyValue(field)) { properties.add(0, value); } else { properties.add(propertyName); properties.add(value); } } } return properties; } 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); }
Properties { @SneakyThrows @SuppressWarnings("unchecked") public static List<Object> values(Object object) { List<Object> properties = new ArrayList<>(); Class<?> objectClass = object.getClass(); if (isPrimitive(objectClass)) { properties.add(object); } else if (isElement(objectClass)) { for (Field field : fields((Class<? extends Element>) objectClass)) { Object value = propertyValue(field, object); if (isMissing(value)) { continue; } String propertyName = propertyKey(field); if (isPropertyValue(field)) { properties.add(0, value); } else { properties.add(propertyName); properties.add(value); } } } return properties; } 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); }
@Test public void testIsPrimaryKey() { assertTrue(isPrimaryKey(personName)); assertFalse(isPrimaryKey(personAge)); assertFalse(isPrimaryKey(personTitles)); }
public static boolean isPrimaryKey(Field field) { return has(field, PrimaryKey.class); }
Keys { public static boolean isPrimaryKey(Field field) { return has(field, PrimaryKey.class); } }
Keys { public static boolean isPrimaryKey(Field field) { return has(field, PrimaryKey.class); } private Keys(); }
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); }
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); }
@Test public void testIsOrderingKey() { assertFalse(isOrderingKey(personName)); assertTrue(isOrderingKey(personAge)); assertFalse(isOrderingKey(personTitles)); }
public static boolean isOrderingKey(Field field) { return has(field, OrderingKey.class); }
Keys { public static boolean isOrderingKey(Field field) { return has(field, OrderingKey.class); } }
Keys { public static boolean isOrderingKey(Field field) { return has(field, OrderingKey.class); } private Keys(); }
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); }
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); }
@Test public void testPrimaryKeyFields() { assertEquals(Arrays.asList(personName), primaryKeyFields(Person.class)); assertTrue(primaryKeyFields(Develops.class).isEmpty()); }
public static List<Field> primaryKeyFields(Element element) { return primaryKeyFields(element.getClass()); }
Keys { public static List<Field> primaryKeyFields(Element element) { return primaryKeyFields(element.getClass()); } }
Keys { public static List<Field> primaryKeyFields(Element element) { return primaryKeyFields(element.getClass()); } private Keys(); }
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); }
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); }
@Test public void testHasPrimaryKey() { assertTrue(hasPrimaryKeys(Person.class)); assertFalse(hasPrimaryKeys(Develops.class)); }
public static boolean hasPrimaryKeys(Element element) { return hasPrimaryKeys(element.getClass()); }
Keys { public static boolean hasPrimaryKeys(Element element) { return hasPrimaryKeys(element.getClass()); } }
Keys { public static boolean hasPrimaryKeys(Element element) { return hasPrimaryKeys(element.getClass()); } private Keys(); }
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); }
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); }
@Test public void testOrderingKeyFields() { assertEquals(Arrays.asList(personAge), orderingKeyFields(Person.class)); assertTrue(orderingKeyFields(Develops.class).isEmpty()); }
public static List<Field> orderingKeyFields(Element element) { return orderingKeyFields(element.getClass()); }
Keys { public static List<Field> orderingKeyFields(Element element) { return orderingKeyFields(element.getClass()); } }
Keys { public static List<Field> orderingKeyFields(Element element) { return orderingKeyFields(element.getClass()); } private Keys(); }
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); }
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); }
@Test public void testPrimaryKeyNames() { assertEquals(Arrays.asList("name"), primaryKeyNames(Person.class)); assertTrue(primaryKeyNames(Develops.class).isEmpty()); }
public static List<String> primaryKeyNames(Element element) { return primaryKeyNames(element); }
Keys { public static List<String> primaryKeyNames(Element element) { return primaryKeyNames(element); } }
Keys { public static List<String> primaryKeyNames(Element element) { return primaryKeyNames(element); } private Keys(); }
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); }
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); }
@Test(expected = IllegalArgumentException.class) public void testNullPrimaryKey() { marko.name(null); id(marko); }
@SneakyThrows @SuppressWarnings("PMD.ShortMethodName") public static <E extends Element> Object id(E element) { if (element == null) { return null; } Object elementId = element.id(); if (elementId != null) { return elementId; } Map<String, Object> mappedId = new HashMap<>(); if (isVertex(element)) { mappedId.put(T.label.getAccessor(), element.label()); } Consumer<Field> addKey = field -> { Object propertyValue = propertyValue(field, element); if (isMissing(propertyValue)) { throw Element.Exceptions.requiredKeysMissing(element.getClass(), propertyKey(field)); } mappedId.put(propertyKey(field), propertyValue); }; primaryKeyFields(element).forEach(addKey); orderingKeyFields(element).forEach(addKey); return mappedId.isEmpty() ? null : mappedId; }
Keys { @SneakyThrows @SuppressWarnings("PMD.ShortMethodName") public static <E extends Element> Object id(E element) { if (element == null) { return null; } Object elementId = element.id(); if (elementId != null) { return elementId; } Map<String, Object> mappedId = new HashMap<>(); if (isVertex(element)) { mappedId.put(T.label.getAccessor(), element.label()); } Consumer<Field> addKey = field -> { Object propertyValue = propertyValue(field, element); if (isMissing(propertyValue)) { throw Element.Exceptions.requiredKeysMissing(element.getClass(), propertyKey(field)); } mappedId.put(propertyKey(field), propertyValue); }; primaryKeyFields(element).forEach(addKey); orderingKeyFields(element).forEach(addKey); return mappedId.isEmpty() ? null : mappedId; } }
Keys { @SneakyThrows @SuppressWarnings("PMD.ShortMethodName") public static <E extends Element> Object id(E element) { if (element == null) { return null; } Object elementId = element.id(); if (elementId != null) { return elementId; } Map<String, Object> mappedId = new HashMap<>(); if (isVertex(element)) { mappedId.put(T.label.getAccessor(), element.label()); } Consumer<Field> addKey = field -> { Object propertyValue = propertyValue(field, element); if (isMissing(propertyValue)) { throw Element.Exceptions.requiredKeysMissing(element.getClass(), propertyKey(field)); } mappedId.put(propertyKey(field), propertyValue); }; primaryKeyFields(element).forEach(addKey); orderingKeyFields(element).forEach(addKey); return mappedId.isEmpty() ? null : mappedId; } private Keys(); }
Keys { @SneakyThrows @SuppressWarnings("PMD.ShortMethodName") public static <E extends Element> Object id(E element) { if (element == null) { return null; } Object elementId = element.id(); if (elementId != null) { return elementId; } Map<String, Object> mappedId = new HashMap<>(); if (isVertex(element)) { mappedId.put(T.label.getAccessor(), element.label()); } Consumer<Field> addKey = field -> { Object propertyValue = propertyValue(field, element); if (isMissing(propertyValue)) { throw Element.Exceptions.requiredKeysMissing(element.getClass(), propertyKey(field)); } mappedId.put(propertyKey(field), propertyValue); }; primaryKeyFields(element).forEach(addKey); orderingKeyFields(element).forEach(addKey); return mappedId.isEmpty() ? null : mappedId; } 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); }
Keys { @SneakyThrows @SuppressWarnings("PMD.ShortMethodName") public static <E extends Element> Object id(E element) { if (element == null) { return null; } Object elementId = element.id(); if (elementId != null) { return elementId; } Map<String, Object> mappedId = new HashMap<>(); if (isVertex(element)) { mappedId.put(T.label.getAccessor(), element.label()); } Consumer<Field> addKey = field -> { Object propertyValue = propertyValue(field, element); if (isMissing(propertyValue)) { throw Element.Exceptions.requiredKeysMissing(element.getClass(), propertyKey(field)); } mappedId.put(propertyKey(field), propertyValue); }; primaryKeyFields(element).forEach(addKey); orderingKeyFields(element).forEach(addKey); return mappedId.isEmpty() ? null : mappedId; } 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); }
@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()); }
@SuppressWarnings("PMD.ShortMethodName") public static Values of(org.apache.tinkerpop.gremlin.object.structure.Element element) { return of(Properties.names(element)); }
Values implements ElementTo.Any { @SuppressWarnings("PMD.ShortMethodName") public static Values of(org.apache.tinkerpop.gremlin.object.structure.Element element) { return of(Properties.names(element)); } }
Values implements ElementTo.Any { @SuppressWarnings("PMD.ShortMethodName") public static Values of(org.apache.tinkerpop.gremlin.object.structure.Element element) { return of(Properties.names(element)); } }
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); }
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); }
@Test(expected = IllegalArgumentException.class) public void testNullOrderingKey() { Primitives.allowDefaultKeys = false; marko.age(0); id(marko); }
@SneakyThrows @SuppressWarnings("PMD.ShortMethodName") public static <E extends Element> Object id(E element) { if (element == null) { return null; } Object elementId = element.id(); if (elementId != null) { return elementId; } Map<String, Object> mappedId = new HashMap<>(); if (isVertex(element)) { mappedId.put(T.label.getAccessor(), element.label()); } Consumer<Field> addKey = field -> { Object propertyValue = propertyValue(field, element); if (isMissing(propertyValue)) { throw Element.Exceptions.requiredKeysMissing(element.getClass(), propertyKey(field)); } mappedId.put(propertyKey(field), propertyValue); }; primaryKeyFields(element).forEach(addKey); orderingKeyFields(element).forEach(addKey); return mappedId.isEmpty() ? null : mappedId; }
Keys { @SneakyThrows @SuppressWarnings("PMD.ShortMethodName") public static <E extends Element> Object id(E element) { if (element == null) { return null; } Object elementId = element.id(); if (elementId != null) { return elementId; } Map<String, Object> mappedId = new HashMap<>(); if (isVertex(element)) { mappedId.put(T.label.getAccessor(), element.label()); } Consumer<Field> addKey = field -> { Object propertyValue = propertyValue(field, element); if (isMissing(propertyValue)) { throw Element.Exceptions.requiredKeysMissing(element.getClass(), propertyKey(field)); } mappedId.put(propertyKey(field), propertyValue); }; primaryKeyFields(element).forEach(addKey); orderingKeyFields(element).forEach(addKey); return mappedId.isEmpty() ? null : mappedId; } }
Keys { @SneakyThrows @SuppressWarnings("PMD.ShortMethodName") public static <E extends Element> Object id(E element) { if (element == null) { return null; } Object elementId = element.id(); if (elementId != null) { return elementId; } Map<String, Object> mappedId = new HashMap<>(); if (isVertex(element)) { mappedId.put(T.label.getAccessor(), element.label()); } Consumer<Field> addKey = field -> { Object propertyValue = propertyValue(field, element); if (isMissing(propertyValue)) { throw Element.Exceptions.requiredKeysMissing(element.getClass(), propertyKey(field)); } mappedId.put(propertyKey(field), propertyValue); }; primaryKeyFields(element).forEach(addKey); orderingKeyFields(element).forEach(addKey); return mappedId.isEmpty() ? null : mappedId; } private Keys(); }
Keys { @SneakyThrows @SuppressWarnings("PMD.ShortMethodName") public static <E extends Element> Object id(E element) { if (element == null) { return null; } Object elementId = element.id(); if (elementId != null) { return elementId; } Map<String, Object> mappedId = new HashMap<>(); if (isVertex(element)) { mappedId.put(T.label.getAccessor(), element.label()); } Consumer<Field> addKey = field -> { Object propertyValue = propertyValue(field, element); if (isMissing(propertyValue)) { throw Element.Exceptions.requiredKeysMissing(element.getClass(), propertyKey(field)); } mappedId.put(propertyKey(field), propertyValue); }; primaryKeyFields(element).forEach(addKey); orderingKeyFields(element).forEach(addKey); return mappedId.isEmpty() ? null : mappedId; } 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); }
Keys { @SneakyThrows @SuppressWarnings("PMD.ShortMethodName") public static <E extends Element> Object id(E element) { if (element == null) { return null; } Object elementId = element.id(); if (elementId != null) { return elementId; } Map<String, Object> mappedId = new HashMap<>(); if (isVertex(element)) { mappedId.put(T.label.getAccessor(), element.label()); } Consumer<Field> addKey = field -> { Object propertyValue = propertyValue(field, element); if (isMissing(propertyValue)) { throw Element.Exceptions.requiredKeysMissing(element.getClass(), propertyKey(field)); } mappedId.put(propertyKey(field), propertyValue); }; primaryKeyFields(element).forEach(addKey); orderingKeyFields(element).forEach(addKey); return mappedId.isEmpty() ? null : mappedId; } 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); }
@Test @SuppressWarnings("serial") public void testIdIsInternalOrGenerated() { assertEquals(new HashMap<String, Object>() { { put(T.label.getAccessor(), marko.label()); put("name", "marko"); put("age", 29); } }, id(marko)); }
@SneakyThrows @SuppressWarnings("PMD.ShortMethodName") public static <E extends Element> Object id(E element) { if (element == null) { return null; } Object elementId = element.id(); if (elementId != null) { return elementId; } Map<String, Object> mappedId = new HashMap<>(); if (isVertex(element)) { mappedId.put(T.label.getAccessor(), element.label()); } Consumer<Field> addKey = field -> { Object propertyValue = propertyValue(field, element); if (isMissing(propertyValue)) { throw Element.Exceptions.requiredKeysMissing(element.getClass(), propertyKey(field)); } mappedId.put(propertyKey(field), propertyValue); }; primaryKeyFields(element).forEach(addKey); orderingKeyFields(element).forEach(addKey); return mappedId.isEmpty() ? null : mappedId; }
Keys { @SneakyThrows @SuppressWarnings("PMD.ShortMethodName") public static <E extends Element> Object id(E element) { if (element == null) { return null; } Object elementId = element.id(); if (elementId != null) { return elementId; } Map<String, Object> mappedId = new HashMap<>(); if (isVertex(element)) { mappedId.put(T.label.getAccessor(), element.label()); } Consumer<Field> addKey = field -> { Object propertyValue = propertyValue(field, element); if (isMissing(propertyValue)) { throw Element.Exceptions.requiredKeysMissing(element.getClass(), propertyKey(field)); } mappedId.put(propertyKey(field), propertyValue); }; primaryKeyFields(element).forEach(addKey); orderingKeyFields(element).forEach(addKey); return mappedId.isEmpty() ? null : mappedId; } }
Keys { @SneakyThrows @SuppressWarnings("PMD.ShortMethodName") public static <E extends Element> Object id(E element) { if (element == null) { return null; } Object elementId = element.id(); if (elementId != null) { return elementId; } Map<String, Object> mappedId = new HashMap<>(); if (isVertex(element)) { mappedId.put(T.label.getAccessor(), element.label()); } Consumer<Field> addKey = field -> { Object propertyValue = propertyValue(field, element); if (isMissing(propertyValue)) { throw Element.Exceptions.requiredKeysMissing(element.getClass(), propertyKey(field)); } mappedId.put(propertyKey(field), propertyValue); }; primaryKeyFields(element).forEach(addKey); orderingKeyFields(element).forEach(addKey); return mappedId.isEmpty() ? null : mappedId; } private Keys(); }
Keys { @SneakyThrows @SuppressWarnings("PMD.ShortMethodName") public static <E extends Element> Object id(E element) { if (element == null) { return null; } Object elementId = element.id(); if (elementId != null) { return elementId; } Map<String, Object> mappedId = new HashMap<>(); if (isVertex(element)) { mappedId.put(T.label.getAccessor(), element.label()); } Consumer<Field> addKey = field -> { Object propertyValue = propertyValue(field, element); if (isMissing(propertyValue)) { throw Element.Exceptions.requiredKeysMissing(element.getClass(), propertyKey(field)); } mappedId.put(propertyKey(field), propertyValue); }; primaryKeyFields(element).forEach(addKey); orderingKeyFields(element).forEach(addKey); return mappedId.isEmpty() ? null : mappedId; } 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); }
Keys { @SneakyThrows @SuppressWarnings("PMD.ShortMethodName") public static <E extends Element> Object id(E element) { if (element == null) { return null; } Object elementId = element.id(); if (elementId != null) { return elementId; } Map<String, Object> mappedId = new HashMap<>(); if (isVertex(element)) { mappedId.put(T.label.getAccessor(), element.label()); } Consumer<Field> addKey = field -> { Object propertyValue = propertyValue(field, element); if (isMissing(propertyValue)) { throw Element.Exceptions.requiredKeysMissing(element.getClass(), propertyKey(field)); } mappedId.put(propertyKey(field), propertyValue); }; primaryKeyFields(element).forEach(addKey); orderingKeyFields(element).forEach(addKey); return mappedId.isEmpty() ? null : mappedId; } 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); }
@Test(expected = IllegalStateException.class) public void testCannotDeleteDetachedVertex() { Person person = createElement(); person.remove(); }
public void remove() { org.apache.tinkerpop.gremlin.structure.Vertex delegate = delegate(); if (delegate == null) { throw Element.Exceptions.removingDetachedElement(this); } delegate.remove(); }
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 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); }
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(); }
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(); }
@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) } ); }
protected <V extends Vertex> GraphTraversal update(V vertex) { GraphTraversal traversal = find(vertex); return update(traversal, vertex, Properties::of); }
VertexGraph extends ElementGraph { protected <V extends Vertex> GraphTraversal update(V vertex) { GraphTraversal traversal = find(vertex); return update(traversal, vertex, Properties::of); } }
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); }
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(); }
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(); }
@Test public void testAddVertex() { Person marko = createElement(); vertexGraph.addVertex(marko); InOrder inOrder = inOrder(g, traversal); switch (should) { case MERGE: inOrder.verify(g, times(1)).inject(1); inOrder.verify(traversal, times(1)).coalesce(traversal, traversal); break; case REPLACE: inOrder.verify(g, times(1)).inject(1); inOrder.verify(traversal, times(1)).coalesce(traversal, traversal, traversal); break; case INSERT: inOrder.verify(g, times(1)).V(); inOrder.verify(traversal, times(1)).coalesce(traversal, traversal); break; case IGNORE: inOrder.verify(g, times(1)).inject(1); inOrder.verify(traversal, times(1)).coalesce(traversal, traversal); break; default: break; } }
public <V extends Vertex> Vertex addVertex(V vertex) { vertex.validate(); org.apache.tinkerpop.gremlin.structure.Vertex delegate; switch (should()) { case CREATE: delegate = complete(create(vertex)); break; case MERGE: delegate = complete(g.inject(1).coalesce( update(vertex), create(vertex))); break; case REPLACE: delegate = complete(g.inject(1).coalesce( clear(vertex), update(vertex), create(vertex))); break; case INSERT: delegate = insert(vertex); break; case IGNORE: default: delegate = complete(g.inject(1).coalesce(find(vertex), create(vertex))); break; } vertex.setDelegate(delegate); vertex.setUserSuppliedId(delegate.id()); delegates.put(vertex.id(), delegate); this.vertex = Parser.as(delegate, vertex.getClass()); observers.notifyAll(observer -> observer.vertexAdded(vertex, this.vertex)); return this.vertex; }
VertexGraph extends ElementGraph { public <V extends Vertex> Vertex addVertex(V vertex) { vertex.validate(); org.apache.tinkerpop.gremlin.structure.Vertex delegate; switch (should()) { case CREATE: delegate = complete(create(vertex)); break; case MERGE: delegate = complete(g.inject(1).coalesce( update(vertex), create(vertex))); break; case REPLACE: delegate = complete(g.inject(1).coalesce( clear(vertex), update(vertex), create(vertex))); break; case INSERT: delegate = insert(vertex); break; case IGNORE: default: delegate = complete(g.inject(1).coalesce(find(vertex), create(vertex))); break; } vertex.setDelegate(delegate); vertex.setUserSuppliedId(delegate.id()); delegates.put(vertex.id(), delegate); this.vertex = Parser.as(delegate, vertex.getClass()); observers.notifyAll(observer -> observer.vertexAdded(vertex, this.vertex)); return this.vertex; } }
VertexGraph extends ElementGraph { public <V extends Vertex> Vertex addVertex(V vertex) { vertex.validate(); org.apache.tinkerpop.gremlin.structure.Vertex delegate; switch (should()) { case CREATE: delegate = complete(create(vertex)); break; case MERGE: delegate = complete(g.inject(1).coalesce( update(vertex), create(vertex))); break; case REPLACE: delegate = complete(g.inject(1).coalesce( clear(vertex), update(vertex), create(vertex))); break; case INSERT: delegate = insert(vertex); break; case IGNORE: default: delegate = complete(g.inject(1).coalesce(find(vertex), create(vertex))); break; } vertex.setDelegate(delegate); vertex.setUserSuppliedId(delegate.id()); delegates.put(vertex.id(), delegate); this.vertex = Parser.as(delegate, vertex.getClass()); observers.notifyAll(observer -> observer.vertexAdded(vertex, this.vertex)); return this.vertex; } VertexGraph(Graph graph, GraphTraversalSource g); }
VertexGraph extends ElementGraph { public <V extends Vertex> Vertex addVertex(V vertex) { vertex.validate(); org.apache.tinkerpop.gremlin.structure.Vertex delegate; switch (should()) { case CREATE: delegate = complete(create(vertex)); break; case MERGE: delegate = complete(g.inject(1).coalesce( update(vertex), create(vertex))); break; case REPLACE: delegate = complete(g.inject(1).coalesce( clear(vertex), update(vertex), create(vertex))); break; case INSERT: delegate = insert(vertex); break; case IGNORE: default: delegate = complete(g.inject(1).coalesce(find(vertex), create(vertex))); break; } vertex.setDelegate(delegate); vertex.setUserSuppliedId(delegate.id()); delegates.put(vertex.id(), delegate); this.vertex = Parser.as(delegate, vertex.getClass()); observers.notifyAll(observer -> observer.vertexAdded(vertex, this.vertex)); return this.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(); }
VertexGraph extends ElementGraph { public <V extends Vertex> Vertex addVertex(V vertex) { vertex.validate(); org.apache.tinkerpop.gremlin.structure.Vertex delegate; switch (should()) { case CREATE: delegate = complete(create(vertex)); break; case MERGE: delegate = complete(g.inject(1).coalesce( update(vertex), create(vertex))); break; case REPLACE: delegate = complete(g.inject(1).coalesce( clear(vertex), update(vertex), create(vertex))); break; case INSERT: delegate = insert(vertex); break; case IGNORE: default: delegate = complete(g.inject(1).coalesce(find(vertex), create(vertex))); break; } vertex.setDelegate(delegate); vertex.setUserSuppliedId(delegate.id()); delegates.put(vertex.id(), delegate); this.vertex = Parser.as(delegate, vertex.getClass()); observers.notifyAll(observer -> observer.vertexAdded(vertex, this.vertex)); return this.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(); }
@Test(expected = IllegalArgumentException.class) public void testAddInvalidVertex() { Person marko = createElement(); marko.name(null); vertexGraph.addVertex(marko); }
public <V extends Vertex> Vertex addVertex(V vertex) { vertex.validate(); org.apache.tinkerpop.gremlin.structure.Vertex delegate; switch (should()) { case CREATE: delegate = complete(create(vertex)); break; case MERGE: delegate = complete(g.inject(1).coalesce( update(vertex), create(vertex))); break; case REPLACE: delegate = complete(g.inject(1).coalesce( clear(vertex), update(vertex), create(vertex))); break; case INSERT: delegate = insert(vertex); break; case IGNORE: default: delegate = complete(g.inject(1).coalesce(find(vertex), create(vertex))); break; } vertex.setDelegate(delegate); vertex.setUserSuppliedId(delegate.id()); delegates.put(vertex.id(), delegate); this.vertex = Parser.as(delegate, vertex.getClass()); observers.notifyAll(observer -> observer.vertexAdded(vertex, this.vertex)); return this.vertex; }
VertexGraph extends ElementGraph { public <V extends Vertex> Vertex addVertex(V vertex) { vertex.validate(); org.apache.tinkerpop.gremlin.structure.Vertex delegate; switch (should()) { case CREATE: delegate = complete(create(vertex)); break; case MERGE: delegate = complete(g.inject(1).coalesce( update(vertex), create(vertex))); break; case REPLACE: delegate = complete(g.inject(1).coalesce( clear(vertex), update(vertex), create(vertex))); break; case INSERT: delegate = insert(vertex); break; case IGNORE: default: delegate = complete(g.inject(1).coalesce(find(vertex), create(vertex))); break; } vertex.setDelegate(delegate); vertex.setUserSuppliedId(delegate.id()); delegates.put(vertex.id(), delegate); this.vertex = Parser.as(delegate, vertex.getClass()); observers.notifyAll(observer -> observer.vertexAdded(vertex, this.vertex)); return this.vertex; } }
VertexGraph extends ElementGraph { public <V extends Vertex> Vertex addVertex(V vertex) { vertex.validate(); org.apache.tinkerpop.gremlin.structure.Vertex delegate; switch (should()) { case CREATE: delegate = complete(create(vertex)); break; case MERGE: delegate = complete(g.inject(1).coalesce( update(vertex), create(vertex))); break; case REPLACE: delegate = complete(g.inject(1).coalesce( clear(vertex), update(vertex), create(vertex))); break; case INSERT: delegate = insert(vertex); break; case IGNORE: default: delegate = complete(g.inject(1).coalesce(find(vertex), create(vertex))); break; } vertex.setDelegate(delegate); vertex.setUserSuppliedId(delegate.id()); delegates.put(vertex.id(), delegate); this.vertex = Parser.as(delegate, vertex.getClass()); observers.notifyAll(observer -> observer.vertexAdded(vertex, this.vertex)); return this.vertex; } VertexGraph(Graph graph, GraphTraversalSource g); }
VertexGraph extends ElementGraph { public <V extends Vertex> Vertex addVertex(V vertex) { vertex.validate(); org.apache.tinkerpop.gremlin.structure.Vertex delegate; switch (should()) { case CREATE: delegate = complete(create(vertex)); break; case MERGE: delegate = complete(g.inject(1).coalesce( update(vertex), create(vertex))); break; case REPLACE: delegate = complete(g.inject(1).coalesce( clear(vertex), update(vertex), create(vertex))); break; case INSERT: delegate = insert(vertex); break; case IGNORE: default: delegate = complete(g.inject(1).coalesce(find(vertex), create(vertex))); break; } vertex.setDelegate(delegate); vertex.setUserSuppliedId(delegate.id()); delegates.put(vertex.id(), delegate); this.vertex = Parser.as(delegate, vertex.getClass()); observers.notifyAll(observer -> observer.vertexAdded(vertex, this.vertex)); return this.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(); }
VertexGraph extends ElementGraph { public <V extends Vertex> Vertex addVertex(V vertex) { vertex.validate(); org.apache.tinkerpop.gremlin.structure.Vertex delegate; switch (should()) { case CREATE: delegate = complete(create(vertex)); break; case MERGE: delegate = complete(g.inject(1).coalesce( update(vertex), create(vertex))); break; case REPLACE: delegate = complete(g.inject(1).coalesce( clear(vertex), update(vertex), create(vertex))); break; case INSERT: delegate = insert(vertex); break; case IGNORE: default: delegate = complete(g.inject(1).coalesce(find(vertex), create(vertex))); break; } vertex.setDelegate(delegate); vertex.setUserSuppliedId(delegate.id()); delegates.put(vertex.id(), delegate); this.vertex = Parser.as(delegate, vertex.getClass()); observers.notifyAll(observer -> observer.vertexAdded(vertex, this.vertex)); return this.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(); }
@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(); }
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 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 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); }
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(); }
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(); }
@Test(expected = IllegalStateException.class) public void testAddEdgeWithMissingVertex() { Develops develops = createElement(); edgeGraph.addEdge(develops, null, marko); }
public <E extends Edge> Edge addEdge(E edge, org.apache.tinkerpop.gremlin.structure.Vertex from, AnyTraversal anyTraversal) { if (from == null) { throw Edge.Exceptions.missingEdgeVertex(Direction.OUT, edge, from); } List<Vertex> tos = query.by(anyTraversal).list(Vertex.class); if (tos == null || tos.isEmpty()) { throw Edge.Exceptions.missingEdgeVertex(Direction.IN, edge, anyTraversal); } tos.forEach(to -> { edge.to(to); addEdge(edge, from, to.delegate()); }); return edge; }
EdgeGraph extends ElementGraph { public <E extends Edge> Edge addEdge(E edge, org.apache.tinkerpop.gremlin.structure.Vertex from, AnyTraversal anyTraversal) { if (from == null) { throw Edge.Exceptions.missingEdgeVertex(Direction.OUT, edge, from); } List<Vertex> tos = query.by(anyTraversal).list(Vertex.class); if (tos == null || tos.isEmpty()) { throw Edge.Exceptions.missingEdgeVertex(Direction.IN, edge, anyTraversal); } tos.forEach(to -> { edge.to(to); addEdge(edge, from, to.delegate()); }); return edge; } }
EdgeGraph extends ElementGraph { public <E extends Edge> Edge addEdge(E edge, org.apache.tinkerpop.gremlin.structure.Vertex from, AnyTraversal anyTraversal) { if (from == null) { throw Edge.Exceptions.missingEdgeVertex(Direction.OUT, edge, from); } List<Vertex> tos = query.by(anyTraversal).list(Vertex.class); if (tos == null || tos.isEmpty()) { throw Edge.Exceptions.missingEdgeVertex(Direction.IN, edge, anyTraversal); } tos.forEach(to -> { edge.to(to); addEdge(edge, from, to.delegate()); }); return edge; } EdgeGraph(Graph graph, Query query, GraphTraversalSource g); }
EdgeGraph extends ElementGraph { public <E extends Edge> Edge addEdge(E edge, org.apache.tinkerpop.gremlin.structure.Vertex from, AnyTraversal anyTraversal) { if (from == null) { throw Edge.Exceptions.missingEdgeVertex(Direction.OUT, edge, from); } List<Vertex> tos = query.by(anyTraversal).list(Vertex.class); if (tos == null || tos.isEmpty()) { throw Edge.Exceptions.missingEdgeVertex(Direction.IN, edge, anyTraversal); } tos.forEach(to -> { edge.to(to); addEdge(edge, from, to.delegate()); }); 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(); }
EdgeGraph extends ElementGraph { public <E extends Edge> Edge addEdge(E edge, org.apache.tinkerpop.gremlin.structure.Vertex from, AnyTraversal anyTraversal) { if (from == null) { throw Edge.Exceptions.missingEdgeVertex(Direction.OUT, edge, from); } List<Vertex> tos = query.by(anyTraversal).list(Vertex.class); if (tos == null || tos.isEmpty()) { throw Edge.Exceptions.missingEdgeVertex(Direction.IN, edge, anyTraversal); } tos.forEach(to -> { edge.to(to); addEdge(edge, from, to.delegate()); }); 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(); }
@Test(expected = IllegalStateException.class) public void testAddEdgeWithEmptyTraversal() { Develops develops = createElement(); when(query.by((AnyTraversal) any())).thenReturn(query); when(query.by((SubTraversal) any())).thenReturn(query); when(query.list((Class) any())).thenReturn(null); edgeGraph.addEdge(develops, marko, g -> null); }
public <E extends Edge> Edge addEdge(E edge, org.apache.tinkerpop.gremlin.structure.Vertex from, AnyTraversal anyTraversal) { if (from == null) { throw Edge.Exceptions.missingEdgeVertex(Direction.OUT, edge, from); } List<Vertex> tos = query.by(anyTraversal).list(Vertex.class); if (tos == null || tos.isEmpty()) { throw Edge.Exceptions.missingEdgeVertex(Direction.IN, edge, anyTraversal); } tos.forEach(to -> { edge.to(to); addEdge(edge, from, to.delegate()); }); return edge; }
EdgeGraph extends ElementGraph { public <E extends Edge> Edge addEdge(E edge, org.apache.tinkerpop.gremlin.structure.Vertex from, AnyTraversal anyTraversal) { if (from == null) { throw Edge.Exceptions.missingEdgeVertex(Direction.OUT, edge, from); } List<Vertex> tos = query.by(anyTraversal).list(Vertex.class); if (tos == null || tos.isEmpty()) { throw Edge.Exceptions.missingEdgeVertex(Direction.IN, edge, anyTraversal); } tos.forEach(to -> { edge.to(to); addEdge(edge, from, to.delegate()); }); return edge; } }
EdgeGraph extends ElementGraph { public <E extends Edge> Edge addEdge(E edge, org.apache.tinkerpop.gremlin.structure.Vertex from, AnyTraversal anyTraversal) { if (from == null) { throw Edge.Exceptions.missingEdgeVertex(Direction.OUT, edge, from); } List<Vertex> tos = query.by(anyTraversal).list(Vertex.class); if (tos == null || tos.isEmpty()) { throw Edge.Exceptions.missingEdgeVertex(Direction.IN, edge, anyTraversal); } tos.forEach(to -> { edge.to(to); addEdge(edge, from, to.delegate()); }); return edge; } EdgeGraph(Graph graph, Query query, GraphTraversalSource g); }
EdgeGraph extends ElementGraph { public <E extends Edge> Edge addEdge(E edge, org.apache.tinkerpop.gremlin.structure.Vertex from, AnyTraversal anyTraversal) { if (from == null) { throw Edge.Exceptions.missingEdgeVertex(Direction.OUT, edge, from); } List<Vertex> tos = query.by(anyTraversal).list(Vertex.class); if (tos == null || tos.isEmpty()) { throw Edge.Exceptions.missingEdgeVertex(Direction.IN, edge, anyTraversal); } tos.forEach(to -> { edge.to(to); addEdge(edge, from, to.delegate()); }); 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(); }
EdgeGraph extends ElementGraph { public <E extends Edge> Edge addEdge(E edge, org.apache.tinkerpop.gremlin.structure.Vertex from, AnyTraversal anyTraversal) { if (from == null) { throw Edge.Exceptions.missingEdgeVertex(Direction.OUT, edge, from); } List<Vertex> tos = query.by(anyTraversal).list(Vertex.class); if (tos == null || tos.isEmpty()) { throw Edge.Exceptions.missingEdgeVertex(Direction.IN, edge, anyTraversal); } tos.forEach(to -> { edge.to(to); addEdge(edge, from, to.delegate()); }); 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(); }
@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()); }
<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 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 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); }
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(); }
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(); }
@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()); }
@SuppressWarnings("PMD.ShortMethodName") public static Keys of(org.apache.tinkerpop.gremlin.object.structure.Element element) { return of(element.getClass()); }
Keys implements ElementTo.Any { @SuppressWarnings("PMD.ShortMethodName") public static Keys of(org.apache.tinkerpop.gremlin.object.structure.Element element) { return of(element.getClass()); } }
Keys implements ElementTo.Any { @SuppressWarnings("PMD.ShortMethodName") public static Keys of(org.apache.tinkerpop.gremlin.object.structure.Element element) { return of(element.getClass()); } }
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); }
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); }
@Test public void testUpdateElement() { Develops develops = createElement(); edgeGraph.update(traversal, develops, Properties::all); verify(traversal, times(1)).property("since", develops.since()); }
<E extends Edge> GraphTraversal update(E edge, Object fromId, Object toId) { GraphTraversal traversal = find(edge, fromId, toId); return update(traversal, edge, Properties::of); }
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 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); }
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(); }
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(); }
@Test public void testAddEdge() { Develops develops = createElement(); edgeGraph.addEdge(develops, marko, vadas); InOrder inOrder = inOrder(g, traversal); switch (should) { case CREATE: 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)).V(); inOrder.verify(traversal, times(1)).hasId(vadas.id()); inOrder.verify(traversal, times(1)).as("to"); inOrder.verify(traversal, times(1)).addE(develops.label()); inOrder.verify(traversal, times(1)).as("edge"); inOrder.verify(traversal, times(1)).from("from"); verify(traversal, times(1)).property("since", develops.since()); break; case MERGE: inOrder.verify(g, times(1)).inject(1); inOrder.verify(traversal, times(1)).coalesce(traversal, traversal); break; case REPLACE: inOrder.verify(g, times(1)).inject(1); inOrder.verify(traversal, times(1)).coalesce(traversal, traversal, traversal); break; case INSERT: inOrder.verify(g, times(1)).inject(1); 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(1)).select("edge"); inOrder.verify(traversal, times(1)).choose(__.value()); 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)).V(); inOrder.verify(traversal, times(1)).hasId(vadas.id()); inOrder.verify(traversal, times(1)).as("to"); inOrder.verify(traversal, times(1)).addE(develops.label()); inOrder.verify(traversal, times(1)).as("edge"); inOrder.verify(traversal, times(1)).from("from"); verify(traversal, times(1)).property("since", develops.since()); inOrder.verify(traversal, times(1)).coalesce(traversal, traversal); break; case IGNORE: inOrder.verify(g, times(1)).inject(1); inOrder.verify(traversal, times(1)).coalesce(traversal, traversal); break; default: break; } }
public <E extends Edge> Edge addEdge(E edge, org.apache.tinkerpop.gremlin.structure.Vertex from, AnyTraversal anyTraversal) { if (from == null) { throw Edge.Exceptions.missingEdgeVertex(Direction.OUT, edge, from); } List<Vertex> tos = query.by(anyTraversal).list(Vertex.class); if (tos == null || tos.isEmpty()) { throw Edge.Exceptions.missingEdgeVertex(Direction.IN, edge, anyTraversal); } tos.forEach(to -> { edge.to(to); addEdge(edge, from, to.delegate()); }); return edge; }
EdgeGraph extends ElementGraph { public <E extends Edge> Edge addEdge(E edge, org.apache.tinkerpop.gremlin.structure.Vertex from, AnyTraversal anyTraversal) { if (from == null) { throw Edge.Exceptions.missingEdgeVertex(Direction.OUT, edge, from); } List<Vertex> tos = query.by(anyTraversal).list(Vertex.class); if (tos == null || tos.isEmpty()) { throw Edge.Exceptions.missingEdgeVertex(Direction.IN, edge, anyTraversal); } tos.forEach(to -> { edge.to(to); addEdge(edge, from, to.delegate()); }); return edge; } }
EdgeGraph extends ElementGraph { public <E extends Edge> Edge addEdge(E edge, org.apache.tinkerpop.gremlin.structure.Vertex from, AnyTraversal anyTraversal) { if (from == null) { throw Edge.Exceptions.missingEdgeVertex(Direction.OUT, edge, from); } List<Vertex> tos = query.by(anyTraversal).list(Vertex.class); if (tos == null || tos.isEmpty()) { throw Edge.Exceptions.missingEdgeVertex(Direction.IN, edge, anyTraversal); } tos.forEach(to -> { edge.to(to); addEdge(edge, from, to.delegate()); }); return edge; } EdgeGraph(Graph graph, Query query, GraphTraversalSource g); }
EdgeGraph extends ElementGraph { public <E extends Edge> Edge addEdge(E edge, org.apache.tinkerpop.gremlin.structure.Vertex from, AnyTraversal anyTraversal) { if (from == null) { throw Edge.Exceptions.missingEdgeVertex(Direction.OUT, edge, from); } List<Vertex> tos = query.by(anyTraversal).list(Vertex.class); if (tos == null || tos.isEmpty()) { throw Edge.Exceptions.missingEdgeVertex(Direction.IN, edge, anyTraversal); } tos.forEach(to -> { edge.to(to); addEdge(edge, from, to.delegate()); }); 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(); }
EdgeGraph extends ElementGraph { public <E extends Edge> Edge addEdge(E edge, org.apache.tinkerpop.gremlin.structure.Vertex from, AnyTraversal anyTraversal) { if (from == null) { throw Edge.Exceptions.missingEdgeVertex(Direction.OUT, edge, from); } List<Vertex> tos = query.by(anyTraversal).list(Vertex.class); if (tos == null || tos.isEmpty()) { throw Edge.Exceptions.missingEdgeVertex(Direction.IN, edge, anyTraversal); } tos.forEach(to -> { edge.to(to); addEdge(edge, from, to.delegate()); }); 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(); }
@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(); }
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 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 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); }
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(); }
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(); }
@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()); }
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; }
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; } }
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; } }
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; } }
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; } }