├── README.md ├── java-06-gson ├── src │ ├── test │ │ ├── resources │ │ │ └── car.json │ │ └── java │ │ │ └── ai │ │ │ └── incredible │ │ │ └── gson │ │ │ └── GsonTest.java │ └── main │ │ └── java │ │ └── ai │ │ └── incredible │ │ └── gson │ │ ├── Main.java │ │ └── Car.java └── build.gradle ├── java-12-cassandra ├── src │ ├── main │ │ └── java │ │ │ └── ai │ │ │ └── incredible │ │ │ └── cassandra │ │ │ ├── Main.java │ │ │ └── DataBean.java │ └── test │ │ └── java │ │ └── ai │ │ └── incredible │ │ └── cassandra │ │ └── SparkTest.java └── build.gradle ├── java-05-protobuf ├── src │ ├── main │ │ ├── java │ │ │ └── ai │ │ │ │ └── incredible │ │ │ │ └── protobuf │ │ │ │ └── Main.java │ │ └── proto │ │ │ └── my.proto │ └── test │ │ └── java │ │ └── ai │ │ └── incredible │ │ └── protobuf │ │ └── MyProtobufTest.java └── build.gradle ├── gradle └── wrapper │ └── gradle-wrapper.properties ├── java-04-spark ├── src │ ├── main │ │ └── java │ │ │ └── ai │ │ │ └── incredible │ │ │ └── spark │ │ │ └── Main.java │ └── test │ │ └── java │ │ └── ai │ │ └── incredible │ │ └── spark │ │ ├── SparkContextTest.java │ │ └── SparkTest.java └── build.gradle ├── java-03-solr ├── src │ ├── main │ │ ├── java │ │ │ └── ai │ │ │ │ └── incredible │ │ │ │ └── solr │ │ │ │ ├── User.java │ │ │ │ └── Location.java │ │ └── resources │ │ │ └── data.json │ └── test │ │ ├── resources │ │ └── geodata.json │ │ └── java │ │ └── ai │ │ └── incredible │ │ └── solr │ │ └── SolrTest.java └── build.gradle ├── java-01-unittest ├── src │ ├── main │ │ └── java │ │ │ └── ai │ │ │ └── incredible │ │ │ └── unittest │ │ │ └── Calculator.java │ └── test │ │ └── java │ │ └── ai │ │ └── incredible │ │ └── unittest │ │ ├── CastingTeset.java │ │ └── CalculatorTest.java └── build.gradle ├── settings.gradle ├── java-11-caffeine ├── src │ ├── main │ │ └── java │ │ │ └── ai │ │ │ └── incredible │ │ │ └── caffeine │ │ │ ├── Data.java │ │ │ └── Main.java │ └── test │ │ └── java │ │ └── ai │ │ └── incredible │ │ └── caffeine │ │ └── MainTest.java └── build.gradle ├── code-01-simple ├── build.gradle └── src │ ├── main │ └── java │ │ └── ai │ │ └── incredible │ │ └── code │ │ └── _01TwoSum.java │ └── test │ └── java │ └── ai │ └── incredible │ └── code │ └── _01TwoSumTest.java ├── .gitignore ├── java-02-grpc ├── src │ ├── main │ │ ├── proto │ │ │ └── andersonServer.proto │ │ └── java │ │ │ └── ai │ │ │ └── incredible │ │ │ └── grpc │ │ │ ├── AndersonServer.java │ │ │ └── AndersonClient.java │ └── test │ │ └── java │ │ └── ai │ │ └── incredible │ │ └── grpc │ │ ├── AndersonServerTest.java │ │ └── AndersonClientTest.java └── build.gradle ├── java-10-lightgbm ├── build.gradle └── src │ └── main │ └── java │ └── ai │ └── incredible │ └── lightgbm │ └── Main.java └── gradlew /README.md: -------------------------------------------------------------------------------- 1 | Installation 2 | 3 | ## Solr 4 | 5 | -------------------------------------------------------------------------------- /java-06-gson/src/test/resources/car.json: -------------------------------------------------------------------------------- 1 | { 2 | "brand": "Samsung", 3 | "power": 123 4 | } -------------------------------------------------------------------------------- /java-06-gson/src/main/java/ai/incredible/gson/Main.java: -------------------------------------------------------------------------------- 1 | package ai.incredible.gson; 2 | 3 | public class Main { 4 | public static void main(String[] args) { 5 | System.out.println("Hello world!"); 6 | } 7 | } -------------------------------------------------------------------------------- /java-12-cassandra/src/main/java/ai/incredible/cassandra/Main.java: -------------------------------------------------------------------------------- 1 | package ai.incredible.cassandra; 2 | 3 | public class Main { 4 | public static void main(String[] args) { 5 | System.out.println("Hello world!"); 6 | } 7 | } -------------------------------------------------------------------------------- /java-05-protobuf/src/main/java/ai/incredible/protobuf/Main.java: -------------------------------------------------------------------------------- 1 | package ai.incredible.protobuf; 2 | 3 | public class Main { 4 | public static void main(String[] args) { 5 | System.out.println("Hello world!"); 6 | } 7 | } -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.properties: -------------------------------------------------------------------------------- 1 | distributionBase=GRADLE_USER_HOME 2 | distributionPath=wrapper/dists 3 | distributionUrl=https\://services.gradle.org/distributions/gradle-7.2-bin.zip 4 | zipStoreBase=GRADLE_USER_HOME 5 | zipStorePath=wrapper/dists 6 | -------------------------------------------------------------------------------- /java-04-spark/src/main/java/ai/incredible/spark/Main.java: -------------------------------------------------------------------------------- 1 | package ai.incredible.spark; 2 | import org.apache.spark.sql.SparkSession; 3 | 4 | public class Main { 5 | public static void main(String[] args) { 6 | System.out.println("Hello world!"); 7 | } 8 | } -------------------------------------------------------------------------------- /java-06-gson/src/main/java/ai/incredible/gson/Car.java: -------------------------------------------------------------------------------- 1 | package ai.incredible.gson; 2 | 3 | public class Car { 4 | public String brand; 5 | public int power; 6 | public boolean missing; 7 | public boolean missingTrue = true; 8 | public boolean missingFalse = false; 9 | } 10 | -------------------------------------------------------------------------------- /java-03-solr/src/main/java/ai/incredible/solr/User.java: -------------------------------------------------------------------------------- 1 | package ai.incredible.solr; 2 | 3 | import lombok.Getter; 4 | import lombok.Setter; 5 | 6 | @Getter 7 | @Setter 8 | public class User { 9 | private String name; 10 | private int userId; 11 | private int age; 12 | private String[] tags; 13 | 14 | } 15 | -------------------------------------------------------------------------------- /java-01-unittest/src/main/java/ai/incredible/unittest/Calculator.java: -------------------------------------------------------------------------------- 1 | package ai.incredible.unittest; 2 | 3 | public class Calculator { 4 | public static void main(String[] args) { 5 | System.out.println("Hello world!"); 6 | } 7 | 8 | public int sum(int a, int b) { 9 | return a + b; 10 | } 11 | } -------------------------------------------------------------------------------- /java-05-protobuf/src/main/proto/my.proto: -------------------------------------------------------------------------------- 1 | syntax = "proto3"; 2 | package tutorial; 3 | 4 | option java_multiple_files = true; 5 | option java_package = "ai.incredible.protobuf"; 6 | option java_outer_classname = "MyProtobuf"; 7 | 8 | 9 | message Person { 10 | string name = 1; 11 | int32 age = 2; 12 | repeated string tags=3; 13 | } -------------------------------------------------------------------------------- /settings.gradle: -------------------------------------------------------------------------------- 1 | rootProject.name = 'java-anderson' 2 | include 'code-01-simple' 3 | include 'java-01-unittest' 4 | include 'java-02-grpc' 5 | include 'java-03-solr' 6 | include 'java-04-spark' 7 | include 'java-05-protobuf' 8 | include 'java-06-gson' 9 | include 'java-10-lightgbm' 10 | include 'java-11-caffeine' 11 | include 'java-12-cassandra' 12 | 13 | -------------------------------------------------------------------------------- /java-11-caffeine/src/main/java/ai/incredible/caffeine/Data.java: -------------------------------------------------------------------------------- 1 | package ai.incredible.caffeine; 2 | 3 | import lombok.Builder; 4 | import lombok.Getter; 5 | 6 | import java.io.Serializable; 7 | 8 | @Builder 9 | public class Data implements Serializable { 10 | 11 | @Getter 12 | private int money; 13 | 14 | @Getter 15 | private String name; 16 | } 17 | -------------------------------------------------------------------------------- /java-03-solr/src/main/java/ai/incredible/solr/Location.java: -------------------------------------------------------------------------------- 1 | package ai.incredible.solr; 2 | 3 | import lombok.Getter; 4 | import lombok.Setter; 5 | 6 | @Getter 7 | @Setter 8 | public class Location { 9 | 10 | private String name; 11 | private int age; 12 | private String ab; 13 | private double lat; 14 | private double lng; 15 | 16 | } 17 | -------------------------------------------------------------------------------- /java-04-spark/src/test/java/ai/incredible/spark/SparkContextTest.java: -------------------------------------------------------------------------------- 1 | package ai.incredible.spark; 2 | 3 | import org.apache.spark.SparkConf; 4 | 5 | public class SparkContextTest { 6 | 7 | public SparkContextTest() { 8 | SparkConf conf = new SparkConf() 9 | .setAppName("Spark Conf Test") 10 | .setMaster("local[*]"); 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /code-01-simple/build.gradle: -------------------------------------------------------------------------------- 1 | plugins { 2 | id 'java' 3 | } 4 | 5 | group 'ai.incredible.code.simple' 6 | version '1.0-SNAPSHOT' 7 | 8 | repositories { 9 | mavenCentral() 10 | } 11 | 12 | dependencies { 13 | testImplementation 'org.junit.jupiter:junit-jupiter-api:5.8.1' 14 | testRuntimeOnly 'org.junit.jupiter:junit-jupiter-engine:5.8.1' 15 | } 16 | 17 | test { 18 | useJUnitPlatform() 19 | } -------------------------------------------------------------------------------- /java-12-cassandra/src/main/java/ai/incredible/cassandra/DataBean.java: -------------------------------------------------------------------------------- 1 | package ai.incredible.cassandra; 2 | 3 | import lombok.Data; 4 | import lombok.ToString; 5 | 6 | import java.sql.Timestamp; 7 | 8 | @Data 9 | @ToString 10 | public class DataBean { 11 | protected String uid; 12 | protected String name; 13 | protected Integer age; 14 | protected Boolean married; 15 | protected Timestamp createdAt; 16 | protected Long writetime; 17 | } 18 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # IDE 2 | .idea 3 | *.iml 4 | *.ipr 5 | *.iws 6 | 7 | # Package Files # 8 | *.class 9 | *.jar 10 | *.war 11 | *.nar 12 | *.ear 13 | *.zip 14 | *.tar.gz 15 | *.rar 16 | 17 | 18 | # virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml 19 | hs_err_pid* 20 | replay_pid* 21 | 22 | # Gradle 23 | .gradle 24 | .gradletasknamecache 25 | build/ 26 | bin/ 27 | 28 | # Files 29 | *.log 30 | *.ctxt 31 | bin/** 32 | gen/** -------------------------------------------------------------------------------- /java-01-unittest/src/test/java/ai/incredible/unittest/CastingTeset.java: -------------------------------------------------------------------------------- 1 | package ai.incredible.unittest; 2 | 3 | import static org.junit.jupiter.api.Assertions.assertEquals; 4 | 5 | import org.junit.jupiter.api.Test; 6 | 7 | public class CastingTeset { 8 | 9 | @Test 10 | void testLong(){ 11 | Long value = 13L; 12 | value = Long.parseLong(String.valueOf(value)); 13 | assertEquals(13L, value); 14 | 15 | } 16 | 17 | } 18 | -------------------------------------------------------------------------------- /java-06-gson/build.gradle: -------------------------------------------------------------------------------- 1 | plugins { 2 | id 'java' 3 | } 4 | 5 | group = 'ai.incredible.gson' 6 | version = '1.0-SNAPSHOT' 7 | 8 | repositories { 9 | mavenCentral() 10 | } 11 | 12 | dependencies { 13 | implementation group: 'com.google.code.gson', name: 'gson', version: '2.7' 14 | 15 | 16 | testImplementation platform('org.junit:junit-bom:5.10.0') 17 | testImplementation 'org.junit.jupiter:junit-jupiter' 18 | } 19 | 20 | test { 21 | useJUnitPlatform() 22 | } -------------------------------------------------------------------------------- /java-01-unittest/build.gradle: -------------------------------------------------------------------------------- 1 | plugins { 2 | id 'java' 3 | } 4 | 5 | 6 | group 'ai.incredible.unittest' 7 | version '1.0-SNAPSHOT' 8 | 9 | repositories { 10 | mavenCentral() 11 | } 12 | 13 | dependencies { 14 | testImplementation 'org.junit.jupiter:junit-jupiter-api:5.8.1' 15 | testRuntimeOnly 'org.junit.jupiter:junit-jupiter-engine:5.8.1' 16 | } 17 | 18 | test { 19 | // Enable JUnit 5 (Gradle 4.6+). 이것만 넣으면 실제로 Junit이 실행된다 20 | useJUnitPlatform() 21 | 22 | // Always run tests, even when nothing changed. 23 | dependsOn 'cleanTest' 24 | } -------------------------------------------------------------------------------- /code-01-simple/src/main/java/ai/incredible/code/_01TwoSum.java: -------------------------------------------------------------------------------- 1 | package ai.incredible.code; 2 | 3 | import java.util.HashMap; 4 | import java.util.Map; 5 | 6 | public class _01TwoSum { 7 | 8 | public int[] twoSum(int[] nums, int target) { 9 | Map map = new HashMap<>(); 10 | for (int i = 0; i < nums.length; i++) { 11 | int complement = target - nums[i]; 12 | if(map.containsKey(complement)){ 13 | return new int[] {map.get(complement), i}; 14 | } 15 | map.put(nums[i], i); 16 | } 17 | return null; 18 | } 19 | } -------------------------------------------------------------------------------- /java-04-spark/build.gradle: -------------------------------------------------------------------------------- 1 | plugins { 2 | id 'java' 3 | } 4 | 5 | group 'ai.incredible.spark' 6 | version '1.0-SNAPSHOT' 7 | 8 | repositories { 9 | mavenCentral() 10 | } 11 | 12 | dependencies { 13 | implementation group: 'org.apache.spark', name: 'spark-sql_2.13', version: '3.3.1' 14 | implementation group: 'com.fasterxml.jackson.core', name: 'jackson-databind', version: '2.14.1' 15 | 16 | 17 | testImplementation 'org.junit.jupiter:junit-jupiter-api:5.8.1' 18 | testRuntimeOnly 'org.junit.jupiter:junit-jupiter-engine:5.8.1' 19 | } 20 | 21 | test { 22 | useJUnit() 23 | useJUnitPlatform() 24 | } -------------------------------------------------------------------------------- /java-03-solr/src/main/resources/data.json: -------------------------------------------------------------------------------- 1 | [ 2 | { 3 | "name": "Anderson", 4 | "userId": 1, 5 | "tags": [ 6 | "Machine Learning", 7 | "Statistics", 8 | "Mathematics" 9 | ] 10 | }, 11 | { 12 | "name": "Power", 13 | "userId": 2, 14 | "tags": [ 15 | "Statistics" 16 | ] 17 | }, 18 | { 19 | "name": "Batman", 20 | "userId": 3, 21 | "tags": [ 22 | "Machine Learning", 23 | "Mathematics" 24 | ] 25 | }, 26 | { 27 | "name": "Tesla", 28 | "userId": 4, 29 | "tags": [ 30 | "Car", 31 | "Machine Learning" 32 | ] 33 | } 34 | ] -------------------------------------------------------------------------------- /java-02-grpc/src/main/proto/andersonServer.proto: -------------------------------------------------------------------------------- 1 | syntax = "proto3"; 2 | 3 | option java_multiple_files = true; 4 | option java_package = "ai.incredible.grpc"; 5 | option java_outer_classname = "AndersonServerProto"; 6 | option objc_class_prefix = "HLW"; 7 | 8 | package example; 9 | 10 | service Greeter { 11 | rpc SayHello (HelloRequest) returns (HelloReply) {} 12 | rpc SayHelloAgain (HelloRequest) returns (HelloReply) {} 13 | } 14 | 15 | // The request message containing the user's name. 16 | message HelloRequest { 17 | string name = 1; 18 | } 19 | 20 | // The response message containing the greetings 21 | message HelloReply { 22 | string message = 1; 23 | } -------------------------------------------------------------------------------- /java-03-solr/build.gradle: -------------------------------------------------------------------------------- 1 | plugins { 2 | id 'java' 3 | } 4 | 5 | group 'ai.incredible.solr' 6 | version '1.0-SNAPSHOT' 7 | 8 | repositories { 9 | mavenCentral() 10 | } 11 | 12 | dependencies { 13 | 14 | implementation group: 'org.projectlombok', name: 'lombok', version: '1.18.24' 15 | annotationProcessor group: 'org.projectlombok', name: 'lombok', version: '1.18.24' 16 | implementation group: 'com.google.code.gson', name: 'gson', version: '2.9.1' 17 | implementation group: 'org.apache.solr', name: 'solr-solrj', version: '8.11.2' 18 | testImplementation group: 'org.slf4j', name: 'slf4j-simple', version: '2.0.3' 19 | 20 | 21 | testImplementation 'org.junit.jupiter:junit-jupiter-api:5.9.0' 22 | testRuntimeOnly 'org.junit.jupiter:junit-jupiter-engine:5.9.0' 23 | } 24 | 25 | 26 | test { 27 | useJUnitPlatform() 28 | } -------------------------------------------------------------------------------- /java-12-cassandra/build.gradle: -------------------------------------------------------------------------------- 1 | plugins { 2 | id 'java' 3 | id 'scala' 4 | } 5 | 6 | group = 'ai.incredible.cassandra' 7 | version = '1.0-SNAPSHOT' 8 | 9 | repositories { 10 | mavenCentral() 11 | } 12 | 13 | dependencies { 14 | implementation "com.github.jnr:jnr-posix:3.1.15" 15 | implementation 'joda-time:joda-time:2.12.7' 16 | 17 | implementation group: 'org.projectlombok', name: 'lombok', version: '1.18.34' 18 | implementation 'org.apache.spark:spark-core_2.12:3.4.1' 19 | implementation 'org.apache.spark:spark-sql_2.12:3.4.1' 20 | implementation 'com.datastax.spark:spark-cassandra-connector_2.12:3.4.1' 21 | // implementation 'com.datastax.oss:java-driver-core:4.17.0' 22 | 23 | testImplementation platform('org.junit:junit-bom:5.10.0') 24 | testImplementation 'org.junit.jupiter:junit-jupiter' 25 | } 26 | 27 | test { 28 | useJUnitPlatform() 29 | } -------------------------------------------------------------------------------- /java-10-lightgbm/build.gradle: -------------------------------------------------------------------------------- 1 | plugins { 2 | id 'java' 3 | } 4 | 5 | group = 'ai.incredible.lightgbm' 6 | version = '1.0-SNAPSHOT' 7 | 8 | repositories { 9 | mavenCentral() 10 | } 11 | 12 | dependencies { 13 | implementation 'io.github.metarank:lightgbm4j:4.3.0-1' 14 | implementation group: 'com.google.guava', name: 'guava', version: '11.0.2' 15 | implementation group: 'org.apache.parquet', name: 'parquet-arrow', version: '1.14.1' 16 | implementation group: 'org.apache.arrow', name: 'arrow-vector', version: '16.1.0' 17 | 18 | compileOnly 'org.projectlombok:lombok:1.18.34' 19 | annotationProcessor 'org.projectlombok:lombok:1.18.34' 20 | 21 | testCompileOnly 'org.projectlombok:lombok:1.18.34' 22 | testAnnotationProcessor 'org.projectlombok:lombok:1.18.34' 23 | testImplementation platform('org.junit:junit-bom:5.10.0') 24 | testImplementation 'org.junit.jupiter:junit-jupiter' 25 | } 26 | 27 | test { 28 | useJUnitPlatform() 29 | } -------------------------------------------------------------------------------- /java-11-caffeine/build.gradle: -------------------------------------------------------------------------------- 1 | plugins { 2 | id 'java' 3 | } 4 | 5 | group = 'ai.incredible.caffeine' 6 | version = '1.0-SNAPSHOT' 7 | 8 | repositories { 9 | mavenCentral() 10 | } 11 | 12 | dependencies { 13 | implementation("com.github.ben-manes.caffeine:caffeine:3.1.8") 14 | compileOnly 'org.projectlombok:lombok:1.18.34' 15 | annotationProcessor 'org.projectlombok:lombok:1.18.34' 16 | 17 | testCompileOnly 'org.projectlombok:lombok:1.18.34' 18 | testAnnotationProcessor 'org.projectlombok:lombok:1.18.34' 19 | testImplementation platform('org.junit:junit-bom:5.10.0') 20 | testImplementation 'org.junit.jupiter:junit-jupiter' 21 | testImplementation group: 'com.google.guava', name: 'guava-testlib', version: '33.2.1-jre' 22 | 23 | testImplementation "org.junit.jupiter:junit-jupiter-api:5.9.0" 24 | testImplementation "org.mockito:mockito-core:4.8.0" 25 | testRuntimeOnly "org.junit.jupiter:junit-jupiter-engine:5.9.0" 26 | } 27 | 28 | test { 29 | useJUnitPlatform() 30 | } -------------------------------------------------------------------------------- /code-01-simple/src/test/java/ai/incredible/code/_01TwoSumTest.java: -------------------------------------------------------------------------------- 1 | package ai.incredible.code; 2 | 3 | import static org.junit.jupiter.api.Assertions.assertArrayEquals; 4 | import static org.junit.jupiter.api.Assertions.assertNull; 5 | 6 | import ai.incredible.code._01TwoSum; 7 | import org.junit.jupiter.api.AfterEach; 8 | import org.junit.jupiter.api.BeforeEach; 9 | import org.junit.jupiter.api.Test; 10 | 11 | class _01TwoSumTest { 12 | 13 | _01TwoSum model; 14 | 15 | @BeforeEach 16 | void setUp() { 17 | model = new _01TwoSum(); 18 | } 19 | 20 | @AfterEach 21 | void tearDown() { 22 | model = null; 23 | } 24 | 25 | 26 | @Test 27 | void test01(){ 28 | int[] nums = {1, 2, 3, 4}; 29 | int[] ans = {0, 1}; 30 | assertArrayEquals(ans, model.twoSum(nums, 3)); 31 | } 32 | 33 | @Test 34 | void test02(){ 35 | int[] nums = {1, 2, 3, 4}; 36 | int[] ans = {0, 1}; 37 | assertNull(model.twoSum(nums, 1000)); 38 | } 39 | } -------------------------------------------------------------------------------- /java-05-protobuf/build.gradle: -------------------------------------------------------------------------------- 1 | buildscript { 2 | repositories { 3 | gradlePluginPortal() 4 | } 5 | dependencies { 6 | classpath 'com.google.protobuf:protobuf-gradle-plugin:0.9.1' 7 | } 8 | } 9 | 10 | apply plugin: 'java' 11 | apply plugin: "com.google.protobuf" 12 | apply plugin: 'idea' 13 | 14 | group 'ai.incredible.protobuf' 15 | version '1.0-SNAPSHOT' 16 | 17 | repositories { 18 | mavenCentral() 19 | } 20 | 21 | dependencies { 22 | // implementation 'com.google.protobuf:protobuf-gradle-plugin:0.9.1' 23 | implementation 'com.google.protobuf:protobuf-java:3.19.1' 24 | implementation 'com.google.protobuf:protobuf-java-util:3.19.1' 25 | 26 | testImplementation 'org.junit.jupiter:junit-jupiter-api:5.8.1' 27 | testRuntimeOnly 'org.junit.jupiter:junit-jupiter-engine:5.8.1' 28 | } 29 | 30 | protobuf { 31 | protoc { 32 | // Download from repositories 33 | artifact = 'com.google.protobuf:protoc:3.19.1' 34 | } 35 | } 36 | 37 | test { 38 | useJUnitPlatform() 39 | } -------------------------------------------------------------------------------- /java-03-solr/src/test/resources/geodata.json: -------------------------------------------------------------------------------- 1 | [ 2 | { 3 | "name": "Seoul Dogok Elementary School", 4 | "age": 14, 5 | "ab": "A", 6 | "lat": 37.499402, 7 | "lng": 127.054207 8 | }, 9 | { 10 | "name": "Nearby", 11 | "age": 20, 12 | "ab": "B", 13 | "lat": 37.498402, 14 | "lng": 127.054207 15 | }, 16 | { 17 | "name": "Posco", 18 | "age": 50, 19 | "ab": "A", 20 | "lat": 37.499402, 21 | "lng": 127.034207 22 | }, 23 | { 24 | "name": "KyungBu HighRoad", 25 | "age": 32, 26 | "ab": "B", 27 | "lat": 37.469502, 28 | "lng": 127.034207 29 | }, 30 | { 31 | "name": "Yang Ju", 32 | "age": 44, 33 | "ab": "A", 34 | "lat": 37.799502, 35 | "lng": 127.104207 36 | }, 37 | { 38 | "name": "OhSan - LakePark", 39 | "age": 39, 40 | "ab": "B", 41 | "lat": 37.169502, 42 | "lng": 127.104207 43 | }, 44 | { 45 | "name": "OhSan - LakePark", 46 | "age": 30, 47 | "ab": "A", 48 | "lat": 37.169502, 49 | "lng": 127.104207 50 | } 51 | 52 | ] -------------------------------------------------------------------------------- /java-05-protobuf/src/test/java/ai/incredible/protobuf/MyProtobufTest.java: -------------------------------------------------------------------------------- 1 | package ai.incredible.protobuf; 2 | 3 | import com.google.protobuf.ProtocolStringList; 4 | import org.junit.jupiter.api.Assertions; 5 | import org.junit.jupiter.api.Test; 6 | 7 | import static org.junit.jupiter.api.Assertions.assertEquals; 8 | 9 | 10 | public class MyProtobufTest { 11 | 12 | 13 | public MyProtobufTest() { 14 | 15 | } 16 | 17 | @Test 18 | public void testMyProtobuf(){ 19 | // Basic Protobuf Test 20 | Person person = Person.newBuilder() 21 | .setName("Anderson") 22 | .setAge(19) 23 | .addTags("first") 24 | .addTags("second") 25 | .setTags(1, "chocolate") 26 | .build(); 27 | 28 | assertEquals(person.getName(), "Anderson"); 29 | assertEquals(person.getAge(), 19); 30 | System.out.println(person.getTagsList()); 31 | 32 | assertEquals(person.getTags(0), "first"); 33 | assertEquals(person.getTags(1), "chocolate"); 34 | 35 | 36 | } 37 | } -------------------------------------------------------------------------------- /java-10-lightgbm/src/main/java/ai/incredible/lightgbm/Main.java: -------------------------------------------------------------------------------- 1 | package ai.incredible.lightgbm; 2 | 3 | import com.google.common.base.Charsets; 4 | import com.google.common.io.Files; 5 | import com.microsoft.ml.lightgbm.PredictionType; 6 | import io.github.metarank.lightgbm4j.LGBMBooster; 7 | 8 | import java.io.File; 9 | import java.util.Arrays; 10 | 11 | public class Main { 12 | static private final String MODEL_PATH = "/home/anderson/Desktop/model.txt"; 13 | static private final String DATA_PARQUET_DIR = "/tmp/lightgbm4j/"; 14 | 15 | @lombok.SneakyThrows 16 | public static void main(String[] args) { 17 | File file = new File(MODEL_PATH); 18 | String modelContent; 19 | modelContent = Files.toString(file, Charsets.UTF_8); 20 | LGBMBooster model = LGBMBooster.loadModelFromString(modelContent); 21 | System.out.println(model); 22 | 23 | float[] input = 24 | new float[] { 0.700720f, 1.287160f, -2.085664f, -0.004941f, 0.249742f, -0.323739f, 25 | -1.946551f, 1.496363f }; 26 | 27 | double[] pred = model.predictForMat(input, 1, 8, true, 28 | PredictionType.C_API_PREDICT_NORMAL); 29 | System.out.println(Arrays.toString(pred)); 30 | } 31 | } -------------------------------------------------------------------------------- /java-06-gson/src/test/java/ai/incredible/gson/GsonTest.java: -------------------------------------------------------------------------------- 1 | package ai.incredible.gson; 2 | 3 | import com.google.gson.Gson; 4 | import org.junit.jupiter.api.Test; 5 | 6 | import java.io.InputStreamReader; 7 | import java.io.Reader; 8 | import java.util.Objects; 9 | 10 | import static org.junit.jupiter.api.Assertions.assertEquals; 11 | 12 | class GsonTest { 13 | Gson gson; 14 | 15 | public GsonTest() { 16 | gson = new Gson(); 17 | } 18 | 19 | InputStreamReader getAsStream(String filepath) { 20 | return new InputStreamReader(Objects.requireNonNull(getClass().getClassLoader().getResourceAsStream(filepath))); 21 | } 22 | 23 | @Test 24 | public void testCar(){ 25 | Reader reader = getAsStream("car.json"); 26 | Car car = gson.fromJson(reader, Car.class); 27 | System.out.println(car); 28 | 29 | assertEquals(car.brand, "Samsung"); 30 | assertEquals(car.power, 123); 31 | assertEquals(car.missing, false); // 기본적으로 false 이다 32 | assertEquals(car.missingTrue, true); // default=true 이면 true 로 나온다 33 | assertEquals(car.missingFalse, false); // default=false 이면 false 로 나온다 34 | } 35 | 36 | } -------------------------------------------------------------------------------- /java-02-grpc/src/test/java/ai/incredible/grpc/AndersonServerTest.java: -------------------------------------------------------------------------------- 1 | package ai.incredible.grpc; 2 | 3 | import static org.junit.Assert.assertEquals; 4 | 5 | import io.grpc.inprocess.InProcessChannelBuilder; 6 | import io.grpc.inprocess.InProcessServerBuilder; 7 | import io.grpc.testing.GrpcCleanupRule; 8 | import org.junit.Rule; 9 | import org.junit.Test; 10 | 11 | public class AndersonServerTest { 12 | 13 | /** 14 | * This rule manages automatic graceful shutdown for the registered servers and channels at the end of test. 15 | */ 16 | @Rule 17 | public final GrpcCleanupRule grpcCleanup = new GrpcCleanupRule(); 18 | 19 | @Test 20 | public void greeterImpl_replyMessage() throws Exception { 21 | // Generate a unique in-process server name. 22 | String serverName = InProcessServerBuilder.generateName(); 23 | 24 | // Create a server, add service, start, and register for automatic graceful shutdown. 25 | grpcCleanup.register(InProcessServerBuilder 26 | .forName(serverName) 27 | .directExecutor() 28 | .addService(new AndersonServer.GreeterImpl()) 29 | .build() 30 | .start()); 31 | 32 | GreeterGrpc.GreeterBlockingStub blockingStub = GreeterGrpc.newBlockingStub( 33 | // Create a client channel and register for automatic graceful shutdown. 34 | grpcCleanup.register(InProcessChannelBuilder.forName(serverName).directExecutor().build())); 35 | 36 | HelloReply reply = blockingStub.sayHello(HelloRequest.newBuilder().setName("잇지").build()); 37 | assertEquals("서버에서 보내요~ 안녕! 잇지", reply.getMessage()); 38 | } 39 | 40 | } -------------------------------------------------------------------------------- /java-11-caffeine/src/main/java/ai/incredible/caffeine/Main.java: -------------------------------------------------------------------------------- 1 | package ai.incredible.caffeine; 2 | 3 | import com.github.benmanes.caffeine.cache.AsyncCache; 4 | import com.github.benmanes.caffeine.cache.AsyncCacheLoader; 5 | import com.github.benmanes.caffeine.cache.Caffeine; 6 | import lombok.SneakyThrows; 7 | 8 | import java.util.concurrent.CompletableFuture; 9 | import java.util.concurrent.Executor; 10 | import java.util.concurrent.TimeUnit; 11 | 12 | public class Main { 13 | @SneakyThrows 14 | public static void main(String[] args) { 15 | AsyncCache cache = Caffeine.newBuilder() 16 | .maximumSize(5) 17 | .refreshAfterWrite(1, TimeUnit.MINUTES) 18 | .buildAsync(new CustomAsyncCacheLoader()); 19 | 20 | CompletableFuture futureValue = cache.getIfPresent("haha"); 21 | 22 | } 23 | 24 | public static class CustomAsyncCacheLoader implements AsyncCacheLoader { 25 | 26 | @Override 27 | public CompletableFuture asyncLoad(String key, Executor executor) 28 | throws Exception { 29 | System.out.println("asyncLoad: "+ key); 30 | return retrieveData(key); 31 | } 32 | 33 | @Override 34 | public CompletableFuture asyncReload(String key, Data oldValue, 35 | Executor executor) throws Exception { 36 | System.out.println("asyncReload: "+ key); 37 | return retrieveData(key); 38 | } 39 | 40 | public CompletableFuture retrieveData(String key) { 41 | 42 | return CompletableFuture.supplyAsync(() -> { 43 | try { 44 | Thread.sleep(3000); 45 | } catch (InterruptedException e) { 46 | throw new RuntimeException(e); 47 | } 48 | return Data.builder().money(100).name(key).build(); 49 | }); 50 | } 51 | 52 | } 53 | 54 | } -------------------------------------------------------------------------------- /java-02-grpc/build.gradle: -------------------------------------------------------------------------------- 1 | plugins { 2 | // Provide convenience executables for trying out the examples. 3 | id 'application' 4 | id 'com.google.protobuf' version '0.8.18' 5 | } 6 | 7 | group 'ai.incredible.grpc' 8 | version '1.0-SNAPSHOT' 9 | 10 | repositories { 11 | maven { url "https://maven-central.storage-download.googleapis.com/maven2/" } 12 | mavenCentral() 13 | } 14 | 15 | def grpcVersion = '1.49.2' 16 | def protobufVersion = '3.21.7' 17 | def protocVersion = protobufVersion 18 | 19 | dependencies { 20 | implementation "io.grpc:grpc-protobuf:${grpcVersion}" 21 | implementation "io.grpc:grpc-stub:${grpcVersion}" 22 | compileOnly "org.apache.tomcat:annotations-api:6.0.53" 23 | 24 | // examples/advanced need this for JsonFormat 25 | implementation "com.google.protobuf:protobuf-java-util:${protobufVersion}" 26 | 27 | runtimeOnly "io.grpc:grpc-netty-shaded:${grpcVersion}" 28 | 29 | testImplementation "io.grpc:grpc-testing:${grpcVersion}" 30 | testImplementation "org.junit.jupiter:junit-jupiter-api:5.9.0" 31 | testImplementation "org.mockito:mockito-core:4.8.0" 32 | testRuntimeOnly "org.junit.jupiter:junit-jupiter-engine:5.9.0" 33 | 34 | } 35 | 36 | protobuf { 37 | protoc { artifact = "com.google.protobuf:protoc:${protocVersion}" } 38 | plugins { grpc { artifact = "io.grpc:protoc-gen-grpc-java:${grpcVersion}" } } 39 | generateProtoTasks { 40 | all()*.plugins { grpc {} } 41 | } 42 | } 43 | 44 | // Inform IDEs like IntelliJ IDEA, Eclipse or NetBeans about the generated code. 45 | sourceSets { 46 | main { 47 | java { 48 | srcDirs 'build/generated/source/proto/main/grpc' 49 | srcDirs 'build/generated/source/proto/main/java' 50 | } 51 | } 52 | } 53 | 54 | 55 | test { 56 | useJUnitPlatform() 57 | } -------------------------------------------------------------------------------- /java-04-spark/src/test/java/ai/incredible/spark/SparkTest.java: -------------------------------------------------------------------------------- 1 | package ai.incredible.spark; 2 | 3 | import org.apache.spark.api.java.JavaPairRDD; 4 | import org.apache.spark.api.java.JavaRDD; 5 | import org.apache.spark.sql.Dataset; 6 | import org.apache.spark.sql.Row; 7 | import org.apache.spark.sql.SparkSession; 8 | import org.junit.jupiter.api.Test; 9 | import scala.Tuple2; 10 | 11 | import java.net.URL; 12 | import java.util.HashSet; 13 | import java.util.Map; 14 | import java.util.Set; 15 | 16 | import static org.junit.jupiter.api.Assertions.assertEquals; 17 | 18 | class SparkTest { 19 | SparkSession spark; 20 | 21 | public SparkTest() { 22 | spark = SparkSession.builder() 23 | .master("local[*]") 24 | .appName("Spark Test") 25 | .config("spark.ui.port", "4050") 26 | .getOrCreate(); 27 | } 28 | 29 | private URL getResource() { 30 | return getClass().getClassLoader().getResource("vgsales.csv"); 31 | } 32 | 33 | @Test 34 | public void testReadCSV() { 35 | String filePath = String.valueOf(getResource()); 36 | Dataset salesDf = spark.read() 37 | .option("header", "true") 38 | .csv(filePath); 39 | 40 | assertEquals(salesDf.count(), 16598); 41 | JavaRDD salesRdd = salesDf.javaRDD(); 42 | 43 | salesDf.show(3); 44 | salesDf.printSchema(); 45 | 46 | // Test Platform count / mapToPair 47 | JavaPairRDD platformCountPairMap = salesRdd.mapToPair( 48 | row -> new Tuple2<>(row.getAs("Platform"), 1)); 49 | Map platformCount = platformCountPairMap 50 | .reduceByKey((x, y) -> (int) x + (int) y).collectAsMap(); 51 | assertEquals(platformCount.size(), 31); 52 | assertEquals(platformCount.get("PSP"), 1213); 53 | } 54 | } -------------------------------------------------------------------------------- /java-01-unittest/src/test/java/ai/incredible/unittest/CalculatorTest.java: -------------------------------------------------------------------------------- 1 | package ai.incredible.unittest; 2 | 3 | import org.junit.jupiter.api.BeforeEach; 4 | import org.junit.jupiter.api.DisplayName; 5 | import org.junit.jupiter.api.RepeatedTest; 6 | import org.junit.jupiter.api.Test; 7 | 8 | import java.io.BufferedReader; 9 | import java.io.IOException; 10 | import java.io.InputStreamReader; 11 | import java.net.HttpURLConnection; 12 | import java.net.URL; 13 | 14 | import static java.time.Duration.ofSeconds; 15 | import static org.junit.jupiter.api.Assertions.*; 16 | 17 | class CalculatorTest { 18 | Calculator calculator; 19 | 20 | /** 21 | * 매번 테스트 함수가 실행될때마다 실행됨 22 | */ 23 | @BeforeEach 24 | void setUp() { // 25 | calculator = new Calculator(); 26 | } 27 | 28 | @Test 29 | @DisplayName("Simple Summation") 30 | void simpleSum() { 31 | assertEquals(20, calculator.sum(10, 10), "simple summation"); 32 | } 33 | 34 | @RepeatedTest(5) 35 | @DisplayName("Ensure correct handling of 0") 36 | void multipleSum() { 37 | assertEquals(0, calculator.sum(5, -5), "it should be 0"); 38 | } 39 | 40 | @Test 41 | @DisplayName("Grouped Assertions") 42 | void groupedAssertions() { 43 | assertAll("Everything should work well", 44 | () -> assertEquals(10, calculator.sum(5, 5)), 45 | () -> assertEquals(20, calculator.sum(0, 20)) 46 | ); 47 | } 48 | 49 | @Test 50 | @DisplayName("HTTP Connection Test") 51 | void timeoutNotExceeded() throws IOException { 52 | URL url = new URL("https://raw.githubusercontent.com/zauberware/personal-interests-json/master/data/interests.json"); 53 | HttpURLConnection connection = (HttpURLConnection) url.openConnection(); 54 | connection.setRequestMethod("GET"); 55 | connection.setRequestProperty("Content-Type", "text/html"); 56 | connection.setUseCaches(false); 57 | connection.setDoOutput(true); 58 | 59 | final StringBuilder stringBuilder = new StringBuilder(); 60 | assertTimeout(ofSeconds(1), 61 | () -> { 62 | BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(connection.getInputStream())); 63 | String line; 64 | while ((line = bufferedReader.readLine()) != null) { 65 | stringBuilder.append(line); 66 | stringBuilder.append('\r'); 67 | } 68 | bufferedReader.close(); 69 | }); 70 | String response = stringBuilder.toString(); 71 | assertEquals(200, connection.getResponseCode()); 72 | assertTrue(10 < response.length()); 73 | } 74 | } -------------------------------------------------------------------------------- /java-02-grpc/src/test/java/ai/incredible/grpc/AndersonClientTest.java: -------------------------------------------------------------------------------- 1 | package ai.incredible.grpc; 2 | 3 | import static org.junit.Assert.assertEquals; 4 | import static org.mockito.AdditionalAnswers.delegatesTo; 5 | import static org.mockito.Mockito.mock; 6 | import static org.mockito.Mockito.verify; 7 | 8 | import io.grpc.ManagedChannel; 9 | import io.grpc.inprocess.InProcessChannelBuilder; 10 | import io.grpc.inprocess.InProcessServerBuilder; 11 | import io.grpc.stub.StreamObserver; 12 | import io.grpc.testing.GrpcCleanupRule; 13 | import org.junit.Before; 14 | import org.junit.Rule; 15 | import org.junit.Test; 16 | import org.junit.runner.RunWith; 17 | import org.junit.runners.JUnit4; 18 | import org.mockito.ArgumentCaptor; 19 | import org.mockito.ArgumentMatchers; 20 | 21 | 22 | @RunWith(JUnit4.class) 23 | public class AndersonClientTest { 24 | 25 | /** 26 | * This rule manages automatic graceful shutdown for the registered servers and channels at the end of test. 27 | */ 28 | @Rule 29 | public final GrpcCleanupRule grpcCleanup = new GrpcCleanupRule(); 30 | private AndersonClient client; 31 | private final GreeterGrpc.GreeterImplBase serviceImpl = mock( 32 | GreeterGrpc.GreeterImplBase.class, 33 | delegatesTo(new AndersonServer.GreeterImpl())); 34 | 35 | @Before 36 | public void setUp() throws Exception { 37 | // Generate a unique in-process server name. 38 | String serverName = InProcessServerBuilder.generateName(); 39 | 40 | // Create a client channel and register for automatic graceful shutdown. 41 | ManagedChannel channel = grpcCleanup.register( 42 | InProcessChannelBuilder 43 | .forName(serverName) 44 | .directExecutor() 45 | .build()); 46 | 47 | // Create a HelloWorldClient using the in-process channel; 48 | client = new AndersonClient(channel); 49 | 50 | // Create a server, add service, start, and register for automatic graceful shutdown. 51 | grpcCleanup.register( 52 | InProcessServerBuilder 53 | .forName(serverName) 54 | .directExecutor() 55 | .addService(serviceImpl) 56 | .build() 57 | .start()); 58 | } 59 | 60 | @Test 61 | public void greet_messageDeliveredToServer() { 62 | ArgumentCaptor requestCaptor = ArgumentCaptor.forClass(HelloRequest.class); 63 | 64 | client.greet("테스터"); 65 | verify(serviceImpl).sayHello(requestCaptor.capture(), 66 | ArgumentMatchers.>any()); 67 | assertEquals("테스터", requestCaptor.getValue().getName()); 68 | } 69 | 70 | } -------------------------------------------------------------------------------- /java-02-grpc/src/main/java/ai/incredible/grpc/AndersonServer.java: -------------------------------------------------------------------------------- 1 | package ai.incredible.grpc; 2 | 3 | 4 | import io.grpc.Server; 5 | import io.grpc.ServerBuilder; 6 | import io.grpc.stub.StreamObserver; 7 | 8 | import java.io.IOException; 9 | import java.util.concurrent.TimeUnit; 10 | import java.util.logging.Logger; 11 | 12 | public class AndersonServer { 13 | private static final Logger logger = Logger.getLogger(AndersonServer.class.getName()); 14 | private Server server; 15 | 16 | private void start() throws IOException { 17 | /* The port on which the server should run */ 18 | int port = 50051; 19 | server = ServerBuilder.forPort(port).addService(new GreeterImpl()).build().start(); 20 | logger.info("Server started, listening on " + port); 21 | Runtime.getRuntime().addShutdownHook(new Thread() { 22 | @Override 23 | public void run() { 24 | // Use stderr here since the logger may have been reset by its JVM shutdown hook. 25 | System.err.println("*** shutting down gRPC server since JVM is shutting down"); 26 | try { 27 | AndersonServer.this.stop(); 28 | } catch (InterruptedException e) { 29 | e.printStackTrace(System.err); 30 | } 31 | System.err.println("*** server shut down"); 32 | } 33 | }); 34 | } 35 | 36 | private void stop() throws InterruptedException { 37 | if (server != null) { 38 | server.shutdown().awaitTermination(30, TimeUnit.SECONDS); 39 | } 40 | } 41 | 42 | /** 43 | * Await termination on the main thread since the grpc library uses daemon threads. 44 | */ 45 | private void blockUntilShutdown() throws InterruptedException { 46 | if (server != null) { 47 | server.awaitTermination(); 48 | } 49 | } 50 | 51 | public static void main(String[] args) throws IOException, InterruptedException { 52 | final AndersonServer server = new AndersonServer(); 53 | server.start(); 54 | server.blockUntilShutdown(); 55 | } 56 | 57 | static class GreeterImpl extends GreeterGrpc.GreeterImplBase { 58 | @Override 59 | public void sayHello(HelloRequest request, StreamObserver responseObserver) { 60 | HelloReply reply = HelloReply.newBuilder().setMessage("서버에서 보내요~ 안녕! " + request.getName()).build(); 61 | responseObserver.onNext(reply); 62 | responseObserver.onCompleted(); 63 | } 64 | 65 | @Override 66 | public void sayHelloAgain(HelloRequest request, StreamObserver responseObserver) { 67 | super.sayHelloAgain(request, responseObserver); 68 | } 69 | } 70 | 71 | } -------------------------------------------------------------------------------- /java-11-caffeine/src/test/java/ai/incredible/caffeine/MainTest.java: -------------------------------------------------------------------------------- 1 | package ai.incredible.caffeine; 2 | 3 | import com.github.benmanes.caffeine.cache.AsyncCache; 4 | import com.github.benmanes.caffeine.cache.AsyncCacheLoader; 5 | import com.github.benmanes.caffeine.cache.Caffeine; 6 | import com.github.benmanes.caffeine.cache.Ticker; 7 | import org.junit.jupiter.api.Assertions; 8 | import org.junit.jupiter.api.BeforeEach; 9 | import org.junit.jupiter.api.Test; 10 | 11 | import java.util.concurrent.CompletableFuture; 12 | import java.util.concurrent.ExecutionException; 13 | import java.util.concurrent.Executor; 14 | import java.util.concurrent.TimeUnit; 15 | 16 | public class MainTest { 17 | private AsyncCache cache; 18 | private FakeTicker fakeTicker; 19 | 20 | public static class FakeTicker implements Ticker { 21 | long nanoseconds = 0; 22 | 23 | @Override 24 | public long read() { 25 | return nanoseconds; 26 | } 27 | 28 | public void advance(long n, TimeUnit unit) { 29 | nanoseconds += unit.toNanos(n); 30 | } 31 | } 32 | 33 | @BeforeEach 34 | public void setup() { 35 | fakeTicker = new FakeTicker(); 36 | cache = Caffeine.newBuilder() 37 | // .expireAfterWrite(5, TimeUnit.SECONDS) 38 | .refreshAfterWrite(1, TimeUnit.SECONDS) 39 | .ticker(fakeTicker) 40 | .buildAsync(new AsyncCacheLoader() { 41 | 42 | @Override 43 | public CompletableFuture asyncLoad(String key, Executor executor) { 44 | return CompletableFuture.completedFuture(createData(key)); 45 | } 46 | 47 | @Override 48 | public CompletableFuture asyncReload(String key, Data oldValue, 49 | Executor executor) throws Exception { 50 | return CompletableFuture.completedFuture(createData(key)); 51 | } 52 | }); 53 | } 54 | 55 | protected Data createData(String key) { 56 | 57 | return Data.builder().name(key).money(1000).build(); 58 | } 59 | 60 | @Test 61 | public void testCacheExpiration() throws ExecutionException, InterruptedException { 62 | String key = "key1"; 63 | cache.put(key, CompletableFuture.supplyAsync(() -> createData("haha"))); 64 | CompletableFuture future = cache.getIfPresent(key); 65 | Assertions.assertEquals("haha", future.get().getName()); 66 | 67 | fakeTicker.advance(2, TimeUnit.SECONDS); 68 | future = 69 | cache.get(key, (k, executor) -> CompletableFuture.supplyAsync(() -> createData("CC"))); 70 | Assertions.assertEquals(key, future.get().getName()); 71 | 72 | key = "key2"; 73 | fakeTicker.advance(5, TimeUnit.SECONDS); 74 | CompletableFuture ifPresent = 75 | cache.get(key, (k, executor) -> CompletableFuture.supplyAsync(() -> createData("CC"))); 76 | Assertions.assertNull(ifPresent); 77 | cache.synchronous(); 78 | 79 | fakeTicker.advance(5, TimeUnit.SECONDS); 80 | ifPresent = cache.getIfPresent(key); 81 | Assertions.assertNull(ifPresent); 82 | } 83 | 84 | } -------------------------------------------------------------------------------- /java-02-grpc/src/main/java/ai/incredible/grpc/AndersonClient.java: -------------------------------------------------------------------------------- 1 | package ai.incredible.grpc; 2 | 3 | import io.grpc.Channel; 4 | import io.grpc.ManagedChannel; 5 | import io.grpc.ManagedChannelBuilder; 6 | import io.grpc.StatusRuntimeException; 7 | import java.util.concurrent.TimeUnit; 8 | 9 | public class AndersonClient { 10 | 11 | private final GreeterGrpc.GreeterBlockingStub blockingStub; 12 | 13 | public AndersonClient(Channel channel) { 14 | blockingStub = GreeterGrpc.newBlockingStub(channel); 15 | } 16 | 17 | public void greet(String name) { 18 | HelloRequest request = HelloRequest.newBuilder().setName(name).build(); 19 | HelloReply response; 20 | try { 21 | response = blockingStub.sayHello(request); 22 | } catch (StatusRuntimeException e) { 23 | // logger.log(Level.WARNING, "RPC failed: {0}", e.getStatus()); 24 | return; 25 | } 26 | // logger.info("Greeting: " + response.getMessage()); 27 | } 28 | 29 | public static void main(String[] args) throws Exception { 30 | String user = "world"; 31 | // Access a service running on the local machine on port 50051 32 | String target = "localhost:50051"; 33 | // Allow passing in the user and target strings as command line arguments 34 | if (args.length > 0) { 35 | if ("--help".equals(args[0])) { 36 | System.err.println("Usage: [name [target]]"); 37 | System.err.println(); 38 | System.err.println( 39 | " name The name you wish to be greeted by. Defaults to " + user); 40 | System.err.println(" target The server to connect to. Defaults to " + target); 41 | System.exit(1); 42 | } 43 | user = args[0]; 44 | } 45 | if (args.length > 1) { 46 | target = args[1]; 47 | } 48 | 49 | // Create a communication channel to the server, known as a Channel. Channels are thread-safe 50 | // and reusable. It is common to create channels at the beginning of your application and reuse 51 | // them until the application shuts down. 52 | ManagedChannel channel = ManagedChannelBuilder.forTarget(target) 53 | // Channels are secure by default (via SSL/TLS). For the example we disable TLS to avoid 54 | // needing certificates. 55 | .usePlaintext().build(); 56 | try { 57 | AndersonClient client = new AndersonClient(channel); 58 | client.greet(user); 59 | } finally { 60 | // ManagedChannels use resources like threads and TCP connections. To prevent leaking these 61 | // resources the channel should be shut down when it will no longer be used. If it may be used 62 | // again leave it running. 63 | channel.shutdownNow().awaitTermination(5, TimeUnit.SECONDS); 64 | } 65 | } 66 | } 67 | -------------------------------------------------------------------------------- /java-12-cassandra/src/test/java/ai/incredible/cassandra/SparkTest.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Cassandra/bin 들어가서 3 | * ./cassandra -f 4 | * 위의 명령어로 카산드라 서버 켜야 함 5 | */ 6 | package ai.incredible.cassandra; 7 | 8 | import com.datastax.oss.driver.api.core.CqlSession; 9 | import com.datastax.oss.driver.api.core.cql.ResultSet; 10 | import com.datastax.oss.driver.api.core.cql.SimpleStatement; 11 | import com.datastax.oss.driver.internal.core.metadata.DefaultEndPoint; 12 | import com.datastax.spark.connector.japi.CassandraRow; 13 | import com.datastax.spark.connector.japi.rdd.CassandraTableScanJavaRDD; 14 | import org.apache.spark.SparkConf; 15 | import org.apache.spark.api.java.JavaRDD; 16 | import org.apache.spark.sql.*; 17 | import org.apache.spark.sql.types.DataTypes; 18 | import org.apache.spark.sql.types.StructField; 19 | import org.apache.spark.sql.types.StructType; 20 | import org.junit.jupiter.api.BeforeEach; 21 | import org.junit.jupiter.api.Test; 22 | 23 | import java.net.InetSocketAddress; 24 | import java.sql.Timestamp; 25 | import java.util.*; 26 | 27 | import static com.datastax.spark.connector.japi.CassandraJavaUtil.column; 28 | import static com.datastax.spark.connector.japi.CassandraJavaUtil.javaFunctions; 29 | import static com.datastax.spark.connector.japi.CassandraJavaUtil.mapRowTo; 30 | import static com.datastax.spark.connector.japi.CassandraJavaUtil.writeTime; 31 | import static org.junit.jupiter.api.Assertions.assertEquals; 32 | import static org.junit.jupiter.api.Assertions.assertTrue; 33 | 34 | public class SparkTest { 35 | protected SparkSession spark; 36 | 37 | @BeforeEach 38 | public void setup() { 39 | SparkConf conf = new SparkConf() 40 | .setAppName("Local Spark Example") 41 | .setMaster("local[2]") 42 | // .set("spark.cassandra.auth.username", "user_id") 43 | // .set("spark.cassandra.auth.password", "password") 44 | // .set("spark.cassandra.input.throughputMBPerSec", "1") 45 | .set("spark.cassandra.connection.host", "127.0.0.1"); 46 | 47 | spark = SparkSession.builder() 48 | .config(conf) 49 | .getOrCreate(); 50 | 51 | addTestData(); 52 | } 53 | 54 | protected void addTestData() { 55 | try (CqlSession session = CqlSession.builder() 56 | .addContactEndPoint( 57 | new DefaultEndPoint(new InetSocketAddress("localhost", 9042))) 58 | .withLocalDatacenter("datacenter1") 59 | // .withAuthCredentials("your_username", "your_password") // 사용자 인증 정보 추가 60 | .build()) { 61 | String createKeySpace = "CREATE KEYSPACE IF NOT EXISTS my_keyspace " 62 | + "WITH replication = {'class': 'SimpleStrategy', 'replication_factor': 1};"; 63 | 64 | String createTable = 65 | "CREATE TABLE IF NOT EXISTS my_keyspace.users (" 66 | + "uid UUID PRIMARY KEY, " 67 | + "name text, " 68 | + "age int, " 69 | + "married boolean," 70 | + "created_at timestamp);"; 71 | 72 | System.out.println(createTable); 73 | session.execute(createKeySpace); 74 | session.execute(createTable); 75 | } 76 | 77 | // 데이터 생성 78 | StructType schema = DataTypes.createStructType(new StructField[] { 79 | DataTypes.createStructField("uid", DataTypes.StringType, false), 80 | DataTypes.createStructField("name", DataTypes.StringType, false), 81 | DataTypes.createStructField("age", DataTypes.IntegerType, false), 82 | DataTypes.createStructField("married", DataTypes.BooleanType, false), 83 | DataTypes.createStructField("created_at", DataTypes.TimestampType, false) 84 | }); 85 | 86 | Timestamp timestamp = new Timestamp(new Date().getTime()); 87 | Dataset userData = spark.createDataFrame(Arrays.asList( 88 | RowFactory.create(UUID.randomUUID().toString(), "Anderson", 40, true, timestamp), 89 | RowFactory.create(UUID.randomUUID().toString(), "Alice", 25, false, timestamp), 90 | RowFactory.create(UUID.randomUUID().toString(), "Yoona", 21, false, timestamp) 91 | ), schema); 92 | 93 | userData.write() 94 | .format("org.apache.spark.sql.cassandra") 95 | .mode(SaveMode.Append) 96 | .option("keyspace", "my_keyspace") 97 | .option("table", "users") 98 | .save(); 99 | } 100 | 101 | @Test 102 | public void readAllTable() { 103 | // 방법 1 104 | // Spark 에서 전체 데이터를 다 가져오기. 105 | Dataset df = spark.read() 106 | .format("org.apache.spark.sql.cassandra") 107 | .option("keyspace", "my_keyspace") 108 | .option("table", "users") 109 | .load(); 110 | 111 | assertTrue(df.count() >= 3); 112 | Row andersonRow = df.filter("name = 'Anderson'").first(); 113 | assertEquals(40, (int) andersonRow.getAs("age")); 114 | assertEquals(true, andersonRow.getAs("married")); 115 | df.show(); 116 | } 117 | 118 | @Test 119 | public void readThroughCassandraConnector1() { 120 | CassandraTableScanJavaRDD rdd = 121 | javaFunctions(spark.sparkContext()) 122 | .cassandraTable("my_keyspace", "users") 123 | .select(column("uid"), 124 | column("name"), 125 | column("age"), 126 | column("married"), 127 | column("created_at").as("createdAt"), 128 | writeTime("name").as("writetime")); 129 | JavaRDD javaRdd = rdd.map(row -> { 130 | return RowFactory.create( 131 | row.getString("uid"), 132 | row.getString("name"), 133 | row.getInt("age"), 134 | row.getBoolean("married"), 135 | new Timestamp(row.getLong("createdAt")), 136 | row.getLong("writetime")); 137 | }); 138 | 139 | StructType schema = DataTypes.createStructType(new StructField[] { 140 | DataTypes.createStructField("uid", DataTypes.StringType, false), 141 | DataTypes.createStructField("name", DataTypes.StringType, false), 142 | DataTypes.createStructField("age", DataTypes.IntegerType, false), 143 | DataTypes.createStructField("married", DataTypes.BooleanType, false), 144 | DataTypes.createStructField("createdAt", DataTypes.TimestampType, false), 145 | DataTypes.createStructField("writetime", DataTypes.LongType, false) 146 | }); 147 | 148 | Dataset dataset = spark.createDataFrame(javaRdd, schema); 149 | dataset.show(); 150 | System.out.println(dataset); 151 | 152 | } 153 | 154 | @Test 155 | public void readThroughCassandraConnector2() { 156 | // 방법 2 157 | // Spark Cassandra Connector를 사용해서, 좀더 자세한 정보를 가져오는 방법 158 | // 회사에서는 됐는데, 지금 여기서는 안됨. select 에서 empty 가 나옴. 159 | CassandraTableScanJavaRDD rdd = javaFunctions(spark.sparkContext()) 160 | .cassandraTable("my_keyspace", "users", mapRowTo(DataBean.class)) 161 | .select(column("uid"), 162 | column("name"), 163 | column("age"), 164 | column("married"), 165 | column("created_at").as("createdAt"), 166 | writeTime("name").as("writetime")); 167 | JavaRDD javaRdd = rdd.map(row -> { 168 | return RowFactory.create( 169 | // row.getUid(), 170 | // row.getName(), 171 | // row.getAge(), 172 | // row.getMarried(), 173 | // row.getCreatedAt(), 174 | // row.getWritetime() 175 | ); 176 | }); 177 | // 178 | Dataset dataset = spark.createDataFrame(javaRdd, DataBean.class); 179 | dataset.show(); 180 | } 181 | 182 | @Test 183 | public void cqlSessionTest() { 184 | // 방법 4 185 | // CQL 로 direct 접속을 해서 데이터를 가져옵니다. 186 | // 해당 방법은 spark.read() 를 사용하는 것이 아니며, 이를 spark 에서 사용시에 187 | // driver 에서 바로 가져오는 것이기 때문에 distributed loading 이 되는 것이 아닙니다. 188 | // Spark 에서 쓰는 것 보다는 따로 CQL 로 접속해야 할때 사용하면 좋은 방법입니다. 189 | try (CqlSession session = CqlSession.builder() 190 | .addContactEndPoint( 191 | new DefaultEndPoint(new InetSocketAddress("localhost", 9042))) 192 | .withLocalDatacenter("datacenter1") 193 | // .withAuthCredentials("your_username", "your_password") // 사용자 인증 정보 추가 194 | .build()) { 195 | 196 | // 중요한점! ALLOW FILTERING 에 끝에 들어갔음. 197 | // Cassandra 에서는 WHERE statement 가 연산량이 많은듯 함. 198 | // 그래서 WHERE 사용시 반드시 뒤에 ALLOW FILTERING 써줘야 함 199 | // 또한 setPageSize 를 통해서 한번에 얼마나 가져올지를 정함 200 | String query = "SELECT name, age, WRITETIME(name) as created_at " 201 | + "FROM my_keyspace.users WHERE name='Anderson' ALLOW FILTERING;"; 202 | ResultSet resultSet = session.execute(SimpleStatement.builder(query) 203 | .setPageSize(5).build()); 204 | 205 | List rows = new ArrayList<>(); 206 | do { 207 | for (com.datastax.oss.driver.api.core.cql.Row cassandraRow : resultSet) { 208 | rows.add(RowFactory.create( 209 | cassandraRow.getString("name"), 210 | cassandraRow.getInt("age"), 211 | new Timestamp(cassandraRow.getLong("created_at") / 1000) 212 | )); 213 | } 214 | 215 | } while (!resultSet.isFullyFetched()); 216 | 217 | StructType schema2 = DataTypes.createStructType(new StructField[] { 218 | DataTypes.createStructField("name", DataTypes.StringType, false), 219 | DataTypes.createStructField("age", DataTypes.IntegerType, false), 220 | DataTypes.createStructField("created_at", DataTypes.TimestampType, false) 221 | }); 222 | 223 | Dataset df2 = spark.createDataFrame(rows, schema2); 224 | df2.show(); 225 | } 226 | } 227 | } 228 | -------------------------------------------------------------------------------- /gradlew: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | 3 | # 4 | # Copyright © 2015-2021 the original authors. 5 | # 6 | # Licensed under the Apache License, Version 2.0 (the "License"); 7 | # you may not use this file except in compliance with the License. 8 | # You may obtain a copy of the License at 9 | # 10 | # https://www.apache.org/licenses/LICENSE-2.0 11 | # 12 | # Unless required by applicable law or agreed to in writing, software 13 | # distributed under the License is distributed on an "AS IS" BASIS, 14 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 15 | # See the License for the specific language governing permissions and 16 | # limitations under the License. 17 | # 18 | 19 | ############################################################################## 20 | # 21 | # Gradle start up script for POSIX generated by Gradle. 22 | # 23 | # Important for running: 24 | # 25 | # (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is 26 | # noncompliant, but you have some other compliant shell such as ksh or 27 | # bash, then to run this script, type that shell name before the whole 28 | # command line, like: 29 | # 30 | # ksh Gradle 31 | # 32 | # Busybox and similar reduced shells will NOT work, because this script 33 | # requires all of these POSIX shell features: 34 | # * functions; 35 | # * expansions «$var», «${var}», «${var:-default}», «${var+SET}», 36 | # «${var#prefix}», «${var%suffix}», and «$( cmd )»; 37 | # * compound commands having a testable exit status, especially «case»; 38 | # * various built-in commands including «command», «set», and «ulimit». 39 | # 40 | # Important for patching: 41 | # 42 | # (2) This script targets any POSIX shell, so it avoids extensions provided 43 | # by Bash, Ksh, etc; in particular arrays are avoided. 44 | # 45 | # The "traditional" practice of packing multiple parameters into a 46 | # space-separated string is a well documented source of bugs and security 47 | # problems, so this is (mostly) avoided, by progressively accumulating 48 | # options in "$@", and eventually passing that to Java. 49 | # 50 | # Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS, 51 | # and GRADLE_OPTS) rely on word-splitting, this is performed explicitly; 52 | # see the in-line comments for details. 53 | # 54 | # There are tweaks for specific operating systems such as AIX, CygWin, 55 | # Darwin, MinGW, and NonStop. 56 | # 57 | # (3) This script is generated from the Groovy template 58 | # https://github.com/gradle/gradle/blob/master/subprojects/plugins/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt 59 | # within the Gradle project. 60 | # 61 | # You can find Gradle at https://github.com/gradle/gradle/. 62 | # 63 | ############################################################################## 64 | 65 | # Attempt to set APP_HOME 66 | 67 | # Resolve links: $0 may be a link 68 | app_path=$0 69 | 70 | # Need this for daisy-chained symlinks. 71 | while 72 | APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path 73 | [ -h "$app_path" ] 74 | do 75 | ls=$( ls -ld "$app_path" ) 76 | link=${ls#*' -> '} 77 | case $link in #( 78 | /*) app_path=$link ;; #( 79 | *) app_path=$APP_HOME$link ;; 80 | esac 81 | done 82 | 83 | APP_HOME=$( cd "${APP_HOME:-./}" && pwd -P ) || exit 84 | 85 | APP_NAME="Gradle" 86 | APP_BASE_NAME=${0##*/} 87 | 88 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 89 | DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' 90 | 91 | # Use the maximum available, or set MAX_FD != -1 to use that value. 92 | MAX_FD=maximum 93 | 94 | warn () { 95 | echo "$*" 96 | } >&2 97 | 98 | die () { 99 | echo 100 | echo "$*" 101 | echo 102 | exit 1 103 | } >&2 104 | 105 | # OS specific support (must be 'true' or 'false'). 106 | cygwin=false 107 | msys=false 108 | darwin=false 109 | nonstop=false 110 | case "$( uname )" in #( 111 | CYGWIN* ) cygwin=true ;; #( 112 | Darwin* ) darwin=true ;; #( 113 | MSYS* | MINGW* ) msys=true ;; #( 114 | NONSTOP* ) nonstop=true ;; 115 | esac 116 | 117 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar 118 | 119 | 120 | # Determine the Java command to use to start the JVM. 121 | if [ -n "$JAVA_HOME" ] ; then 122 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then 123 | # IBM's JDK on AIX uses strange locations for the executables 124 | JAVACMD=$JAVA_HOME/jre/sh/java 125 | else 126 | JAVACMD=$JAVA_HOME/bin/java 127 | fi 128 | if [ ! -x "$JAVACMD" ] ; then 129 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME 130 | 131 | Please set the JAVA_HOME variable in your environment to match the 132 | location of your Java installation." 133 | fi 134 | else 135 | JAVACMD=java 136 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 137 | 138 | Please set the JAVA_HOME variable in your environment to match the 139 | location of your Java installation." 140 | fi 141 | 142 | # Increase the maximum file descriptors if we can. 143 | if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then 144 | case $MAX_FD in #( 145 | max*) 146 | MAX_FD=$( ulimit -H -n ) || 147 | warn "Could not query maximum file descriptor limit" 148 | esac 149 | case $MAX_FD in #( 150 | '' | soft) :;; #( 151 | *) 152 | ulimit -n "$MAX_FD" || 153 | warn "Could not set maximum file descriptor limit to $MAX_FD" 154 | esac 155 | fi 156 | 157 | # Collect all arguments for the java command, stacking in reverse order: 158 | # * args from the command line 159 | # * the main class name 160 | # * -classpath 161 | # * -D...appname settings 162 | # * --module-path (only if needed) 163 | # * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables. 164 | 165 | # For Cygwin or MSYS, switch paths to Windows format before running java 166 | if "$cygwin" || "$msys" ; then 167 | APP_HOME=$( cygpath --path --mixed "$APP_HOME" ) 168 | CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" ) 169 | 170 | JAVACMD=$( cygpath --unix "$JAVACMD" ) 171 | 172 | # Now convert the arguments - kludge to limit ourselves to /bin/sh 173 | for arg do 174 | if 175 | case $arg in #( 176 | -*) false ;; # don't mess with options #( 177 | /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath 178 | [ -e "$t" ] ;; #( 179 | *) false ;; 180 | esac 181 | then 182 | arg=$( cygpath --path --ignore --mixed "$arg" ) 183 | fi 184 | # Roll the args list around exactly as many times as the number of 185 | # args, so each arg winds up back in the position where it started, but 186 | # possibly modified. 187 | # 188 | # NB: a `for` loop captures its iteration list before it begins, so 189 | # changing the positional parameters here affects neither the number of 190 | # iterations, nor the values presented in `arg`. 191 | shift # remove old arg 192 | set -- "$@" "$arg" # push replacement arg 193 | done 194 | fi 195 | 196 | # Collect all arguments for the java command; 197 | # * $DEFAULT_JVM_OPTS, $JAVA_OPTS, and $GRADLE_OPTS can contain fragments of 198 | # shell script including quotes and variable substitutions, so put them in 199 | # double quotes to make sure that they get re-expanded; and 200 | # * put everything else in single quotes, so that it's not re-expanded. 201 | 202 | set -- \ 203 | "-Dorg.gradle.appname=$APP_BASE_NAME" \ 204 | -classpath "$CLASSPATH" \ 205 | org.gradle.wrapper.GradleWrapperMain \ 206 | "$@" 207 | 208 | # Use "xargs" to parse quoted args. 209 | # 210 | # With -n1 it outputs one arg per line, with the quotes and backslashes removed. 211 | # 212 | # In Bash we could simply go: 213 | # 214 | # readarray ARGS < <( xargs -n1 <<<"$var" ) && 215 | # set -- "${ARGS[@]}" "$@" 216 | # 217 | # but POSIX shell has neither arrays nor command substitution, so instead we 218 | # post-process each arg (as a line of input to sed) to backslash-escape any 219 | # character that might be a shell metacharacter, then use eval to reverse 220 | # that process (while maintaining the separation between arguments), and wrap 221 | # the whole thing up as a single "set" statement. 222 | # 223 | # This will of course break if any of these variables contains a newline or 224 | # an unmatched quote. 225 | # 226 | 227 | eval "set -- $( 228 | printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" | 229 | xargs -n1 | 230 | sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' | 231 | tr '\n' ' ' 232 | )" '"$@"' 233 | 234 | exec "$JAVACMD" "$@" 235 | -------------------------------------------------------------------------------- /java-03-solr/src/test/java/ai/incredible/solr/SolrTest.java: -------------------------------------------------------------------------------- 1 | package ai.incredible.solr; 2 | 3 | import static org.junit.jupiter.api.Assertions.assertEquals; 4 | 5 | import com.google.gson.Gson; 6 | 7 | import java.io.IOException; 8 | import java.io.InputStreamReader; 9 | import java.io.Reader; 10 | import java.util.ArrayList; 11 | import java.util.Arrays; 12 | import java.util.Objects; 13 | import java.util.stream.Collectors; 14 | 15 | import org.apache.solr.client.solrj.SolrQuery; 16 | import org.apache.solr.client.solrj.SolrServerException; 17 | import org.apache.solr.client.solrj.impl.HttpSolrClient; 18 | import org.apache.solr.client.solrj.impl.XMLResponseParser; 19 | import org.apache.solr.client.solrj.response.QueryResponse; 20 | import org.apache.solr.common.SolrDocument; 21 | import org.apache.solr.common.SolrDocumentList; 22 | import org.apache.solr.common.SolrInputDocument; 23 | import org.junit.jupiter.api.AfterEach; 24 | import org.junit.jupiter.api.BeforeEach; 25 | import org.junit.jupiter.api.Test; 26 | 27 | /** 28 | * 시작전에 다음을 실행. 29 | * ./bin/solr create -c users 30 | * ./bin/solr start 31 | *

32 | * 삭제는.. 33 | * rm -rf server/solr/users/ 34 | * 그리고 재시작 35 | */ 36 | class SolrTest { 37 | 38 | private static final String url = "http://localhost:8983/solr/users"; 39 | 40 | private final HttpSolrClient client; 41 | 42 | public SolrTest() throws SolrServerException, IOException { 43 | client = new HttpSolrClient.Builder(url).build(); 44 | client.setParser(new XMLResponseParser()); 45 | } 46 | 47 | @AfterEach 48 | void before() throws SolrServerException, IOException { 49 | client.deleteByQuery("*:*"); 50 | client.commit(); 51 | } 52 | 53 | User[] getUserData() { 54 | try (Reader reader = new InputStreamReader(Objects.requireNonNull(getClass() 55 | .getClassLoader() 56 | .getResourceAsStream("data.json")))) { 57 | 58 | User[] data = new Gson().fromJson(reader, User[].class); 59 | return data; 60 | } catch (IOException e) { 61 | e.printStackTrace(); 62 | throw new RuntimeException(e); 63 | } 64 | } 65 | 66 | Location[] getLocationData() { 67 | try (Reader reader = new InputStreamReader(Objects.requireNonNull(getClass() 68 | .getClassLoader() 69 | .getResourceAsStream("geodata.json")))) { 70 | 71 | Location[] data = new Gson().fromJson(reader, Location[].class); 72 | return data; 73 | } catch (IOException e) { 74 | e.printStackTrace(); 75 | throw new RuntimeException(e); 76 | } 77 | } 78 | 79 | void storeUserData() throws SolrServerException, IOException { 80 | User[] users = getUserData(); 81 | for (User user : users) { 82 | SolrInputDocument doc = new SolrInputDocument(); 83 | doc.setField("name", user.getName()); 84 | doc.setField("id", user.getUserId()); 85 | doc.setField("age", user.getAge()); 86 | doc.setField("tags", user.getTags()); 87 | client.add(doc); 88 | } 89 | client.commit(); 90 | } 91 | 92 | void storeLocationData() throws SolrServerException, IOException { 93 | Location[] locations = getLocationData(); 94 | for (Location location : locations) { 95 | SolrInputDocument doc = new SolrInputDocument(); 96 | doc.addField("name", location.getName()); 97 | doc.addField("age", location.getAge()); 98 | doc.addField("ab", location.getAb()); 99 | doc.addField("lat", location.getLat()); 100 | doc.addField("lng", location.getLng()); 101 | client.add(doc); 102 | } 103 | client.commit(); 104 | } 105 | 106 | 107 | @Test 108 | void testSimpleQuerying() throws SolrServerException, IOException { 109 | // Input a document 110 | ArrayList bookIds = new ArrayList(Arrays.asList(1L, 2L, 3L, 4L, 5L)); 111 | 112 | SolrInputDocument document = new SolrInputDocument(); 113 | document.addField("id", "123456"); 114 | document.addField("name", "Kenmore Dishwasher"); 115 | document.addField("price", "599.99"); 116 | document.addField("bookIds", bookIds); 117 | document.addField("cum", 10L); 118 | document.addField("cum", 20L); 119 | document.addField("cum", 30L); 120 | document.addField("cum", 40L); 121 | document.addField("cum", 50L); 122 | document.setField("status", "Good"); 123 | document.setField("status", "Bad"); 124 | document.setField("status", "AWESOME!"); 125 | client.add(document); 126 | client.commit(); 127 | 128 | // Get Response from Solr 129 | SolrQuery query = new SolrQuery(); 130 | query.set("q", "price:599.99"); 131 | QueryResponse response = client.query(query); 132 | 133 | // Validation 134 | SolrDocumentList docs = response.getResults(); 135 | assertEquals(1, docs.size()); 136 | for (SolrDocument doc : response.getResults()) { 137 | assertEquals("Kenmore Dishwasher", doc.getFieldValue("name")); 138 | assertEquals((Double) 599.99, (Double) doc.getFieldValue("price")); 139 | 140 | // 처리 방식이 다르다. Collection 으로 되어 있음 141 | ArrayList values = doc.getFieldValues("bookIds") 142 | .stream() 143 | .map(c -> (Long) c) 144 | .collect(Collectors.toCollection(ArrayList::new)); 145 | for (int i = 0; i < values.size(); i++) { 146 | assertEquals(i + 1, values.get(i)); 147 | } 148 | 149 | // Collection 으로 되어 있음. 150 | ArrayList values2 = doc.getFieldValues("cum") 151 | .stream() 152 | .map(c -> (Long) c) 153 | .collect(Collectors.toCollection(ArrayList::new)); 154 | for (int i = 0; i < values.size(); i++) { 155 | assertEquals((i + 1) * 10L, values2.get(i)); 156 | } 157 | 158 | // Test setField for duplicate array. 159 | assertEquals(1, doc.getFieldValues("status").size()); 160 | 161 | } 162 | 163 | // Get Book ID 164 | query = new SolrQuery(); 165 | query.set("q", "bookIds:3"); 166 | response = client.query(query); 167 | assertEquals(1, response.getResults().size()); 168 | assertEquals(599.99, response.getResults().get(0).getFieldValue("price")); 169 | 170 | // Get not-existing book ID 171 | query = new SolrQuery(); 172 | query.set("q", "bookIds:100"); 173 | response = client.query(query); 174 | assertEquals(0, response.getResults().size()); 175 | 176 | // Get cum 177 | query = new SolrQuery(); 178 | query.set("q", "cum:(20 100)"); 179 | response = client.query(query); 180 | assertEquals(1, response.getResults().size()); 181 | assertEquals(599.99, response.getResults().get(0).getFieldValue("price")); 182 | 183 | // Get non-existing cum 184 | query = new SolrQuery(); 185 | query.set("q", "cum:(500 100)"); 186 | response = client.query(query); 187 | assertEquals(0, response.getResults().size()); 188 | 189 | } 190 | 191 | @Test 192 | void testGSonSolrQuerying() throws SolrServerException, IOException { 193 | storeUserData(); 194 | 195 | // Get Response from Solr 196 | SolrQuery query = new SolrQuery(); 197 | query.set("q", "tags:Statistics"); 198 | QueryResponse response = client.query(query); 199 | 200 | // Validation 201 | SolrDocumentList docs = response.getResults(); 202 | assertEquals(2, docs.size()); 203 | } 204 | 205 | @Test 206 | void testAddFieldVSSetField() throws SolrServerException, IOException { 207 | SolrInputDocument document = new SolrInputDocument(); 208 | document.setField("id", "987654321"); 209 | document.setField("status1", "Good"); 210 | document.setField("status1", "Bad"); 211 | document.setField("status1", "AWESOME!"); 212 | document.addField("status2", "Good"); 213 | document.addField("status2", "Bad"); 214 | document.addField("status2", "AWESOME!"); 215 | client.add(document); 216 | client.commit(); 217 | 218 | SolrQuery query = new SolrQuery(); 219 | query.set("q", "id:987654321"); 220 | QueryResponse response = client.query(query); 221 | SolrDocument responseDocument = response.getResults().get(0); 222 | 223 | ArrayList status1 = responseDocument.getFieldValues("status1") 224 | .stream().map(v -> (String) v) 225 | .collect(Collectors.toCollection(ArrayList::new)); 226 | 227 | ArrayList status2 = responseDocument.getFieldValues("status2") 228 | .stream().map(v -> (String) v) 229 | .collect(Collectors.toCollection(ArrayList::new)); 230 | 231 | assertEquals(1, status1.size()); 232 | assertEquals(3, status2.size()); 233 | } 234 | 235 | @Test 236 | void testQueryField() throws SolrServerException, IOException { 237 | storeLocationData(); 238 | SolrQuery query = new SolrQuery(); 239 | query.set("q", ""); 240 | // query.set("qf", "ab^10"); 241 | QueryResponse response = client.query(query); 242 | 243 | for (SolrDocument doc : response.getResults()) { 244 | System.out.println(String.format("%s | %s | %s", 245 | doc.getFieldValue("name"), 246 | doc.getFieldValue("age"), 247 | doc.getFieldValue("ab")) 248 | ); 249 | } 250 | 251 | 252 | } 253 | 254 | // @Test 255 | void testGeoFilter() throws SolrServerException, IOException { 256 | storeLocationData(); 257 | SolrQuery query = new SolrQuery(); 258 | query.set("q", "{!geofilt d=10}&pt=37.499402,127.054207"); 259 | QueryResponse response = client.query(query); 260 | 261 | for (SolrDocument doc : response.getResults()) { 262 | System.out.println(doc.getFieldValue("name")); 263 | } 264 | } 265 | 266 | } 267 | --------------------------------------------------------------------------------