src_fm_fc_ms_ff
stringlengths
43
86.8k
target
stringlengths
20
276k
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 cloneDigest() throws Exception { Digest d1Orig = new SHA512Digest(); Digest d1Clone = RSAOAEPDigestFactory.cloneDigest(d1Orig); assertTrue(d1Clone instanceof SHA512Digest); assertNotEquals(d1Orig, d1Clone); }
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 encrypt() throws Exception { AbstractPublicKey rsaPublicKey = oaepSpec.getPublicKey(); ((RSAOAEPPublicKey) rsaPublicKey).resetEncryptor(); assertArrayEquals(rsaPublicKey.encrypt(oaepSpec.M), oaepSpec.C); }
StandaloneBean { public String returnMessage() { return message; } String returnMessage(); }
@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); }
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 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()); }
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 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)")); } }
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 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()); }
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 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()); } @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()); } } @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()); }
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 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()); } }
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 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()); } @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()); } @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()); }
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 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()); }
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 testOutTraversal() { Out out = Out.of(sanFrancisco); traverse(out); verify(traversal, times(1)).out("City"); assertEquals(sanFrancisco.label(), out.label()); }
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 testIsSet() { assertTrue(isSet(new HashSet<>())); assertFalse(isSet(Person.class)); }
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 testIsCollection() { assertTrue(isCollection(new ArrayList<>())); assertFalse(isCollection(new PriorityQueue<>())); assertFalse(isCollection(Person.class)); }
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 testIsFunctional() { assertTrue(isFunctional(HasKeys.class)); assertFalse(isFunctional(Person.class)); }
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 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)); }
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 testVertexLabelWithAlias() { assertEquals("person", of(Person.class)); assertEquals("person", of(marko)); } @Test public void testEdgeLabelWithoutAlias() { assertEquals("develops", of(Develops.class)); assertEquals("develops", of(develops)); } @Test public void testVertexLabelWithoutAlias() { assertEquals("City", of(City.class)); }
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 testIsPrimitiveType() { assertTrue(isPrimitive(String.class)); assertTrue(isPrimitive(Graph.Should.class)); assertFalse(isPrimitive(Set.class)); }
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 testIsTimeType() { assertTrue(isTimeType(Instant.class)); assertFalse(isTimeType(Integer.class)); }
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 testToDateTime() { assertEquals(Date.from(now), toTimeType(now, Date.class)); assertEquals(Date.from(now), toTimeType(now.toEpochMilli(), Date.class)); } @Test public void testToInstantTime() { assertEquals(now, toTimeType(Date.from(now), Instant.class)); assertEquals(now, toTimeType(now.toEpochMilli(), Instant.class)); } @Test public void testToEpochTime() { assertEquals(Long.valueOf(now.toEpochMilli()), toTimeType(now, Long.class)); assertEquals(Long.valueOf(now.toEpochMilli()), toTimeType(Date.from(now), Long.class)); }
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 testHasPrimaryKeyTraversal() { HasKeys hasKeys = HasKeys.of(sanFrancisco); traverse(hasKeys); verify(traversal, times(1)).hasLabel("City"); verify(traversal, times(1)).has("name", "San Francisco"); assertEquals(sanFrancisco, hasKeys.element()); } @Test(expected = IllegalArgumentException.class) public void testNullPrimaryKeyTraversal() { sanFrancisco.setName(null); HasKeys hasKeys = HasKeys.of(sanFrancisco); traverse(hasKeys); }
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 testIsPropertyValue() { assertTrue(isPropertyValue(field(location, "name"))); assertFalse(isPropertyValue(field(marko, "age"))); }
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 testAsEnum() { assertEquals(MERGE, as("MERGE", Should.class)); } @Test public void testAsItself() { assertEquals(MERGE, as(MERGE, Should.class)); } @Test(expected = ClassCastException.class) public void testAsUnhandled() { assertEquals(Collections.emptyList(), as(new ArrayList<>(), Person.class)); } @Test public void testAsVertex() { assertEquals(marko, as(new DetachedVertex( 1, "person", new HashMap<String, Object>() { { put("name", Arrays.asList(new HashMap<String, Object>() { { put("value", "marko"); } })); put("age", Arrays.asList(new HashMap<String, Object>() { { put("value", 29); } })); } }), Person.class)); } @Test public void testAsEdge() { assertEquals(develops, as(new DetachedEdge( null, Label.of(Develops.class), new HashMap<String, Object>() { { put("since", develops.since()); } }, null, null, null, null), Develops.class)); }
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 testHasAnnotation() { assertTrue(has(name, PrimaryKey.class)); assertFalse(has(name, OrderingKey.class)); }
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 public void testAliasProperty() { assertEquals("person", alias(Person.class, Alias::label)); assertNull(alias(locations, Alias::key)); }
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 testPropertyKey() { assertEquals("name", propertyKey(name)); }
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 testPropertyValue() { assertEquals("marko", propertyValue(name, marko)); }
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 testGetField() { assertEquals("age", field(marko, "age").getName()); }
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 testGetAllFields() { assertEquals( Arrays.asList("name", "age", "locations", "titles"), fields(marko).stream().map(Field::getName).collect(Collectors.toList())); } @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)); } } @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; } } @Test public void testGetPrimaryKeyFields() { assertEquals( Arrays.asList("name"), fields(marko, Keys::isPrimaryKey).stream() .map(Field::getName).collect(Collectors.toList())); } @Test public void testGetNonKeyFields() { assertEquals( Arrays.asList("locations", "titles"), fields(marko, field -> !Keys.isKey(field)).stream() .map(Field::getName).collect(Collectors.toList())); }
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 testPropertyId() { assertArrayEquals(new Object[] {"name", "marko", "age", 29}, id(marko)); assertArrayEquals(new Object[] {}, id(develops)); }
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 testPropertyAll() { assertArrayEquals(new Object[] {"name", "marko", "age", 29}, all(marko)); assertArrayEquals(new Object[] {"since", year(2000)}, all(develops)); }
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 testHasLabelTraversal() { HasLabel hasLabel = HasLabel.of(sanFrancisco); traverse(hasLabel); verify(traversal, times(1)).hasLabel("City"); assertEquals(Label.of(sanFrancisco), hasLabel.label()); }
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 testPropertyOf() { assertArrayEquals(new Object[] {}, of(marko)); assertArrayEquals(new Object[] {"since", year(2000)}, of(develops)); }
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 testPropertyNames() { assertEquals(Arrays.asList("name", "age", "locations", "titles"), names(marko)); assertEquals(Arrays.asList("since"), names(develops)); }
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 testPropertyValues() { assertEquals(Arrays.asList("san diego", "startTime", year(2000)), values(location)); assertEquals(Arrays.asList("since", year(2000)), values(develops)); }
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 testIsPrimaryKey() { assertTrue(isPrimaryKey(personName)); assertFalse(isPrimaryKey(personAge)); assertFalse(isPrimaryKey(personTitles)); }
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 testIsOrderingKey() { assertFalse(isOrderingKey(personName)); assertTrue(isOrderingKey(personAge)); assertFalse(isOrderingKey(personTitles)); }
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 testPrimaryKeyFields() { assertEquals(Arrays.asList(personName), primaryKeyFields(Person.class)); assertTrue(primaryKeyFields(Develops.class).isEmpty()); }
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 testHasPrimaryKey() { assertTrue(hasPrimaryKeys(Person.class)); assertFalse(hasPrimaryKeys(Develops.class)); }
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 testOrderingKeyFields() { assertEquals(Arrays.asList(personAge), orderingKeyFields(Person.class)); assertTrue(orderingKeyFields(Develops.class).isEmpty()); }
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 public void testPrimaryKeyNames() { assertEquals(Arrays.asList("name"), primaryKeyNames(Person.class)); assertTrue(primaryKeyNames(Develops.class).isEmpty()); }
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 = IllegalArgumentException.class) public void testNullPrimaryKey() { marko.name(null); id(marko); } @Test(expected = IllegalArgumentException.class) public void testNullOrderingKey() { Primitives.allowDefaultKeys = false; marko.age(0); id(marko); } @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)); }
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 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()); }
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(expected = IllegalStateException.class) public void testCannotDeleteDetachedVertex() { Person person = createElement(); person.remove(); }
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 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) } ); }
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 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; } } @Test(expected = IllegalArgumentException.class) public void testAddInvalidVertex() { Person marko = createElement(); marko.name(null); vertexGraph.addVertex(marko); }
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 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(); }
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 testAddEdgeWithMissingVertex() { Develops develops = createElement(); edgeGraph.addEdge(develops, null, marko); } @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); } @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; } }
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 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()); }
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 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()); }
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 testUpdateElement() { Develops develops = createElement(); edgeGraph.update(traversal, develops, Properties::all); verify(traversal, times(1)).property("since", develops.since()); }
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 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(); }
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; } }
@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()); }
ElementGraph { protected <E extends Element> GraphTraversal update( GraphTraversal traversal, E element, Function<E, Object[]> lister) { return update(traversal, UpdateBy.TRAVERSAL, element, lister); } }
@Test public void testUpdateElement() { Location location = (Location) createElement(); elementGraph.update(traversal, location, Properties::all); InOrder inOrder = inOrder(traversal); inOrder.verify(traversal, times(1)).property("name", "San Francisco"); inOrder.verify(traversal, times(1)).property("startTime", location.startTime()); }
Element implements Comparable<Element> { @SuppressWarnings({"PMD.ShortMethodName"}) public final Object id() { if (userSuppliedId != null) { return userSuppliedId; } if (delegate != null) { return delegate.id(); } return null; } Element(Element other); final String label(); @SuppressWarnings({"PMD.ShortMethodName"}) final Object id(); @SneakyThrows @SuppressWarnings({"PMD.ShortMethodName"}) ElementTo.Element s(String key); void validate(); static void cache(long numberOfElements); @Override boolean equals(Object other); @Override @SneakyThrows int hashCode(); @Override int compareTo(Element that); boolean existsIn(Collection<? extends Element> elements); @SuppressWarnings("unchecked") static final Comparator<Element> valuesOf(List<Field> fields); static final long serialVersionUID; final ElementTo.Element withLabel; final ElementTo.Element withId; }
@Test public void testWithIdTraversal() { Element element = createElement(); traverse(element.withId); verify(traversal, times(1)).hasId(element.id()); }
Element implements Comparable<Element> { public final String label() { return Label.of(getClass()); } Element(Element other); final String label(); @SuppressWarnings({"PMD.ShortMethodName"}) final Object id(); @SneakyThrows @SuppressWarnings({"PMD.ShortMethodName"}) ElementTo.Element s(String key); void validate(); static void cache(long numberOfElements); @Override boolean equals(Object other); @Override @SneakyThrows int hashCode(); @Override int compareTo(Element that); boolean existsIn(Collection<? extends Element> elements); @SuppressWarnings("unchecked") static final Comparator<Element> valuesOf(List<Field> fields); static final long serialVersionUID; final ElementTo.Element withLabel; final ElementTo.Element withId; }
@Test public void testWithLabelTraversal() { Element element = createElement(); traverse(element.withLabel); verify(traversal, times(1)).hasLabel(element.label()); } @Test public void testLabelExists() { Element element = createElement(); assertEquals(Label.of(element), element.label()); }
Element implements Comparable<Element> { public boolean existsIn(Collection<? extends Element> elements) { final List<Field> fields = keyFields(getClass()); if (fields.isEmpty()) { fields.addAll(fields(getClass())); } return elements.stream() .anyMatch(element -> valuesOf(fields).compare(element, this) == 0); } Element(Element other); final String label(); @SuppressWarnings({"PMD.ShortMethodName"}) final Object id(); @SneakyThrows @SuppressWarnings({"PMD.ShortMethodName"}) ElementTo.Element s(String key); void validate(); static void cache(long numberOfElements); @Override boolean equals(Object other); @Override @SneakyThrows int hashCode(); @Override int compareTo(Element that); boolean existsIn(Collection<? extends Element> elements); @SuppressWarnings("unchecked") static final Comparator<Element> valuesOf(List<Field> fields); static final long serialVersionUID; final ElementTo.Element withLabel; final ElementTo.Element withId; }
@Test public void testExistsIn() { Element element = createElement(); Element other = anotherElement(); assertTrue(element.existsIn(Arrays.asList(element))); assertFalse(element.existsIn(Arrays.asList(other))); }
Edge extends Element { @SuppressWarnings("PMD.CloseResource") public boolean connects(Vertex from, Vertex to) { return connects(from.getClass(), to.getClass()); } org.apache.tinkerpop.gremlin.structure.Edge delegate(); V fromAs(Class<V> vertexType); V toAs(Class<V> vertexType); @SuppressWarnings("PMD.CloseResource") boolean connects(Vertex from, Vertex to); @SuppressWarnings("PMD.CloseResource") boolean connects(Class<? extends Vertex> fromClass, Class<? extends Vertex> toClass); }
@Test public void testConnectsProperly() { Develops develops = createElement(); assertTrue(develops.connects(Person.class, Software.class)); assertFalse(develops.connects(Person.class, Person.class)); }
Classes { public static boolean isElement(Class<?> type) { return is(type, Element.class); } private Classes(); static boolean isElement(Class<?> type); static boolean isVertex(Object object); static boolean isVertex(Class<?> type); static boolean isEdge(Object object); static boolean isEdge(Class<?> type); static boolean isList(Object object); static boolean isList(Class<?> type); static boolean isSet(Object object); static boolean isSet(Class<?> type); static boolean isCollection(Object object); static boolean isCollection(Class<?> type); static boolean isFunctional(Class<?> type); @SuppressWarnings({"PMD.ShortMethodName"}) static boolean is(Class<?> type, Object that); @SuppressWarnings({"PMD.ShortMethodName"}) static boolean is(Object object, Class<?> that); @SuppressWarnings({"PMD.ShortMethodName"}) static boolean is(Class<?> type, Class<?> that); @SuppressWarnings("unchecked") static void sortCollection(Class<?> clazz, Collection<?> collection); @SneakyThrows @SuppressWarnings("rawtypes") static Collection newCollection(Class<?> clazz); static String name(Class<?> type); }
@Test public void testIsElement() { assertTrue(isElement(Person.class)); assertTrue(isElement(Develops.class)); }
Classes { public static boolean isVertex(Object object) { return object != null && isVertex(object.getClass()); } private Classes(); static boolean isElement(Class<?> type); static boolean isVertex(Object object); static boolean isVertex(Class<?> type); static boolean isEdge(Object object); static boolean isEdge(Class<?> type); static boolean isList(Object object); static boolean isList(Class<?> type); static boolean isSet(Object object); static boolean isSet(Class<?> type); static boolean isCollection(Object object); static boolean isCollection(Class<?> type); static boolean isFunctional(Class<?> type); @SuppressWarnings({"PMD.ShortMethodName"}) static boolean is(Class<?> type, Object that); @SuppressWarnings({"PMD.ShortMethodName"}) static boolean is(Object object, Class<?> that); @SuppressWarnings({"PMD.ShortMethodName"}) static boolean is(Class<?> type, Class<?> that); @SuppressWarnings("unchecked") static void sortCollection(Class<?> clazz, Collection<?> collection); @SneakyThrows @SuppressWarnings("rawtypes") static Collection newCollection(Class<?> clazz); static String name(Class<?> type); }
@Test public void testIsVertex() { assertTrue(isVertex(Person.class)); assertFalse(isVertex(Develops.class)); }
Classes { public static boolean isEdge(Object object) { return object != null && isEdge(object.getClass()); } private Classes(); static boolean isElement(Class<?> type); static boolean isVertex(Object object); static boolean isVertex(Class<?> type); static boolean isEdge(Object object); static boolean isEdge(Class<?> type); static boolean isList(Object object); static boolean isList(Class<?> type); static boolean isSet(Object object); static boolean isSet(Class<?> type); static boolean isCollection(Object object); static boolean isCollection(Class<?> type); static boolean isFunctional(Class<?> type); @SuppressWarnings({"PMD.ShortMethodName"}) static boolean is(Class<?> type, Object that); @SuppressWarnings({"PMD.ShortMethodName"}) static boolean is(Object object, Class<?> that); @SuppressWarnings({"PMD.ShortMethodName"}) static boolean is(Class<?> type, Class<?> that); @SuppressWarnings("unchecked") static void sortCollection(Class<?> clazz, Collection<?> collection); @SneakyThrows @SuppressWarnings("rawtypes") static Collection newCollection(Class<?> clazz); static String name(Class<?> type); }
@Test public void testIsEdge() { assertFalse(isEdge(Person.class)); assertTrue(isEdge(Develops.class)); }
Classes { public static boolean isList(Object object) { return object != null && isList(object.getClass()); } private Classes(); static boolean isElement(Class<?> type); static boolean isVertex(Object object); static boolean isVertex(Class<?> type); static boolean isEdge(Object object); static boolean isEdge(Class<?> type); static boolean isList(Object object); static boolean isList(Class<?> type); static boolean isSet(Object object); static boolean isSet(Class<?> type); static boolean isCollection(Object object); static boolean isCollection(Class<?> type); static boolean isFunctional(Class<?> type); @SuppressWarnings({"PMD.ShortMethodName"}) static boolean is(Class<?> type, Object that); @SuppressWarnings({"PMD.ShortMethodName"}) static boolean is(Object object, Class<?> that); @SuppressWarnings({"PMD.ShortMethodName"}) static boolean is(Class<?> type, Class<?> that); @SuppressWarnings("unchecked") static void sortCollection(Class<?> clazz, Collection<?> collection); @SneakyThrows @SuppressWarnings("rawtypes") static Collection newCollection(Class<?> clazz); static String name(Class<?> type); }
@Test public void testIsList() { assertFalse(isList(Person.class)); assertTrue(isList(Arrays.asList(develops))); }
CounterViewModel extends BaseObservable { @Bindable public int getCount() { return count; } void increment(); void decrement(); @Bindable int getCount(); }
@Test public void testInitialState() { Assert.assertEquals(0, counterViewModel.getCount()); }
CounterViewModel extends BaseObservable { public void increment() { setCount(getCount() + 1); } void increment(); void decrement(); @Bindable int getCount(); }
@Test public void testIncrement() { for (int i = 1; i <= 5; i++) { counterViewModel.increment(); Assert.assertEquals(i, counterViewModel.getCount()); } }
CounterViewModel extends BaseObservable { public void decrement() { setCount(getCount() - 1); } void increment(); void decrement(); @Bindable int getCount(); }
@Test public void testDecrement() { for (int i = 1; i <= 5; i++) { counterViewModel.decrement(); Assert.assertEquals(i * -1, counterViewModel.getCount()); } }
IniRealmDemo { public boolean helloShiro(String username, String password) { initSecurityUtils(); UsernamePasswordToken usernamePasswordToken = new UsernamePasswordToken(username, password); usernamePasswordToken.setRememberMe(true); Subject currentUser = SecurityUtils.getSubject(); try { currentUser.login(usernamePasswordToken); log.debug("currentUser.isAuthenticated()'s value : {}", currentUser.isAuthenticated()); } catch (Exception e) { log.error("usernamePasswordToken's value : {}", usernamePasswordToken); } return currentUser.isAuthenticated(); } boolean helloShiro(String username, String password); }
@Test void helloShiro() { String username = "admin"; String password = "admin"; IniRealmDemo iniRealmDemo = new IniRealmDemo(); Assert.assertEquals(true, iniRealmDemo.helloShiro(username, password)); }
StaticCglibProxyDemo extends UserServiceImpl { @Override public void removeUser(String name) { log.warn("before remove user"); super.removeUser(name); log.warn("after remove user"); } @Override void addUser(String name); @Override void removeUser(String name); @Override String getUsername(String name); }
@Test void removeUser() { }
StaticCglibProxyDemo extends UserServiceImpl { @Override public String getUsername(String name) { log.warn("before get username"); String username = super.getUsername(name); log.warn("after get username"); return username; } @Override void addUser(String name); @Override void removeUser(String name); @Override String getUsername(String name); }
@Test void getUsername() { }
JDKProxyDemo { public UserService getUserService(){ ProxyHandler proxyHandler = new ProxyHandler(userService); return (UserService) Proxy.newProxyInstance(proxyHandler.getClass().getClassLoader(),userService.getClass().getInterfaces(),proxyHandler); } UserService getUserService(); }
@Test void getUserService() { jdkProxyDemo.getUserService().addUser("xiaoming"); jdkProxyDemo.getUserService().removeUser("xiaoming"); jdkProxyDemo.getUserService().getUsername("xiaoming"); System.out.println(); jdkProxyDemo.getUserService().getClass(); } @Test void getUserService2(){ jdkProxyDemo.getUserService().getUsernameFromSelf("xiaoming"); }
CglibProxyDemo { public UserService getUserService(){ Enhancer en = new Enhancer(); en.setSuperclass(userService.getClass()); en.setCallback((MethodInterceptor) (arg0, method, args, arg3) -> { log.info("pre class: {} method: {} return type:{} args:{}", userService.getClass().getName(),method.getName(),method.getReturnType(),args); Object result = method.invoke(userService, args); log.info("post class: {} method: {} return type:{} result:{}", userService.getClass().getName(),method.getName(),method.getReturnType(),result); return result; }); return (UserService) en.create(); } UserService getUserService(); }
@Test void getUserService() { cglibProxyDemo.getUserService().getUsernameFromSelf("xiaoming"); } @Test void getUserService1() { cglibProxyDemo.getUserService().getUsername("xiaoming"); }
LogAop { @Pointcut("execution(public * org.laidu.learn.spring.aop.service..*(..))") public void serviceLog(){} @Pointcut("execution(* org.laidu.learn.spring.aop.service..*(..))") void serviceLog(); @Before("serviceLog()") void doBefore(JoinPoint joinPoint); @AfterReturning(returning = "ret", pointcut = "serviceLog()") void doAfterReturning(Object ret); }
@Test void serviceLog() { userService.getUsername("xiaomig"); }
UserServiceImpl implements UserService { @Override @Cacheable("getUserInfo") public UserInfo getUserInfo(String key) { UserInfo userInfo = redisTemplate.opsForValue().get(key); if (userInfo == null) { log.info("cache null : {}", key); userInfo = addUser("demo","demo"); } return userInfo; } @Autowired UserServiceImpl(RedisTemplate<String, UserInfo> redisTemplate); @Override @Cacheable("getUserInfo") UserInfo getUserInfo(String key); @Override @Cacheable("userinfo") UserInfo addUser(String username, String password); @Override UserInfo updateUsername(String id, String username); }
@Test void getUserInfo() { UserInfo userInfo = userService.getUserInfo("xiaoming"); log.info("user info: {}", userInfo); }
UserServiceImpl implements UserService { @Override @Cacheable("userinfo") public UserInfo addUser(String username, String password) { return UserInfo.builder() .userId(UUID.randomUUID().toString()) .username(username) .build(); } @Autowired UserServiceImpl(RedisTemplate<String, UserInfo> redisTemplate); @Override @Cacheable("getUserInfo") UserInfo getUserInfo(String key); @Override @Cacheable("userinfo") UserInfo addUser(String username, String password); @Override UserInfo updateUsername(String id, String username); }
@Test void addUser() { UserInfo userInfo = userService.addUser("xiaoming","123123"); log.info("user info: {}", userInfo); }
UserServiceImpl implements UserService { @Override public UserInfo updateUsername(String id, String username) { boolean res = false; UserInfo info = null; RLock lock = redission.getLock("lock_"+id); try { lock.lock(10, TimeUnit.SECONDS); System.out.println("got lock"); }catch (Exception e){ log.warn("获取redis锁失败! {}",id); } finally { try{ lock.unlock(); }finally { System.out.println("unlock"); } } return info; } @Autowired UserServiceImpl(RedisTemplate<String, UserInfo> redisTemplate); @Override @Cacheable("getUserInfo") UserInfo getUserInfo(String key); @Override @Cacheable("userinfo") UserInfo addUser(String username, String password); @Override UserInfo updateUsername(String id, String username); }
@Test void updateUsername() { IntStream.range(0,1000).parallel() .forEach( i -> { userService.updateUsername("123","xiaoming"+i); }); }
SpringClientDemo implements ClientDemo { @Override public void declareQueue() throws IOException { RabbitAdmin rabbitAdmin = rabbitAdmin(); try { rabbitAdmin.declareQueue(new Queue("demo2",false,false,false)); }catch (Exception e){ try { if (406 == ((AMQImpl.Channel.Close) ((ShutdownSignalException)e.getCause().getCause()).getReason()).getReplyCode()) { rabbitAdmin.deleteQueue("demo2"); declareQueue(); } }catch (Exception e1){ } log.error("e 's value : {}", e); } } CachingConnectionFactory cachingConnectionFactory(); RabbitAdmin rabbitAdmin(); @Override void declareQueue(); static void main(String[] args); }
@Test void declareQueue() throws IOException { SpringClientDemo clientDemo = new SpringClientDemo(); clientDemo.declareQueue(); }
ExtendClass implements InterfaceA,InterfaceB { @Override public void sayHello() { log.debug("-*--*--*--*--*--*--*--*--*-- sayHello --*--*--*--*--*--*--*--*--*-: {}","123"); } @Override void sayHello(); @Override void sayBye(); @Override void sayGood(); static void main(String[] args); }
@Test @DisplayName("") void sayHello() { new ExtendClass().sayHello(); }
ExtendClass implements InterfaceA,InterfaceB { @Override public void sayBye() { ((InterfaceA) () -> log.debug("-*--*--*--*--*--*--*--*--*-- sayGood --*--*--*--*--*--*--*--*--*-: {}","good")).sayBye(); } @Override void sayHello(); @Override void sayBye(); @Override void sayGood(); static void main(String[] args); }
@Test void sayBye() { }
ExtendClass implements InterfaceA,InterfaceB { @Override public void sayGood() { log.debug("-*--*--*--*--*--*--*--*--*-- sayGood --*--*--*--*--*--*--*--*--*-: {}","good"); } @Override void sayHello(); @Override void sayBye(); @Override void sayGood(); static void main(String[] args); }
@Test void sayGood() { }
ListStreamDemo { public static String list2String(List<String> list){ return list.parallelStream().collect(Collectors.joining(",")); } static String list2String(List<String> list); static String list2String2(List<String> list); static List<Student> distinctBy(List<Student> students); }
@Test void list2String() { log.info("string result: {}", ListStreamDemo.list2String(list)); }
ListStreamDemo { public static String list2String2(List<String> list){ return String.join(",",list); } static String list2String(List<String> list); static String list2String2(List<String> list); static List<Student> distinctBy(List<Student> students); }
@Test void list2String2() { log.info("String2 result: {}", ListStreamDemo.list2String2(list)); }
StringPartMethod { public static String join(CharSequence delimiter, CharSequence... elements) { Objects.requireNonNull(delimiter); Objects.requireNonNull(elements); StringJoiner joiner = new StringJoiner(delimiter); for (CharSequence cs: elements) { joiner.add(cs); } return joiner.toString(); } static String join(CharSequence delimiter, CharSequence... elements); static String join(CharSequence delimiter, Iterable<? extends CharSequence> elements); }
@Test @DisplayName("java 8 新增方法") void join() { String var = "123123"; var = String.join(":", "a","b","c"); log.info("-*--*--*--*- var: {} -*--*--*--*--",var); } @Test void join1() { String var = "123123"; List<CharSequence> charSequences = Arrays.asList("a","b","c"); var = String.join("-",charSequences); log.info("-*--*--*--*- var: {} -*--*--*--*--",var); }
CurlParserUtil { public Map<String, String> getHeaders(String curlLine) { Map<String, String> keyValuePairs = keyValuePairs(curlLine); keyValuePairs.remove("Content-Length"); return keyValuePairs; } private CurlParserUtil(); static CurlParserUtil getInstance(); Map<String, String> getHeaders(String curlLine); Map<String, String> getCookies(String curlLine); String getMethod(String curlLine); String getUrl(String curlLine); String getBodyString(String curlLine); Map<String, String> getFormBody(String curlLine); }
@Test void getHeaders() { CurlParserUtil.getInstance().getHeaders(curlLine); }
CurlParserUtil { public Map<String, String> getCookies(String curlLine) { Map<String, String> cookieMap = new HashMap<>(); StringBuilder cookiesString = new StringBuilder(); cookiesString.append(getHeaders(curlLine).get("Cookie")); cookiesString.append(getBCookiesString(curlLine)); if (StringUtil.isNotBlank(cookiesString.toString())) { String cookiesPattern = "([^; ]*=[^;]*)+"; List<String> cookieStringList = RegexUtil.getInstance().getMacthAllResult(cookiesPattern,cookiesString.toString()); cookieStringList.forEach(cookie -> { String[] cookiePairs = cookie.split("=", 2); if (cookiePairs.length == 2) { cookieMap.put(cookiePairs[0].trim(), URLDecoder.decode(cookiePairs[1].trim())); } }); } return cookieMap; } private CurlParserUtil(); static CurlParserUtil getInstance(); Map<String, String> getHeaders(String curlLine); Map<String, String> getCookies(String curlLine); String getMethod(String curlLine); String getUrl(String curlLine); String getBodyString(String curlLine); Map<String, String> getFormBody(String curlLine); }
@Test void getCookies() { CurlParserUtil.getInstance().getCookies(curlLine).forEach((k,v) -> System.out.println(k + " : " + v)); }
CurlParserUtil { public String getMethod(String curlLine) { String methodPattern = "-X \\$'([A-Z]{2,5})'"; int methodIndex = 1; return RegexUtil.getInstance().getMacthResult(methodPattern, curlLine, methodIndex, "GET"); } private CurlParserUtil(); static CurlParserUtil getInstance(); Map<String, String> getHeaders(String curlLine); Map<String, String> getCookies(String curlLine); String getMethod(String curlLine); String getUrl(String curlLine); String getBodyString(String curlLine); Map<String, String> getFormBody(String curlLine); }
@Test void getMethod() { Assert.assertEquals("POST",CurlParserUtil.getInstance().getMethod(curlLine)); }
RabbitmqClientDemo implements ClientDemo { public ConnectionFactory connectionFactory(){ ConnectionFactory connectionFactory = new ConnectionFactory(); connectionFactory.setHost("dev"); connectionFactory.setPort(5672); connectionFactory.setUsername("admin"); connectionFactory.setPassword("admin"); connectionFactory.setVirtualHost("/learn"); return connectionFactory; } ConnectionFactory connectionFactory(); Connection connection(ConnectionFactory connectionFactory); @Override void declareQueue(); }
@Test void connectionFactory() { }
CurlParserUtil { public String getUrl(String curlLine) { String urlPattern = "\\$'(https?: int urlIndex = 1; return RegexUtil.getInstance().getMacthResult(urlPattern, curlLine, urlIndex); } private CurlParserUtil(); static CurlParserUtil getInstance(); Map<String, String> getHeaders(String curlLine); Map<String, String> getCookies(String curlLine); String getMethod(String curlLine); String getUrl(String curlLine); String getBodyString(String curlLine); Map<String, String> getFormBody(String curlLine); }
@Test void getUrl() { Assert.assertEquals("http: }
CurlParserUtil { public String getBodyString(String curlLine) { String stringBodyPattern = "--data-binary \\$'([^\\$]*)'"; int stringBodyIndex = 1; return RegexUtil.getInstance().getMacthResult(stringBodyPattern, curlLine, stringBodyIndex); } private CurlParserUtil(); static CurlParserUtil getInstance(); Map<String, String> getHeaders(String curlLine); Map<String, String> getCookies(String curlLine); String getMethod(String curlLine); String getUrl(String curlLine); String getBodyString(String curlLine); Map<String, String> getFormBody(String curlLine); }
@Test void getBodyString() { String dataString = "jlX3dWILl/dMQ+wc0JAMHlKhylfeLb19HyBcb/QKcPKRMtB5Ri77QJ2OpC6P8Rp/aai3j7awGyo1SD/MckKxnHTeGnUIh9Uopg7S+4Db1n8hVV9vsQMLrmZy+0VCnGFgVuTWYvMgiow9+tZJFFdQ549IhLmXBs4Lm3UkEtzpfvwfdoCZC9vAaTbvc6YrGFk9vTRUag3oT+Wlm+RY8KaejV7JXCzV4+jA98GFbVTAn4yNuPIyIoHyhoELsnvMwlbuVmftKn0DDlVWM7xt7P9+AMiyXbNu+2xMuW6w+1EK Assert.assertEquals(dataString,CurlParserUtil.getInstance().getBodyString(curlLine)); }
CurlParserUtil { public Map<String, String> getFormBody(String curlLine) { Map<String, String> formMap = new HashMap<>(); String formBodyString = getBodyString(curlLine); String formDataPattern = "([^=&]+=[^&']*)+"; int formDataIndex = 1; List<String> formStringList = RegexUtil.getInstance().getMacthAllResult(formDataPattern, formBodyString, formDataIndex); formStringList.forEach(formString -> { String[] form = formString.split("=",2); if (form.length==2) { formMap.put(form[0].trim(),form[1].trim()); } }); return formMap; } private CurlParserUtil(); static CurlParserUtil getInstance(); Map<String, String> getHeaders(String curlLine); Map<String, String> getCookies(String curlLine); String getMethod(String curlLine); String getUrl(String curlLine); String getBodyString(String curlLine); Map<String, String> getFormBody(String curlLine); }
@Test void getFormBody() { CurlParserUtil.getInstance().getFormBody(curlLine).forEach((k,v) -> System.out.println(k + " : " + v)); }
JAXBUtil { public String obj2Xml(Object obj) throws JAXBException, UnsupportedEncodingException { ByteArrayOutputStream os = new ByteArrayOutputStream(); JAXBContext jaxbContext = JAXBContext.newInstance(obj.getClass()); Marshaller jaxbMarshaller = jaxbContext.createMarshaller(); jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true ); jaxbMarshaller.marshal(obj,os); return new String(os.toByteArray(),"UTF-8"); } private JAXBUtil(); static JAXBUtil getInstance(); String obj2Xml(Object obj); T xml2Obj(String xmlSource, Class<T> clazz); }
@Test void obj2Xml() throws JAXBException, UnsupportedEncodingException { List<String> names = new ArrayList<>(); names.add("123"); names.add("123"); names.add("123"); names.add("123"); Person person = Person.builder() .name("xiaoming/name>aadsadsa]") .dsaa(names) .sex("nam") .build(); List<Person> people = new ArrayList<>(); people.add(person); people.add(person); people.add(person); people.add(person); String result = JAXBUtil.getInstance().obj2Xml(Person1.builder().person(people).build()); System.out.println(result); }
JAXBUtil { public <T> T xml2Obj(String xmlSource, Class<T> clazz) throws JAXBException { JAXBContext context; context = JAXBContext.newInstance(clazz); Unmarshaller unmarshal = context.createUnmarshaller(); T obj = (T) unmarshal.unmarshal(new StringReader(xmlSource)); return obj; } private JAXBUtil(); static JAXBUtil getInstance(); String obj2Xml(Object obj); T xml2Obj(String xmlSource, Class<T> clazz); }
@Test void xml2Obj() throws JAXBException { String xmlSource = "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>\n" + "<persons>\n" + " <person>\n" + " <dsaa>123</dsaa>\n" + " <dsaa>123</dsaa>\n" + " <dsaa>123</dsaa>\n" + " <dsaa>123</dsaa>\n" + " <name>xiaoming/name&gt;aadsadsa]</name>\n" + " <sex>nam</sex>\n" + " </person>\n" + " <person>\n" + " <dsaa>123</dsaa>\n" + " <dsaa>123</dsaa>\n" + " <dsaa>123</dsaa>\n" + " <dsaa>123</dsaa>\n" + " <name>xiaoming/name&gt;aadsadsa]</name>\n" + " <sex>nam</sex>\n" + " </person>\n" + " <person>\n" + " <dsaa>123</dsaa>\n" + " <dsaa>123</dsaa>\n" + " <dsaa>123</dsaa>\n" + " <dsaa>123</dsaa>\n" + " <name>xiaoming/name&gt;aadsadsa]</name>\n" + " <sex>nam</sex>\n" + " </person>\n" + " <person>\n" + " <dsaa>123</dsaa>\n" + " <dsaa>123</dsaa>\n" + " <dsaa>123</dsaa>\n" + " <dsaa>123</dsaa>\n" + " <name>xiaoming/name&gt;aadsadsa]</name>\n" + " <sex>nam</sex>\n" + " </person>\n" + "</persons>"; Person1 person1 = JAXBUtil.getInstance().xml2Obj(xmlSource,Person1.class); System.out.println(); }
RegexUtil { public List<String> getMacthAllResult(String regex, String source, int index) { return getMacthAllResult(Pattern.compile(regex),source,index); } private RegexUtil(); static RegexUtil getInstance(); List<String> getMacthAllResult(String regex, String source, int index); List<String> getMacthAllResult(Pattern pattern, String source, int index); List<String> getMacthAllResult(String regex, String source); List<String> getMacthAllResult(Pattern pattern, String source); String getMacthResult(String regex, String source, int index); String getMacthResult(Pattern pattern, String source, int index); String getMacthResult(String regex, String source); String getMacthResult(Pattern pattern, String source); String getMacthResult(String regex, String source, int index, String defaultValue); String getMacthResult(Pattern pattern, String source, int index, String defaultValue); }
@Test void getMacthAllResult() { }
RegexUtil { public String getMacthResult(String regex, String source, int index) { return getMacthResult(regex,source,index,null); } private RegexUtil(); static RegexUtil getInstance(); List<String> getMacthAllResult(String regex, String source, int index); List<String> getMacthAllResult(Pattern pattern, String source, int index); List<String> getMacthAllResult(String regex, String source); List<String> getMacthAllResult(Pattern pattern, String source); String getMacthResult(String regex, String source, int index); String getMacthResult(Pattern pattern, String source, int index); String getMacthResult(String regex, String source); String getMacthResult(Pattern pattern, String source); String getMacthResult(String regex, String source, int index, String defaultValue); String getMacthResult(Pattern pattern, String source, int index, String defaultValue); }
@Test void getMacthResult() { String exected = "uuid_tt_dd=1449951587432284316_20171009; bdshare_firstime=1507526697430; _JQCMT_ifcookie=1; _JQCMT_browser=9b9bfcf50ae6c14645788efed25613f9; UN=weixin_38032099; UE=\\\"\\\"; BT=1509089267060; ADHOC_MEMBERSHIP_CLIENT_ID1.0=f4889c67-3d52-6eb3-6cb4-e7a329d9b3c5; Hm_ct_6bcd52f51e9b3dce32bec4a3997715ac=1788*1*PC_VC; __utma=17226283.2019445080.1508118317.1508118317.1512040235.2; __utmz=17226283.1512040235.2.2.utmcsr=google|utmccn=(organic)|utmcmd=organic|utmctr=(not%20provided); uuid=f46ae314-3c9c-41e4-89a8-be900dd703ed; Hm_lvt_6bcd52f51e9b3dce32bec4a3997715ac=1512105168,1512105684,1512108075,1512109410; Hm_lpvt_6bcd52f51e9b3dce32bec4a3997715ac=1512109410; dc_tos=p09r36; dc_session_id=1512108074250"; Assert.assertEquals(exected,RegexUtil.getInstance().getMacthResult("-b \\$'([^']*)'",source,1)); }
AESEncryptionUtil { public byte[] cbcEncrypt(byte[] data, byte[] key, byte[] ivp) { return BasicEncryptionUtil.getInstance().encrypt(HelperHolder.ALGORITHM, HelperHolder.ALGORITHM_CBC_KEY, key, ivp, data); } private AESEncryptionUtil(); static AESEncryptionUtil getInstance(); byte[] cbcEncrypt(byte[] data, byte[] key, byte[] ivp); byte[] cbcDecrypt(byte[] data, byte[] key, byte[] ivp); byte[] ecbEncrypt(byte[] data, byte[] key); byte[] ecbDecrypt(byte[] data, byte[] key); }
@Test void cbcEncrypt() throws DecoderException { byte[] result = AESEncryptionUtil.getInstance().cbcEncrypt(palaintext.getBytes(), key.getBytes(), Base64.decode(ivp)); log.info("result 's value : {}", result); Assert.assertEquals(URLDecoder.decode(cryptograph), Base64.encodeToString(result)); }
AESEncryptionUtil { public byte[] cbcDecrypt(byte[] data, byte[] key, byte[] ivp) { return BasicEncryptionUtil.getInstance().decrypt(HelperHolder.ALGORITHM, HelperHolder.ALGORITHM_CBC_KEY, key, ivp, data); } private AESEncryptionUtil(); static AESEncryptionUtil getInstance(); byte[] cbcEncrypt(byte[] data, byte[] key, byte[] ivp); byte[] cbcDecrypt(byte[] data, byte[] key, byte[] ivp); byte[] ecbEncrypt(byte[] data, byte[] key); byte[] ecbDecrypt(byte[] data, byte[] key); }
@Test void cbcDecrypt() throws Exception { byte[] result = AESEncryptionUtil.getInstance().cbcDecrypt(Base64.decode(cryptograph), key.getBytes(), Base64.decode(ivp)); log.info("result 's value : {}", new String(result)); Assert.assertEquals(URLDecoder.decode(palaintext), new String(result)); }
AESEncryptionUtil { public byte[] ecbDecrypt(byte[] data, byte[] key){ return BasicEncryptionUtil.getInstance().decrypt(HelperHolder.ALGORITHM, HelperHolder.ALGORITHM_ECB_KEY, key, null, data); } private AESEncryptionUtil(); static AESEncryptionUtil getInstance(); byte[] cbcEncrypt(byte[] data, byte[] key, byte[] ivp); byte[] cbcDecrypt(byte[] data, byte[] key, byte[] ivp); byte[] ecbEncrypt(byte[] data, byte[] key); byte[] ecbDecrypt(byte[] data, byte[] key); }
@Test void ecbDecrypt() throws DecoderException, UnsupportedEncodingException { String source = "1d6ca0a793eba254b4950253b11b7897860c497ee6cae7f3b2d8035beccb5ab41411467a32786a72a7b2809952fa5a804a37a4028f72b48cd7e22bc3d400b43358f40c327900dff1dc14c322506b4aba87375aa7e0d3b6689eb52fd06ba30ae3"; String key = "q9YCl%!3*m#d&3Ke"; System.out.println(Base64.encodeToString(Hex.decodeHex(source.toCharArray()))); byte[] reponse = {120,-100,-85,86,74,45,42,-54,47,114,-50,79,73,85,-78,82,-78,4,2,37,29,-91,-36,-44,-30,-30,-60,116,-112,-64,-117,-11,75,95,108,89,-10,-76,127,-5,-45,13,-77,-98,-51,89,-11,108,-13,-118,-89,109,61,74,-75,0,69,58,25,83}; System.out.println(new String(reponse,"utf-8")); byte[] result = AESEncryptionUtil.getInstance().ecbDecrypt(reponse,key.getBytes()); System.out.println("source : "+ new String(AESEncryptionUtil.getInstance().ecbDecrypt(Base64.decode(result),key.getBytes()))); }
RabbitmqClientDemo implements ClientDemo { public Connection connection(ConnectionFactory connectionFactory){ Connection connection = null; try { connection = connectionFactory.newConnection(); } catch (Exception e) { log.error("connection create error", e); } return connection; } ConnectionFactory connectionFactory(); Connection connection(ConnectionFactory connectionFactory); @Override void declareQueue(); }
@Test void connection() { }
MD5Util { public String toMd5(String origin){ String re_md5 = ""; try { MessageDigest md = MessageDigest.getInstance("MD5"); md.update(origin.getBytes()); byte b[] = md.digest(); md = null; int i; StringBuffer buf = new StringBuffer(""); for (int offset = 0; offset < b.length; offset++) { i = b[offset]; if (i < 0) { i += 256; } if (i < 16) { buf.append("0"); } buf.append(Integer.toHexString(i)); } re_md5 = buf.toString(); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } return re_md5; } private MD5Util(); static MD5Util getInstance(); String toMd5(String origin); }
@Test void toMd5() { }
RSAencryptionUtil { public RSAPublicKey getpublicKey(Map<String, Object> keyMap){ RSAPublicKey publicKey = (RSAPublicKey) keyMap.get(HelperHolder.PUBLIC_KEY); return publicKey; } private RSAencryptionUtil(); static RSAencryptionUtil getInstance(); Map<String, Object> initKey(); RSAPublicKey getpublicKey(Map<String, Object> keyMap); RSAPrivateKey getPrivateKey(Map<String, Object> keyMap); byte[] encrypt(byte[] data, RSAPublicKey publicKey); byte[] decrypt(byte[] data, RSAPrivateKey privateKey); }
@Test void getpublicKey() throws NoSuchAlgorithmException, InvalidKeySpecException { bigIntModulus = new BigInteger("bcd32d940d9b013a26767c2a60817a275c688cce324f421e40cb4282bb4f914171c7d362d3ecd651c7391ab1999b1b8a440058a869b53c481d9482370d92afc97b2cb955beb214186a060913748140280e9ecbd4af9cac2765efbc6f7a4c5f5d7b2ab183e7eafd2950dd6425a3f386cb82b0a6fc3b2fe7006c9e1c1a665f28f2fdca56b68b14e622abbd7d9a338297a12a1767bb2066d3711c00e9bce485300fb7039e811ec2dda78fbed61047a93f9e6b82627679af87ab64e8d0480d1db4aee110b3423e599c73cddaa98dbfda93b0c6c7dca54a744e9ecbba2cce26aeba293003f03e6496242671c93368fa325cbe346244d7837aa2fdb4eb5e18fcfaf891",16); bigIntPrivateExponent =new BigInteger("10001",16); palaintext = "{\"latitude\":\"39.921094\",\"loginName\":\"13241847378\",\"deviceId\":\"fd40d837-7a47-340d-8047-d7882d47ff7f\",\"versionCode\":362,\"loginPwd\":\"903198FC13E1963F30834F0AE04A1ACF\",\"longitude\":\"116.419445 \",\"loginKind\":\"normal\"}"; cryptograph = "JC8dE6A/GaHt48dkk5QcpFPBh4sgW913s4CFjZIb/0RShdoHgNPHK22Ove11yES4/TE/d+jQXqApGEV4BKr9DsOC4MkOc1+BuUUQyXmzHvU5NQMHVN5U4EH++idWCJZqSU1IdV0cph5+kY4zX0+523Jh0TrzPnA1HeN7ilg3Xw9IWpa8Z/6nKA/yast DZz3tUzMhcDQvxsonN+Yfb/bIdMJxMvi0KKTnXjvAuISaehv49Ti5n1fv6M2O2awVz+6CMjY8OHn9mxhuivVQpryyK3Bj30VfYqSRtbTYNF0PI4OFUDFI6RFJWJD4G9OqCu8mHdhQYLEgYhH93ttnl2xDfQ=="; RSAPublicKeySpec keySpec = new RSAPublicKeySpec(bigIntModulus,bigIntPrivateExponent); KeyFactory keyFactory = KeyFactory.getInstance("RSA"); RSAPublicKey rsaPublicKey = (RSAPublicKey) keyFactory.generatePublic(keySpec); byte[] result = null; result = RSAencryptionUtil.getInstance().encrypt(palaintext.getBytes(),rsaPublicKey); log.info("result 's value : {}", Base64.encodeToString(result)); result = RSAencryptionUtil.getInstance().encrypt(palaintext.getBytes(),rsaPublicKey); log.info("result 's value : {}", Base64.encodeToString(result)); } @Test void getPublicKey() throws Exception { X509EncodedKeySpec keySpec = new X509EncodedKeySpec(Base64.decode("MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCKNwbSS18PD+lq/kthgNhRv4kmErhqC9X+VLPsbAFRojB+Hiohx7uuD+xcoxfB6BvcKKvPd2/WLDhVlOxsKFlWlzVZG7rCaP38e77jdgDmAVJtmZmyaW/q09fxR8dtwVqiwPtpNUeBWWh1lrtUarY8cQ8KFg5tNYqvqQJ9bN3TAwIDAQAB")); RSAPublicKey publicKey = (RSAPublicKey) KeyFactory.getInstance("RSA").generatePublic(keySpec); Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding"); cipher.init(Cipher.ENCRYPT_MODE,publicKey); byte[] result = cipher.doFinal(new BigInteger("7B7D",16).toByteArray()); System.out.println(Base64.encodeToString(result)); String cryptograph = "PyTBokP3d9gnntWM\\/iXiDbGvSDcMjqkDZcP6YrQBzrzwCUQfOVHSlt8NHd3NEdnEFsZEBVlHwznh2vfEs5AWT9qxNiTkRgEACP5QpJQPq51htp\\/kG\\/LHKHlGf21Onra80P0gyQ+AYbqMunQOCpf2mh0pbSyw2DGy5nf5iGLzOCw="; RSAPrivateKey privateKey = (RSAPrivateKey) KeyFactory.getInstance("RSA").generatePrivate(keySpec); cipher.init(Cipher.DECRYPT_MODE,privateKey); result = cipher.doFinal(Base64.decode(cryptograph)); System.out.println(Base64.encodeToString(result)); }
RSAencryptionUtil { public RSAPrivateKey getPrivateKey(Map<String, Object> keyMap){ RSAPrivateKey privateKey = (RSAPrivateKey) keyMap.get(HelperHolder.PRIVATE_KEY); return privateKey; } private RSAencryptionUtil(); static RSAencryptionUtil getInstance(); Map<String, Object> initKey(); RSAPublicKey getpublicKey(Map<String, Object> keyMap); RSAPrivateKey getPrivateKey(Map<String, Object> keyMap); byte[] encrypt(byte[] data, RSAPublicKey publicKey); byte[] decrypt(byte[] data, RSAPrivateKey privateKey); }
@Test void getPrivateKey() { }
RSAencryptionUtil { public byte[] encrypt(byte[] data, RSAPublicKey publicKey){ return BasicEncryptionUtil.getInstance().encrypt(HelperHolder.ALGOROTHM_KEY,publicKey,data); } private RSAencryptionUtil(); static RSAencryptionUtil getInstance(); Map<String, Object> initKey(); RSAPublicKey getpublicKey(Map<String, Object> keyMap); RSAPrivateKey getPrivateKey(Map<String, Object> keyMap); byte[] encrypt(byte[] data, RSAPublicKey publicKey); byte[] decrypt(byte[] data, RSAPrivateKey privateKey); }
@Test void encrypt() throws NoSuchAlgorithmException, InvalidKeySpecException { bigIntModulus = new BigInteger("8a3706d24b5f0f0fe96afe4b6180d851bf892612b86a0bd5fe54b3ec6c0151a2307e1e2a21c7bbae0fec5ca317c1e81bdc28abcf776fd62c385594ec6c2859569735591bbac268fdfc7bbee37600e601526d9999b2696fead3d7f147c76dc15aa2c0fb6935478159687596bb546ab63c710f0a160e6d358aafa9027d6cddd303",16); bigIntPrivateExponent =new BigInteger("10001",16); palaintext = "{\"latitude\":\"39.921094\",\"loginName\":\"13241847378\",\"deviceId\":\"fd40d837-7a47-340d-8047-d7882d47ff7f\",\"versionCode\":362,\"loginPwd\":\"903198FC13E1963F30834F0AE04A1ACF\",\"longitude\":\"116.419445 \",\"loginKind\":\"normal\"}"; cryptograph = "JC8dE6A/GaHt48dkk5QcpFPBh4sgW913s4CFjZIb/0RShdoHgNPHK22Ove11yES4/TE/d+jQXqApGEV4BKr9DsOC4MkOc1+BuUUQyXmzHvU5NQMHVN5U4EH++idWCJZqSU1IdV0cph5+kY4zX0+523Jh0TrzPnA1HeN7ilg3Xw9IWpa8Z/6nKA/yast DZz3tUzMhcDQvxsonN+Yfb/bIdMJxMvi0KKTnXjvAuISaehv49Ti5n1fv6M2O2awVz+6CMjY8OHn9mxhuivVQpryyK3Bj30VfYqSRtbTYNF0PI4OFUDFI6RFJWJD4G9OqCu8mHdhQYLEgYhH93ttnl2xDfQ=="; RSAPublicKeySpec keySpec = new RSAPublicKeySpec(bigIntModulus,bigIntPrivateExponent); KeyFactory keyFactory = KeyFactory.getInstance("RSA"); RSAPublicKey rsaPublicKey = (RSAPublicKey) keyFactory.generatePublic(keySpec); byte[] result = null; result = RSAencryptionUtil.getInstance().encrypt("13241847378".getBytes(),rsaPublicKey); log.info("result 's value : {}", Base64.encodeToString(result)); result = RSAencryptionUtil.getInstance().encrypt(palaintext.getBytes(),rsaPublicKey); log.info("result 's value : {}", Base64.encodeToString(result)); }
RSAencryptionUtil { public byte[] decrypt(byte[] data, RSAPrivateKey privateKey) throws Exception{ return BasicEncryptionUtil.getInstance().decrypt(HelperHolder.ALGOROTHM_KEY,privateKey,data); } private RSAencryptionUtil(); static RSAencryptionUtil getInstance(); Map<String, Object> initKey(); RSAPublicKey getpublicKey(Map<String, Object> keyMap); RSAPrivateKey getPrivateKey(Map<String, Object> keyMap); byte[] encrypt(byte[] data, RSAPublicKey publicKey); byte[] decrypt(byte[] data, RSAPrivateKey privateKey); }
@Test void decrypt() throws Exception { }