├── .idea ├── codeStyleSettings.xml ├── compiler.xml ├── encodings.xml ├── libraries │ ├── Maven__ch_qos_logback_logback_classic_1_1_2.xml │ ├── Maven__ch_qos_logback_logback_core_1_1_2.xml │ ├── Maven__com_google_code_findbugs_jsr305_1_3_9.xml │ ├── Maven__com_google_errorprone_error_prone_annotations_2_0_18.xml │ ├── Maven__com_google_guava_guava_23_0.xml │ ├── Maven__com_google_j2objc_j2objc_annotations_1_1.xml │ ├── Maven__junit_junit_4_8_1.xml │ ├── Maven__org_codehaus_mojo_animal_sniffer_annotations_1_14.xml │ └── Maven__org_slf4j_slf4j_api_1_7_12.xml ├── misc.xml ├── modules.xml ├── uiDesigner.xml └── vcs.xml ├── Jenkinsfile ├── README.md ├── guava_programming.iml ├── my_servant ├── pom.xml └── src │ └── main │ └── java │ └── com │ └── wangwenjun │ └── servant │ └── ServiceInvoker.java ├── my_service ├── my_service.iml ├── pom.xml └── src │ └── main │ ├── java │ └── com │ │ └── wangwenjun │ │ └── service │ │ ├── Service.java │ │ └── SimpleService.java │ └── resources │ └── META-INF │ └── services │ └── com.wangwenjun.service.Service ├── pom.xml └── src ├── main ├── java │ └── com │ │ └── wangwenjun │ │ └── guava │ │ ├── cache │ │ ├── Employee.java │ │ ├── LRUCache.java │ │ ├── LRUCacheExample.java │ │ ├── LinkedHashLRUCache.java │ │ ├── LinkedHashLRUCacheExample.java │ │ ├── LinkedListLRUCache.java │ │ ├── LinkedListLRUCacheExample.java │ │ ├── ReferenceExample.java │ │ └── SoftLRUCache.java │ │ ├── collections │ │ ├── BiMapExample.java │ │ ├── FluentIterableExample.java │ │ ├── ImmutableCollections.java │ │ ├── ListsExample.java │ │ ├── MapsExample.java │ │ ├── MultimapsExample.java │ │ ├── OrderingExample.java │ │ ├── RangeExample.java │ │ ├── SetsExample.java │ │ └── TableExample.java │ │ ├── concurrent │ │ ├── Bucket.java │ │ ├── BucketTest.java │ │ ├── ListenableFutureExample.java │ │ ├── MonitorExample.java │ │ ├── RateLimiterExample.java │ │ ├── TokenBucket.java │ │ └── TokenBucketExample.java │ │ ├── eventbus │ │ ├── AsyncEventBusExample.java │ │ ├── ComEachOtherEventBusExample.java │ │ ├── DeadEventBusExample.java │ │ ├── ExceptionEventBusExample.java │ │ ├── InheritEventsEventBusExample.java │ │ ├── InheritListenersEventBusExample.java │ │ ├── MultipleEventBusExample.java │ │ ├── SimpleEventBusExample.java │ │ ├── events │ │ │ ├── Apple.java │ │ │ ├── Fruit.java │ │ │ ├── Request.java │ │ │ └── Response.java │ │ ├── internal │ │ │ ├── Bus.java │ │ │ ├── MyAsyncEventBus.java │ │ │ ├── MyDispatcher.java │ │ │ ├── MyEventBus.java │ │ │ ├── MyEventContext.java │ │ │ ├── MyEventExceptionHandler.java │ │ │ ├── MyRegistry.java │ │ │ ├── MySubscribe.java │ │ │ └── MySubscriber.java │ │ ├── listeners │ │ │ ├── AbstractListener.java │ │ │ ├── BaseListener.java │ │ │ ├── ConcreteListener.java │ │ │ ├── DeadEventListener.java │ │ │ ├── ExceptionListener.java │ │ │ ├── FruitEaterListener.java │ │ │ ├── MultipleEventListeners.java │ │ │ └── SimpleListener.java │ │ ├── monitor │ │ │ ├── DirectoryTargetMonitor.java │ │ │ ├── FileChangeEvent.java │ │ │ ├── FileChangeListener.java │ │ │ ├── MonitorClient.java │ │ │ └── TargetMonitor.java │ │ ├── service │ │ │ ├── QueryService.java │ │ │ └── RequestQueryHandler.java │ │ └── test │ │ │ ├── MyAsyncBusExample.java │ │ │ ├── MyEventBusExample.java │ │ │ ├── MySimpleListener.java │ │ │ └── MySimpleListener2.java │ │ ├── functional │ │ └── FunctionExample.java │ │ ├── io │ │ ├── Base64.java │ │ └── package-info.java │ │ └── utilities │ │ ├── ElapsedExample.java │ │ ├── ObjectsExample.java │ │ ├── StopWatchExample.java │ │ └── package-info.java └── resources │ ├── io │ └── source.txt │ └── logback.xml └── test ├── java └── com │ └── wangwenjun │ └── guava │ ├── cache │ ├── CacheLoaderTest.java │ ├── CacheLoaderTest2.java │ ├── CacheLoaderTest3.java │ └── CacheLoaderTest4.java │ ├── collections │ ├── BiMapExampleTest.java │ ├── FluentIterableExampleTest.java │ ├── ImmutableCollectionsTest.java │ ├── ListsExampleTest.java │ ├── MapsExampleTest.java │ ├── MultimapsExampleTest.java │ ├── OrderingExampleTest.java │ ├── RangeExampleTest.java │ ├── SetsExampleTest.java │ └── TableExampleTest.java │ ├── io │ ├── BaseEncodingTest.java │ ├── ByteSinkTest.java │ ├── ByteSourceTest.java │ ├── CharSinkTest.java │ ├── CharSourceTest.java │ ├── CharStreamsTest.java │ ├── CloserTest.java │ └── FilesTest.java │ └── utilities │ ├── JoinerTest.java │ ├── PreconditionsTest.java │ ├── SplitterTest.java │ └── StringsTest.java └── resources └── io ├── files.PNG └── source.txt /.idea/codeStyleSettings.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 7 | 9 | -------------------------------------------------------------------------------- /.idea/compiler.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | -------------------------------------------------------------------------------- /.idea/encodings.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | -------------------------------------------------------------------------------- /.idea/libraries/Maven__ch_qos_logback_logback_classic_1_1_2.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | -------------------------------------------------------------------------------- /.idea/libraries/Maven__ch_qos_logback_logback_core_1_1_2.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | -------------------------------------------------------------------------------- /.idea/libraries/Maven__com_google_code_findbugs_jsr305_1_3_9.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | -------------------------------------------------------------------------------- /.idea/libraries/Maven__com_google_errorprone_error_prone_annotations_2_0_18.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | -------------------------------------------------------------------------------- /.idea/libraries/Maven__com_google_guava_guava_23_0.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | -------------------------------------------------------------------------------- /.idea/libraries/Maven__com_google_j2objc_j2objc_annotations_1_1.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | -------------------------------------------------------------------------------- /.idea/libraries/Maven__junit_junit_4_8_1.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | -------------------------------------------------------------------------------- /.idea/libraries/Maven__org_codehaus_mojo_animal_sniffer_annotations_1_14.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | -------------------------------------------------------------------------------- /.idea/libraries/Maven__org_slf4j_slf4j_api_1_7_12.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | -------------------------------------------------------------------------------- /.idea/misc.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 9 | 10 | 11 | 12 | 13 | -------------------------------------------------------------------------------- /.idea/modules.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | -------------------------------------------------------------------------------- /.idea/uiDesigner.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | 43 | 44 | 45 | 46 | 47 | 48 | 49 | 50 | 51 | 52 | 53 | 54 | 55 | 56 | 57 | 58 | 59 | 60 | 61 | 62 | 63 | 64 | 65 | 66 | 67 | 68 | 69 | 70 | 71 | 72 | 73 | 74 | 75 | 76 | 77 | 78 | 79 | 80 | 81 | 82 | 83 | 84 | 85 | 86 | 87 | 88 | 89 | 90 | 91 | 92 | 93 | 94 | 95 | 96 | 97 | 98 | 99 | 100 | 101 | 102 | 103 | 104 | 105 | 106 | 107 | 108 | 109 | 110 | 111 | 112 | 113 | 114 | 115 | 116 | 117 | 118 | 119 | 120 | 121 | 122 | 123 | 124 | -------------------------------------------------------------------------------- /.idea/vcs.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | -------------------------------------------------------------------------------- /Jenkinsfile: -------------------------------------------------------------------------------- 1 | pipeline { 2 | agent any 3 | stages { 4 | stage('checkout') { 5 | steps { 6 | git(url: 'git@github.com:wangwenjun/guava_programming.git', branch: 'master', changelog: true, poll: true) 7 | } 8 | } 9 | stage('compile') { 10 | steps { 11 | withMaven(jdk: '/opt/java') 12 | } 13 | } 14 | stage('deploy') { 15 | steps { 16 | echo 'hello' 17 | } 18 | } 19 | } 20 | } -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # guava_programming 2 | initial 3 | 4 | 5 | 背景: 6 | 最近公司因为用的云服务器,需要保证kafka的安全性。可喜的是kafka0.9开始,已经支持权限控制了。网上中文资料又少,特此基于kafka0.9,记录kafaka的权限控制 ( flume需要1.7及其以上才支持kafka的SSL认证)。 7 | 8 | 下面各位看官跟着小二一起开始kafak权限认证之旅吧!嘎嘎嘎! 9 | 10 | 介绍: 11 | kafka权限控制整体可以分为三种类型: 12 | 1.基于SSL(CDH 5.8不支持) 13 | 2.基于Kerberos(此认证一般基于CDH,本文不与讨论) 14 | 3.基于acl的 (CDH5.8中的kafka2.X不支持 ) 15 | 16 | 本文主要基于apace版本的,实现1和3,也是用的最多的展开讨论。 17 | 18 | 统一说明: 19 | 在本文中&符号表示注释 20 | 21 | 一,准备工作 22 | 组件分布 23 | kafka centos11,centos12,centos13 24 | zoopeeker centos11,centos12,centos13 25 | 26 | 二、在kafka集群任选一台机子 ( 先介绍基于SSL的 ) 27 | 28 | 密码统一为123456 29 | 30 | &Step 1 Generate SSL key and certificate for each Kafka broker 31 | keytool -keystore server.keystore.jks -alias centos11 -validity 365 -genkey 32 | 33 | %Step 2 Creating your own CA 34 | openssl req -new -x509 -keyout ca-key -out ca-cert -days 365 35 | keytool -keystore server.truststore.jks -alias CARoot -import -file ca-cert 36 | keytool -keystore client.truststore.jks -alias CARoot -import -file ca-cert 37 | 38 | &Step 3 Signing the certificate 39 | keytool -keystore server.keystore.jks -alias centos11 -certreq -file cert-file 40 | openssl x509 -req -CA ca-cert -CAkey ca-key -in cert-file -out cert-signed -days 365 -CAcreateserial -passin pass:123456 41 | keytool -keystore server.keystore.jks -alias CARoot -import -file ca-cert 42 | keytool -keystore server.keystore.jks -alias centos11 -import -file cert-signed 43 | 1 44 | 2 45 | 3 46 | 4 47 | 5 48 | 6 49 | 7 50 | 8 51 | 9 52 | 10 53 | 11 54 | 12 55 | 13 56 | 三、其他的kafka集群 57 | 58 | &机器centos13 centos12 59 | keytool -keystore kafka.client.keystore.jks -alias centos13 -validity 365 -genkey 60 | keytool -keystore kafka.client.keystore.jks -alias centos13 -certreq -file cert-file 61 | cp cert-file cert-file-centos13 62 | 63 | ¢os11 64 | scp ./ca* ce* server* root@centos13:/opt/kafka_2.10/ 65 | 66 | openssl x509 -req -CA ca-cert -CAkey ca-key -in cert-file-centos13 -out cert-signed-centos13 -days 365 -CAcreateserial -passin pass:123456 67 | keytool -keystore kafkacentos13.client.keystore.jks -alias CARoot -import -file ca-cert 68 | keytool -keystore kafkacentos13.client.keystore.jks -alias centos13 -import -file cert-signed-centos13 69 | 70 | 71 | 72 | rm -rf producer.properties 73 | echo "bootstrap.servers=centos13:9093" >> producer.properties 74 | echo "security.protocol=SSL" >> producer.properties 75 | echo "ssl.truststore.location=/opt/kafka_2.10/kafkacentos12.client.keystore.jks">> producer.properties 76 | echo "ssl.truststore.password=123456">> producer.properties 77 | echo "ssl.keystore.location=/opt/kafka_2.10/server.keystore.jks">> producer.properties 78 | echo "ssl.keystore.password=123456">> producer.properties 79 | echo "ssl.key.password=123456">> producer.properties 80 | 1 81 | 2 82 | 3 83 | 4 84 | 5 85 | 6 86 | 7 87 | 8 88 | 9 89 | 10 90 | 11 91 | 12 92 | 13 93 | 14 94 | 15 95 | 16 96 | 17 97 | 18 98 | 19 99 | 20 100 | 21 101 | 22 102 | 4.验证: 103 | 104 | openssl s_client -debug -connect localhost:9093 -tls1 105 | 106 | output: 107 | -----BEGIN CERTIFICATE----- 108 | {variable sized random bytes} 109 | -----END CERTIFICATE----- 110 | subject=/C=US/ST=CA/L=Santa Clara/O=org/OU=org/CN=Sriharsha Chintalapani 111 | issuer=/C=US/ST=CA/L=Santa Clara/O=org/OU=org/CN=kafka/emailAddress=test@test.com 112 | 1 113 | 2 114 | 3 115 | 4 116 | 5 117 | 6 118 | 7 119 | 8 120 | 5.使用: 121 | 122 | bin/kafka-console-consumer.sh --bootstrap-server kafka2:9093 --topic test --new-consumer --consumer.config config/producer.properties 123 | 124 | bin/kafka-console-producer.sh --broker-list centos11:9093 --topic test --producer.config ./config/producer.properties 125 | 126 | bin/kafka-console-consumer.sh --bootstrap-server centos11:9093 --topic test --new-consumer --consumer.config ./config/producer.properties 127 | 128 | bin/kafka-console-consumer.sh --bootstrap-server centos13:9093 --topic test --new-consumer --consumer.config ./config/producer.properties --from-beginning 129 | 1 130 | 2 131 | 3 132 | 4 133 | 5 134 | 6 135 | 7 136 | 6.基于ACL 137 | 138 | server.properties中加配置 139 | 140 | allow.everyone.if.no.acl.found=true 141 | super.users=User:root 142 | authorizer.class.name=kafka.security.auth.SimpleAclAuthorizer 143 | principal.builder.class=org.apache.kafka.common.security.auth.DefaultPrincipalBuilder 144 | 1 145 | 2 146 | 3 147 | 4 148 | 7.ACL的简单使用: 149 | 150 | bin/kafka-acls.sh --authorizer-properties zookeeper.connect=centos11:2181 --add --allow-principal User:Bob --allow-principal User:Alice --allow-host 198.51.100.0 --allow-host 198.51.100.1 --operation Read --operation Write --topic test 151 | 152 | bin/kafka-acls.sh --authorizer-properties zookeeper.connect=centos11:2181 --remove --allow-principal User:Bob --allow-principal User:Alice --allow-host 198.51.100.0 --allow-host 198.51.100.1 --operation Read --operation Write --topic test 153 | 1 154 | 2 155 | 3 156 | 8.Java Demo 157 | 需要将server.keystore.jks、client.truststore.jks从任一台机器上拷贝下来即可。 158 | 159 | SSL is supported only for the new Kafka Producer and Consumer, the older API is not supported 160 | 161 | ConsumerDemo 162 | 163 | package xmhd.examples; 164 | 165 | import org.apache.kafka.clients.CommonClientConfigs; 166 | import org.apache.kafka.clients.consumer.ConsumerRecord; 167 | import org.apache.kafka.clients.consumer.ConsumerRecords; 168 | import org.apache.kafka.clients.consumer.KafkaConsumer; 169 | import org.apache.kafka.clients.producer.ProducerConfig; 170 | import org.apache.kafka.common.config.SslConfigs; 171 | import java.util.Arrays; 172 | import java.util.Properties; 173 | /** 174 | * Created by shengjk1. 175 | * blog address :http://blog.csdn.net/jsjsjs1789 176 | * 177 | * 生产者可以保证权限认证 178 | * SSL is supported only for the new Kafka Producer and Consumer, the older API is not supported 179 | */ 180 | public class ConsumerZbdba { 181 | public static void main(String[] args) { 182 | // new ConsumerZbdba("test").start();// 使用kafka集群中创建好的主题 test 183 | Properties props = new Properties(); 184 | /* 定义kakfa 服务的地址,不需要将所有broker指定上 */ 185 | props.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, "centos11:9093;centos13:9093;centos12:9093"); 186 | /* 制定consumer group */ 187 | props.put("group.id", "test"); 188 | props.put("auto.offset.reset","earliest"); 189 | /* 是否自动确认offset */ 190 | // props.put("enable.auto.commit", "true"); 191 | // props.put(ProducerConfig.CLIENT_ID_CONFIG, "myApiKey"); 192 | props.put(SslConfigs.SSL_KEYSTORE_LOCATION_CONFIG, "F:\\server.keystore.jks"); 193 | props.put(SslConfigs.SSL_KEYSTORE_PASSWORD_CONFIG, "123456"); 194 | props.put(SslConfigs.SSL_TRUSTSTORE_LOCATION_CONFIG, "F:\\client.truststore.jks"); 195 | props.put(SslConfigs.SSL_TRUSTSTORE_PASSWORD_CONFIG, "123456"); 196 | props.put(SslConfigs.SSL_TRUSTSTORE_TYPE_CONFIG, "JKS"); 197 | props.put(CommonClientConfigs.SECURITY_PROTOCOL_CONFIG, "SSL"); 198 | // 199 | 200 | 201 | ///* 自动确认offset的时间间隔 */ 202 | // props.put("auto.commit.interval.ms", "1000"); 203 | // props.put("session.timeout.ms", "30000"); 204 | /* key的序列化类 */ 205 | props.put("key.deserializer", "org.apache.kafka.common.serialization.StringDeserializer"); 206 | /* value的序列化类 */ 207 | props.put("value.deserializer", "org.apache.kafka.common.serialization.StringDeserializer"); 208 | /* 定义consumer */ 209 | KafkaConsumer consumer = new KafkaConsumer<>(props); 210 | /* 消费者订阅的topic, 可同时订阅多个 */ 211 | consumer.subscribe(Arrays.asList("test")); 212 | 213 | /* 读取数据,读取超时时间为100ms */ 214 | while (true) { 215 | ConsumerRecords records = consumer.poll(100); 216 | for (ConsumerRecord record : records) 217 | System.out.printf("offset = %d, key = %s, value = %s", record.offset(), record.key(), record.value()+"\n"); 218 | } 219 | } 220 | } 221 | 1 222 | 2 223 | 3 224 | 4 225 | 5 226 | 6 227 | 7 228 | 8 229 | 9 230 | 10 231 | 11 232 | 12 233 | 13 234 | 14 235 | 15 236 | 16 237 | 17 238 | 18 239 | 19 240 | 20 241 | 21 242 | 22 243 | 23 244 | 24 245 | 25 246 | 26 247 | 27 248 | 28 249 | 29 250 | 30 251 | 31 252 | 32 253 | 33 254 | 34 255 | 35 256 | 36 257 | 37 258 | 38 259 | 39 260 | 40 261 | 41 262 | 42 263 | 43 264 | 44 265 | 45 266 | 46 267 | 47 268 | 48 269 | 49 270 | 50 271 | 51 272 | 52 273 | 53 274 | 54 275 | 55 276 | 56 277 | 57 278 | 58 279 | ProducerDemo 280 | 281 | package xmhd.examples; 282 | import org.apache.kafka.clients.CommonClientConfigs; 283 | import org.apache.kafka.clients.producer.KafkaProducer; 284 | import org.apache.kafka.clients.producer.ProducerConfig; 285 | import org.apache.kafka.clients.producer.ProducerRecord; 286 | import org.apache.kafka.common.config.SslConfigs; 287 | import java.util.Properties; 288 | /** 289 | * Created by shengjk1. 290 | * blog address :http://blog.csdn.net/jsjsjs1789 291 | * 生产者可以保证权限认证 292 | */ 293 | public class ProducerZbdba { 294 | public static void main(String[] args) { 295 | Properties producerProps = new Properties(); 296 | producerProps.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, "centos12:9093"); 297 | // producerProps.put(ProducerConfig.CLIENT_ID_CONFIG, "myApiKey"); 298 | producerProps.put(SslConfigs.SSL_KEYSTORE_LOCATION_CONFIG, "F:\\server.keystore.jks"); 299 | producerProps.put(SslConfigs.SSL_KEYSTORE_PASSWORD_CONFIG, "123456"); 300 | producerProps.put(SslConfigs.SSL_TRUSTSTORE_LOCATION_CONFIG, "F:\\client.truststore.jks"); 301 | producerProps.put(SslConfigs.SSL_TRUSTSTORE_PASSWORD_CONFIG, "123456"); 302 | producerProps.put(SslConfigs.SSL_TRUSTSTORE_TYPE_CONFIG, "JKS"); 303 | producerProps.put(CommonClientConfigs.SECURITY_PROTOCOL_CONFIG, "SSL"); 304 | producerProps.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, "org.apache.kafka.common.serialization.StringSerializer"); 305 | producerProps.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, "org.apache.kafka.common.serialization.StringSerializer"); 306 | KafkaProducer producer = new KafkaProducer(producerProps); 307 | for(int i = 0; i < 100; i++) 308 | producer.send(new ProducerRecord("test", Integer.toString(i), Integer.toString(i))); 309 | System.out.println("test"); 310 | producer.close(); 311 | } 312 | } 313 | 1 314 | 2 315 | 3 316 | 4 317 | 5 318 | 6 319 | 7 320 | 8 321 | 9 322 | 10 323 | 11 324 | 12 325 | 13 326 | 14 327 | 15 328 | 16 329 | 17 330 | 18 331 | 19 332 | 20 333 | 21 334 | 22 335 | 23 336 | 24 337 | 25 338 | 26 339 | 27 340 | 28 341 | 29 342 | 30 343 | 31 344 | 32 345 | 8.1 flume1.7 的配置 (基于kafka SSL认证) 346 | 347 | tier1.sources = source1 348 | tier1.channels = channel1 349 | tier1.sinks = sink1 350 | 351 | 352 | tier1.sources.source1.type = exec 353 | tier1.sources.source1.command = tail -F -n+1 /opt/scan.log 354 | tier1.sources.source1.channels = channel1 355 | 356 | tier1.channels.channel1.type = memory 357 | tier1.sinks.sink1.type = org.apache.flume.sink.kafka.KafkaSink 358 | tier1.sinks.sink1.topic = test 359 | tier1.sinks.sink1.kafka.bootstrap.servers = centos11:9093,centos12:9093,centos13:9093 360 | tier1.channels.channel1.kafka.bootstrap.servers = centos11:9093,centos12:9093,centos13:9093 361 | tier1.sinks.sink1.requiredAcks = 1 362 | tier1.sinks.sink1.batchSize = 100 363 | 364 | 365 | tier1.sinks.sink1.kafka.producer.security.protocol = SSL 366 | tier1.sinks.sink1.kafka.producer.ssl.truststore.type=JKS 367 | tier1.sinks.sink1.kafka.producer.ssl.truststore.location = /opt/kafka_2.10/server.truststore.jks 368 | tier1.sinks.sink1.kafka.producer.ssl.truststore.password =123456 369 | tier1.sinks.sink1.kafka.producer.security.protocol = SSL 370 | tier1.sinks.sink1.kafka.producer.ssl.keystore.location = /opt/kafka_2.10/server.keystore.jks 371 | tier1.sinks.sink1.kafka.producer.ssl.keystore.password =123456 372 | &tier1.sinks.sink1.kafka.producer.ssl.endpoint.identification.algorithm = HTTPS 373 | 374 | 375 | tier1.sinks.sink1.channel = channel1 376 | tier1.channels.channel1.capacity = 100 377 | 378 | 379 | &tier1.channels.channel1.kafka.producer.security.protocol = SSL 380 | &tier1.channels.channel1.kafka.producer.ssl.truststore.type=JKS 381 | &tier1.channels.channel1.kafka.producer.ssl.truststore.location = /opt/kafka_2.10/server.truststore.jks 382 | &tier1.channels.channel1.kafka.producer.ssl.truststore.password =123456 383 | &tier1.channels.channel1.kafka.producer.security.protocol = SSL 384 | &tier1.channels.channel1.kafka.producer.ssl.keystore.location = /opt/kafka_2.10/server.keystore.jks 385 | &tier1.channels.channel1.kafka.producer.ssl.keystore.password =123456 386 | &tier1.channels.channel1.kafka.producer.ssl.endpoint.identification.algorithm = HTTPS 387 | 388 | 389 | &tier1.channels.channel1.kafka.consumer.security.protocol = SSL 390 | &tier1.channels.channel1.kafka.consumer.ssl.truststore.location = /opt/kafka_2.10/server.truststore.jks 391 | &tier1.channels.channel1.kafka.consumer.ssl.truststore.password =123456 392 | &tier1.channels.channel1.kafka.consumer.security.protocol = SSL 393 | &tier1.channels.channel1.kafka.consumer.ssl.keystore.location = /opt/kafka_2.10/server.truststore.jks 394 | &tier1.channels.channel1.kafka.consumer.ssl.keystore.password =123456 395 | &tier1.channels.channel1.kafka.consumer.ssl.endpoint.identification.algorithm = HTTPS 396 | 1 397 | 2 398 | 3 399 | 4 400 | 5 401 | 6 402 | 7 403 | 8 404 | 9 405 | 10 406 | 11 407 | 12 408 | 13 409 | 14 410 | 15 411 | 16 412 | 17 413 | 18 414 | 19 415 | 20 416 | 21 417 | 22 418 | 23 419 | 24 420 | 25 421 | 26 422 | 27 423 | 28 424 | 29 425 | 30 426 | 31 427 | 32 428 | 33 429 | 34 430 | 35 431 | 36 432 | 37 433 | 38 434 | 39 435 | 40 436 | 41 437 | 42 438 | 43 439 | 44 440 | 45 441 | 46 442 | 47 443 | 48 444 | 49 445 | 9.kafak Server.properties最终版的 446 | 447 | 三台机子需保证一样,centos11为机器名,根据需要自行修改 448 | 449 | broker.id=0 450 | ############################# Socket Server Settings ############################# 451 | &这一点可能需要特别的注意,PLAINTEXT注释掉之后,一些基本的kafka脚本都不在能用了 452 | &listeners=PLAINTEXT://centos11:9092,SSL://centos11:9093 453 | listeners=SSL://centos11:9093 454 | advertised.listeners=SSL://centos11:9093 455 | ssl.keystore.location=/opt/kafka_2.10/server.keystore.jks 456 | ssl.keystore.password=123456 457 | ssl.key.password=123456 458 | ssl.truststore.location=/opt/kafka_2.10/server.truststore.jks 459 | ssl.truststore.password=123456 460 | ssl.client.auth=required 461 | ssl.enabled.protocols=TLSv1.2,TLSv1.1,TLSv1 462 | ssl.keystore.type=JKS 463 | ssl.truststore.type=JKS 464 | security.inter.broker.protocol=SSL 465 | 466 | &acl 467 | allow.everyone.if.no.acl.found=true 468 | super.users=User:root 469 | authorizer.class.name=kafka.security.auth.SimpleAclAuthorizer 470 | principal.builder.class=org.apache.kafka.common.security.auth.DefaultPrincipalBuilder 471 | 472 | host.name=centos11 473 | advertised.host.name=centos11 474 | 475 | num.network.threads=3 476 | num.io.threads=8 477 | socket.send.buffer.bytes=102400 478 | socket.receive.buffer.bytes=102400 479 | socket.request.max.bytes=104857600 480 | ############################# Log Basics ############################# 481 | log.dirs=/opt/kafka-logs 482 | num.partitions=1 483 | num.recovery.threads.per.data.dir=1 484 | log.retention.hours=168 485 | log.segment.bytes=1073741824 486 | log.retention.check.interval.ms=300000 487 | ############################# Zookeeper ############################# 488 | zookeeper.connect=centos11:2181,centos12:2181,centos13:2181 489 | zookeeper.connection.timeout.ms=6000 490 | 1 491 | 2 492 | 3 493 | 4 494 | 5 495 | 6 496 | 7 497 | 8 498 | 9 499 | 10 500 | 11 501 | 12 502 | 13 503 | 14 504 | 15 505 | 16 506 | 17 507 | 18 508 | 19 509 | 20 510 | 21 511 | 22 512 | 23 513 | 24 514 | 25 515 | 26 516 | 27 517 | 28 518 | 29 519 | 30 520 | 31 521 | 32 522 | 33 523 | 34 524 | 35 525 | 36 526 | 37 527 | 38 528 | 39 529 | 40 530 | 41 531 | kafka producer.properties 532 | centos11为机器名,根据需求自行修改 533 | 534 | bootstrap.servers=centos11:9093 535 | security.protocol=SSL 536 | ssl.truststore.location=/opt/kafka_2.10/client.truststore.jks 537 | ssl.truststore.password=123456 538 | ssl.keystore.location=/opt/kafka_2.10/server.keystore.jks 539 | ssl.keystore.password=123456 540 | ssl.key.password=123456 541 | -------------------------------------------------------------------------------- /guava_programming.iml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | -------------------------------------------------------------------------------- /my_servant/pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 5 | 6 | guava_programming 7 | guava_programming 8 | 1.0-SNAPSHOT 9 | 10 | 4.0.0 11 | 12 | my_servant 13 | 14 | 15 | 16 | 17 | my_service 18 | guava_programming 19 | 1.0-SNAPSHOT 20 | 21 | 22 | -------------------------------------------------------------------------------- /my_servant/src/main/java/com/wangwenjun/servant/ServiceInvoker.java: -------------------------------------------------------------------------------- 1 | package com.wangwenjun.servant; 2 | 3 | import com.wangwenjun.service.Service; 4 | 5 | import java.util.ServiceLoader; 6 | 7 | /*************************************** 8 | * @author:Alex Wang 9 | * @Date:2017/10/11 10 | * @QQ: 532500648 11 | ***************************************/ 12 | public class ServiceInvoker { 13 | public static void main(String[] args) { 14 | ServiceLoader serviceLoader = ServiceLoader.load(Service.class); 15 | for (Service service : serviceLoader) { 16 | service.show(); 17 | } 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /my_service/my_service.iml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | -------------------------------------------------------------------------------- /my_service/pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 5 | 6 | guava_programming 7 | guava_programming 8 | 1.0-SNAPSHOT 9 | 10 | 4.0.0 11 | 12 | my_service 13 | 14 | 15 | -------------------------------------------------------------------------------- /my_service/src/main/java/com/wangwenjun/service/Service.java: -------------------------------------------------------------------------------- 1 | package com.wangwenjun.service; 2 | 3 | /*************************************** 4 | * @author:Alex Wang 5 | * @Date:2017/10/11 6 | * @QQ: 532500648 7 | ***************************************/ 8 | public interface Service { 9 | 10 | void show(); 11 | } 12 | -------------------------------------------------------------------------------- /my_service/src/main/java/com/wangwenjun/service/SimpleService.java: -------------------------------------------------------------------------------- 1 | package com.wangwenjun.service; 2 | 3 | /*************************************** 4 | * @author:Alex Wang 5 | * @Date:2017/10/11 6 | * @QQ: 532500648 7 | ***************************************/ 8 | public class SimpleService implements Service { 9 | @Override 10 | public void show() { 11 | System.out.println("hi i come from the service loader."); 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /my_service/src/main/resources/META-INF/services/com.wangwenjun.service.Service: -------------------------------------------------------------------------------- 1 | com.wangwenjun.service.SimpleService -------------------------------------------------------------------------------- /pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 5 | 4.0.0 6 | 7 | guava_programming 8 | guava_programming 9 | pom 10 | 1.0-SNAPSHOT 11 | 12 | 13 | 14 | org.apache.maven.plugins 15 | maven-compiler-plugin 16 | 17 | 1.8 18 | 1.8 19 | 20 | 21 | 22 | 23 | 24 | my_service 25 | my_servant 26 | 27 | 28 | 29 | 30 | 31 | com.google.guava 32 | guava 33 | 23.0 34 | 35 | 36 | 37 | junit 38 | junit 39 | 4.8.1 40 | test 41 | 42 | 43 | 44 | org.slf4j 45 | slf4j-api 46 | 1.7.12 47 | 48 | 49 | 50 | ch.qos.logback 51 | logback-classic 52 | 1.1.2 53 | 54 | 55 | 56 | ch.qos.logback 57 | logback-core 58 | 1.1.2 59 | 60 | 61 | 62 | commons-io 63 | commons-io 64 | 2.4 65 | 66 | 67 | -------------------------------------------------------------------------------- /src/main/java/com/wangwenjun/guava/cache/Employee.java: -------------------------------------------------------------------------------- 1 | package com.wangwenjun.guava.cache; 2 | 3 | import com.google.common.base.MoreObjects; 4 | 5 | /*************************************** 6 | * @author:Alex Wang 7 | * @Date:2017/11/18 8 | * QQ: 532500648 9 | * QQ群:463962286 10 | ***************************************/ 11 | public class Employee 12 | { 13 | private final String name; 14 | private final String dept; 15 | private final String empID; 16 | private final byte[] data = new byte[1024 * 1024]; 17 | 18 | public Employee(String name, String dept, String empID) 19 | { 20 | this.name = name; 21 | this.dept = dept; 22 | this.empID = empID; 23 | } 24 | 25 | public String getName() 26 | { 27 | return name; 28 | } 29 | 30 | public String getDept() 31 | { 32 | return dept; 33 | } 34 | 35 | public String getEmpID() 36 | { 37 | return empID; 38 | } 39 | 40 | @Override 41 | public String toString() 42 | { 43 | return MoreObjects.toStringHelper(this) 44 | .add("Name", this.getName()).add("Department", getDept()) 45 | .add("EmployeeID", this.getEmpID()).toString(); 46 | } 47 | 48 | @Override 49 | protected void finalize() throws Throwable 50 | { 51 | System.out.println("The name " + getName() + " will be GC."); 52 | } 53 | } -------------------------------------------------------------------------------- /src/main/java/com/wangwenjun/guava/cache/LRUCache.java: -------------------------------------------------------------------------------- 1 | package com.wangwenjun.guava.cache; 2 | 3 | /*************************************** 4 | * @author:Alex Wang 5 | * @Date:2017/11/13 6 | * QQ: 532500648 7 | * QQ群:463962286 8 | ***************************************/ 9 | public interface LRUCache 10 | { 11 | 12 | void put(K key, V value); 13 | 14 | V get(K key); 15 | 16 | void remove(K key); 17 | 18 | int size(); 19 | 20 | void clear(); 21 | 22 | int limit(); 23 | } 24 | -------------------------------------------------------------------------------- /src/main/java/com/wangwenjun/guava/cache/LRUCacheExample.java: -------------------------------------------------------------------------------- 1 | package com.wangwenjun.guava.cache; 2 | 3 | import java.util.concurrent.TimeUnit; 4 | 5 | /*************************************** 6 | * @author:Alex Wang 7 | * @Date:2017/11/16 8 | * QQ: 532500648 9 | * QQ群:463962286 10 | ***************************************/ 11 | public class LRUCacheExample 12 | { 13 | 14 | public static void main(String[] args) throws InterruptedException 15 | { 16 | final SoftLRUCache cache = new SoftLRUCache<>(100); 17 | 18 | for (int i = 0; i < 1000; i++) 19 | { 20 | cache.put(String.valueOf(i), new byte[1024 * 1024 * 2]); 21 | TimeUnit.MILLISECONDS.sleep(600); 22 | System.out.println("The " + i + " entity is cached."); 23 | } 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /src/main/java/com/wangwenjun/guava/cache/LinkedHashLRUCache.java: -------------------------------------------------------------------------------- 1 | package com.wangwenjun.guava.cache; 2 | 3 | import com.google.common.base.Preconditions; 4 | 5 | import java.util.LinkedHashMap; 6 | import java.util.Map; 7 | 8 | /*************************************** 9 | * @author:Alex Wang 10 | * @Date:2017/11/13 11 | * QQ: 532500648 12 | * QQ群:463962286 13 | ***************************************/ 14 | 15 | /** 16 | * This class is not the thread-safe class. 17 | * 18 | * @param 19 | * @param 20 | */ 21 | public class LinkedHashLRUCache implements LRUCache 22 | { 23 | private static class InternalLRUCache extends LinkedHashMap 24 | { 25 | final private int limit; 26 | 27 | public InternalLRUCache(int limit) 28 | { 29 | super(16, 0.75f, true); 30 | this.limit = limit; 31 | } 32 | 33 | @Override 34 | protected boolean removeEldestEntry(Map.Entry eldest) 35 | { 36 | return size() > limit; 37 | } 38 | } 39 | 40 | private final int limit; 41 | 42 | private final InternalLRUCache internalLRUCache; 43 | 44 | 45 | public LinkedHashLRUCache(int limit) 46 | { 47 | Preconditions.checkArgument(limit > 0, "The limit big than zero."); 48 | this.limit = limit; 49 | this.internalLRUCache = new InternalLRUCache<>(limit); 50 | } 51 | 52 | @Override 53 | public void put(K key, V value) 54 | { 55 | this.internalLRUCache.put(key, value); 56 | } 57 | 58 | @Override 59 | public V get(K key) 60 | { 61 | return this.internalLRUCache.get(key); 62 | } 63 | 64 | @Override 65 | public void remove(K key) 66 | { 67 | this.internalLRUCache.remove(key); 68 | } 69 | 70 | @Override 71 | public int size() 72 | { 73 | return this.internalLRUCache.size(); 74 | } 75 | 76 | @Override 77 | public void clear() 78 | { 79 | this.internalLRUCache.clear(); 80 | } 81 | 82 | @Override 83 | public int limit() 84 | { 85 | return this.limit; 86 | } 87 | 88 | @Override 89 | public String toString() 90 | { 91 | return internalLRUCache.toString(); 92 | } 93 | } -------------------------------------------------------------------------------- /src/main/java/com/wangwenjun/guava/cache/LinkedHashLRUCacheExample.java: -------------------------------------------------------------------------------- 1 | package com.wangwenjun.guava.cache; 2 | 3 | /*************************************** 4 | * @author:Alex Wang 5 | * @Date:2017/11/13 6 | * QQ: 532500648 7 | * QQ群:463962286 8 | ***************************************/ 9 | public class LinkedHashLRUCacheExample 10 | { 11 | public static void main(String[] args) 12 | { 13 | LRUCache cache = new LinkedHashLRUCache<>(3); 14 | cache.put("1", "1"); 15 | cache.put("2", "2"); 16 | cache.put("3", "3"); 17 | System.out.println(cache); 18 | cache.put("4", "4"); 19 | 20 | System.out.println(cache); 21 | 22 | System.out.println(cache.get("2")); 23 | System.out.println(cache); 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /src/main/java/com/wangwenjun/guava/cache/LinkedListLRUCache.java: -------------------------------------------------------------------------------- 1 | package com.wangwenjun.guava.cache; 2 | 3 | import com.google.common.base.Preconditions; 4 | 5 | import java.util.HashMap; 6 | import java.util.LinkedList; 7 | import java.util.Map; 8 | 9 | /*************************************** 10 | * @author:Alex Wang 11 | * @Date:2017/11/13 12 | * QQ: 532500648 13 | * QQ群:463962286 14 | ***************************************/ 15 | 16 | /** 17 | * this class is not thread-safe class 18 | * 19 | * @param 20 | * @param 21 | */ 22 | public class LinkedListLRUCache implements LRUCache 23 | { 24 | private final int limit; 25 | 26 | private final LinkedList keys = new LinkedList<>(); 27 | 28 | private final Map cache = new HashMap<>(); 29 | 30 | public LinkedListLRUCache(int limit) 31 | { 32 | this.limit = limit; 33 | } 34 | 35 | @Override 36 | public void put(K key, V value) 37 | { 38 | Preconditions.checkNotNull(key); 39 | Preconditions.checkNotNull(value); 40 | if (keys.size() >= limit) 41 | { 42 | K oldestKey = keys.removeFirst(); 43 | cache.remove(oldestKey); 44 | } 45 | 46 | keys.addLast(key); 47 | cache.put(key, value); 48 | } 49 | 50 | @Override 51 | public V get(K key) 52 | { 53 | boolean exist = keys.remove(key); 54 | if (!exist) 55 | return null; 56 | 57 | keys.addLast(key); 58 | return cache.get(key); 59 | } 60 | 61 | @Override 62 | public void remove(K key) 63 | { 64 | boolean exist = keys.remove(key); 65 | if (exist) 66 | { 67 | cache.remove(key); 68 | } 69 | } 70 | 71 | @Override 72 | public int size() 73 | { 74 | return keys.size(); 75 | } 76 | 77 | @Override 78 | public void clear() 79 | { 80 | this.keys.clear(); 81 | this.cache.clear(); 82 | } 83 | 84 | @Override 85 | public int limit() 86 | { 87 | return this.limit; 88 | } 89 | 90 | @Override 91 | public String toString() 92 | { 93 | final StringBuilder builder = new StringBuilder(); 94 | for (K k : keys) 95 | { 96 | builder.append(k).append("=").append(cache.get(k)).append(";"); 97 | } 98 | return builder.toString(); 99 | } 100 | } 101 | -------------------------------------------------------------------------------- /src/main/java/com/wangwenjun/guava/cache/LinkedListLRUCacheExample.java: -------------------------------------------------------------------------------- 1 | package com.wangwenjun.guava.cache; 2 | 3 | /*************************************** 4 | * @author:Alex Wang 5 | * @Date:2017/11/13 6 | * QQ: 532500648 7 | * QQ群:463962286 8 | ***************************************/ 9 | public class LinkedListLRUCacheExample 10 | { 11 | 12 | public static void main(String[] args) 13 | { 14 | LRUCache cache = new LinkedListLRUCache<>(3); 15 | cache.put("1", "1"); 16 | cache.put("2", "2"); 17 | cache.put("3", "3"); 18 | System.out.println(cache); 19 | cache.put("4", "4"); 20 | 21 | System.out.println(cache); 22 | 23 | System.out.println(cache.get("2")); 24 | System.out.println(cache); 25 | 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /src/main/java/com/wangwenjun/guava/cache/ReferenceExample.java: -------------------------------------------------------------------------------- 1 | package com.wangwenjun.guava.cache; 2 | 3 | import java.lang.ref.*; 4 | import java.util.ArrayList; 5 | import java.util.List; 6 | import java.util.concurrent.TimeUnit; 7 | 8 | public class ReferenceExample 9 | { 10 | 11 | public static void main(String[] args) throws InterruptedException 12 | { 13 | //Strong Reference 14 | /*int counter = 1; 15 | 16 | List container = new ArrayList<>(); 17 | 18 | for (; ; ) 19 | { 20 | int current = counter++; 21 | container.add(new Ref(current)); 22 | System.out.println("The " + current + " Ref will be insert into container"); 23 | TimeUnit.MILLISECONDS.sleep(500); 24 | }*/ 25 | 26 | // SoftReference reference = new SoftReference<>(new Ref(0)); 27 | 28 | /** 29 | * detected the JVM process will be OOM then try to GC soft reference. 30 | * 31 | */ 32 | 33 | //soft reference 34 | /* int counter = 1; 35 | 36 | List> container = new ArrayList<>(); 37 | 38 | for (; ; ) 39 | { 40 | int current = counter++; 41 | container.add(new SoftReference<>(new Ref(current))); 42 | System.out.println("The " + current + " Ref will be insert into container"); 43 | TimeUnit.SECONDS.sleep(1); 44 | }*/ 45 | 46 | /** 47 | * Weak reference 48 | * 49 | * The reference will be collected when GC. 50 | */ 51 | /*int counter = 1; 52 | 53 | List> container = new ArrayList<>(); 54 | 55 | for (; ; ) 56 | { 57 | int current = counter++; 58 | container.add(new WeakReference<>(new Ref(current))); 59 | System.out.println("The " + current + " Ref will be insert into container"); 60 | TimeUnit.MILLISECONDS.sleep(200); 61 | }*/ 62 | 63 | Ref ref = new Ref(10); 64 | ReferenceQueue queue = new ReferenceQueue<>(); 65 | MyPhantomReference reference = new MyPhantomReference(ref, queue, 10); 66 | ref = null; 67 | 68 | System.out.println(reference.get()); 69 | 70 | System.gc(); 71 | // TimeUnit.SECONDS.sleep(1); 72 | Reference object = queue.remove(); 73 | ((MyPhantomReference) object).doAction(); 74 | 75 | /* System.gc(); 76 | 77 | TimeUnit.SECONDS.sleep(1); 78 | System.out.println(ref); 79 | System.out.println(reference.get().index);*/ 80 | 81 | /** 82 | * File file = new File(); 83 | * file.create(); 84 | * 85 | * 86 | * 87 | * 88 | */ 89 | } 90 | 91 | private static class MyPhantomReference extends PhantomReference 92 | { 93 | 94 | private int index; 95 | 96 | public MyPhantomReference(Object referent, ReferenceQueue q, int index) 97 | { 98 | super(referent, q); 99 | this.index = index; 100 | } 101 | 102 | public void doAction() 103 | { 104 | System.out.println("The object " + index + " is GC."); 105 | } 106 | } 107 | 108 | private static class Ref 109 | { 110 | 111 | private byte[] data = new byte[1024 * 1024]; 112 | 113 | private final int index; 114 | 115 | private Ref(int index) 116 | { 117 | this.index = index; 118 | } 119 | 120 | @Override 121 | protected void finalize() throws Throwable 122 | { 123 | System.out.println("The index [" + index + "] will be GC."); 124 | } 125 | } 126 | } 127 | -------------------------------------------------------------------------------- /src/main/java/com/wangwenjun/guava/cache/SoftLRUCache.java: -------------------------------------------------------------------------------- 1 | package com.wangwenjun.guava.cache; 2 | 3 | import java.lang.ref.SoftReference; 4 | import java.util.LinkedHashMap; 5 | import java.util.Map; 6 | 7 | /*************************************** 8 | * @author:Alex Wang 9 | * @Date:2017/11/16 10 | * QQ: 532500648 11 | * QQ群:463962286 12 | ***************************************/ 13 | public class SoftLRUCache implements LRUCache 14 | { 15 | 16 | 17 | private static class InternalLRUCache extends LinkedHashMap> 18 | { 19 | final private int limit; 20 | 21 | public InternalLRUCache(int limit) 22 | { 23 | super(16, 0.75f, true); 24 | this.limit = limit; 25 | } 26 | 27 | @Override 28 | protected boolean removeEldestEntry(Map.Entry> eldest) 29 | { 30 | return this.size() > limit; 31 | } 32 | } 33 | 34 | private final int limit; 35 | 36 | private final InternalLRUCache cache; 37 | 38 | public SoftLRUCache(int limit) 39 | { 40 | this.limit = limit; 41 | this.cache = new InternalLRUCache<>(limit); 42 | } 43 | 44 | @Override 45 | public void put(K key, V value) 46 | { 47 | this.cache.put(key, new SoftReference<>(value)); 48 | } 49 | 50 | @Override 51 | public V get(K key) 52 | { 53 | SoftReference reference = this.cache.get(key); 54 | if (null == reference) return null; 55 | return reference.get(); 56 | } 57 | 58 | @Override 59 | public void remove(K key) 60 | { 61 | this.cache.remove(key); 62 | } 63 | 64 | @Override 65 | public int size() 66 | { 67 | return this.cache.size(); 68 | } 69 | 70 | @Override 71 | public void clear() 72 | { 73 | this.cache.clear(); 74 | } 75 | 76 | @Override 77 | public int limit() 78 | { 79 | return this.limit; 80 | } 81 | } 82 | -------------------------------------------------------------------------------- /src/main/java/com/wangwenjun/guava/collections/BiMapExample.java: -------------------------------------------------------------------------------- 1 | package com.wangwenjun.guava.collections; 2 | 3 | /*************************************** 4 | * @author:Alex Wang 5 | * @Date:2018/1/14 6 | * QQ: 532500648 7 | * QQ群:463962286 8 | ***************************************/ 9 | public class BiMapExample 10 | { 11 | } 12 | -------------------------------------------------------------------------------- /src/main/java/com/wangwenjun/guava/collections/FluentIterableExample.java: -------------------------------------------------------------------------------- 1 | package com.wangwenjun.guava.collections; 2 | 3 | /*************************************** 4 | * @author:Alex Wang 5 | * @Date:2018/1/13 6 | * QQ: 532500648 7 | * QQ群:463962286 8 | ***************************************/ 9 | public class FluentIterableExample 10 | { 11 | } 12 | -------------------------------------------------------------------------------- /src/main/java/com/wangwenjun/guava/collections/ImmutableCollections.java: -------------------------------------------------------------------------------- 1 | package com.wangwenjun.guava.collections; 2 | 3 | /*************************************** 4 | * @author:Alex Wang 5 | * @Date:2018/1/15 6 | * QQ: 532500648 7 | * QQ群:463962286 8 | ***************************************/ 9 | public class ImmutableCollections 10 | { 11 | } 12 | -------------------------------------------------------------------------------- /src/main/java/com/wangwenjun/guava/collections/ListsExample.java: -------------------------------------------------------------------------------- 1 | package com.wangwenjun.guava.collections; 2 | 3 | /*************************************** 4 | * @author:Alex Wang 5 | * @Date:2018/1/13 6 | * QQ: 532500648 7 | * QQ群:463962286 8 | ***************************************/ 9 | public class ListsExample 10 | { 11 | } 12 | -------------------------------------------------------------------------------- /src/main/java/com/wangwenjun/guava/collections/MapsExample.java: -------------------------------------------------------------------------------- 1 | package com.wangwenjun.guava.collections; 2 | 3 | /*************************************** 4 | * @author:Alex Wang 5 | * @Date:2018/1/14 6 | * QQ: 532500648 7 | * QQ群:463962286 8 | ***************************************/ 9 | public class MapsExample 10 | { 11 | } 12 | -------------------------------------------------------------------------------- /src/main/java/com/wangwenjun/guava/collections/MultimapsExample.java: -------------------------------------------------------------------------------- 1 | package com.wangwenjun.guava.collections; 2 | 3 | /*************************************** 4 | * @author:Alex Wang 5 | * @Date:2018/1/14 6 | * QQ: 532500648 7 | * QQ群:463962286 8 | ***************************************/ 9 | public class MultimapsExample 10 | { 11 | } 12 | -------------------------------------------------------------------------------- /src/main/java/com/wangwenjun/guava/collections/OrderingExample.java: -------------------------------------------------------------------------------- 1 | package com.wangwenjun.guava.collections; 2 | 3 | /*************************************** 4 | * @author:Alex Wang 5 | * @Date:2018/1/15 6 | * QQ: 532500648 7 | * QQ群:463962286 8 | ***************************************/ 9 | public class OrderingExample 10 | { 11 | } 12 | -------------------------------------------------------------------------------- /src/main/java/com/wangwenjun/guava/collections/RangeExample.java: -------------------------------------------------------------------------------- 1 | package com.wangwenjun.guava.collections; 2 | 3 | /*************************************** 4 | * @author:Alex Wang 5 | * @Date:2018/1/14 6 | * QQ: 532500648 7 | * QQ群:463962286 8 | ***************************************/ 9 | public class RangeExample 10 | { 11 | 12 | } 13 | -------------------------------------------------------------------------------- /src/main/java/com/wangwenjun/guava/collections/SetsExample.java: -------------------------------------------------------------------------------- 1 | package com.wangwenjun.guava.collections; 2 | 3 | /*************************************** 4 | * @author:Alex Wang 5 | * @Date:2018/1/14 6 | * QQ: 532500648 7 | * QQ群:463962286 8 | ***************************************/ 9 | public class SetsExample 10 | { 11 | } 12 | -------------------------------------------------------------------------------- /src/main/java/com/wangwenjun/guava/collections/TableExample.java: -------------------------------------------------------------------------------- 1 | package com.wangwenjun.guava.collections; 2 | 3 | /*************************************** 4 | * @author:Alex Wang 5 | * @Date:2018/1/14 6 | * QQ: 532500648 7 | * QQ群:463962286 8 | ***************************************/ 9 | public class TableExample 10 | { 11 | } 12 | -------------------------------------------------------------------------------- /src/main/java/com/wangwenjun/guava/concurrent/Bucket.java: -------------------------------------------------------------------------------- 1 | package com.wangwenjun.guava.concurrent; 2 | 3 | import com.google.common.util.concurrent.Monitor; 4 | import com.google.common.util.concurrent.RateLimiter; 5 | 6 | import java.util.concurrent.ConcurrentLinkedQueue; 7 | import java.util.function.Consumer; 8 | 9 | import static java.lang.Thread.currentThread; 10 | 11 | /*************************************** 12 | * @author:Alex Wang 13 | * @Date:2017/11/8 14 | ***************************************/ 15 | public class Bucket 16 | { 17 | 18 | private final ConcurrentLinkedQueue container = new ConcurrentLinkedQueue<>(); 19 | 20 | private final static int BUCKET_LIMIT = 1000; 21 | 22 | private final RateLimiter limiter = RateLimiter.create(10); 23 | 24 | private final Monitor offerMonitor = new Monitor(); 25 | private final Monitor pollMonitor = new Monitor(); 26 | 27 | public void submit(Integer data) 28 | { 29 | if (offerMonitor.enterIf(offerMonitor.newGuard(() -> container.size() < BUCKET_LIMIT))) 30 | { 31 | try 32 | { 33 | container.offer(data); 34 | System.out.println(currentThread() + " submit data " + data + ",current size:" + container.size()); 35 | } finally 36 | { 37 | offerMonitor.leave(); 38 | } 39 | } else 40 | { 41 | throw new IllegalStateException("The bucket is full."); 42 | } 43 | } 44 | 45 | 46 | public void takeThenConsume(Consumer consumer) 47 | { 48 | if (pollMonitor.enterIf(pollMonitor.newGuard(() -> !container.isEmpty()))) 49 | { 50 | try 51 | { 52 | System.out.println(currentThread() + " waiting " + limiter.acquire()); 53 | consumer.accept(container.poll()); 54 | } finally 55 | { 56 | pollMonitor.leave(); 57 | } 58 | } 59 | } 60 | } 61 | -------------------------------------------------------------------------------- /src/main/java/com/wangwenjun/guava/concurrent/BucketTest.java: -------------------------------------------------------------------------------- 1 | package com.wangwenjun.guava.concurrent; 2 | 3 | import java.util.concurrent.TimeUnit; 4 | import java.util.concurrent.atomic.AtomicInteger; 5 | import java.util.stream.IntStream; 6 | 7 | import static java.lang.Thread.currentThread; 8 | 9 | /*************************************** 10 | * @author:Alex Wang 11 | * @Date:2017/11/8 12 | ***************************************/ 13 | public class BucketTest 14 | { 15 | 16 | public static void main(String[] args) 17 | { 18 | final Bucket bucket = new Bucket(); 19 | final AtomicInteger DATA_CREATOR = new AtomicInteger(0); 20 | 21 | IntStream.range(0, 5).forEach(i -> 22 | { 23 | new Thread(() -> 24 | { 25 | for (; ; ) 26 | { 27 | int data = DATA_CREATOR.getAndIncrement(); 28 | bucket.submit(data); 29 | try 30 | { 31 | TimeUnit.MILLISECONDS.sleep(200L); 32 | } catch (Exception e) 33 | { 34 | if (e instanceof IllegalStateException) 35 | { 36 | System.out.println(e.getMessage()); 37 | } 38 | } 39 | } //25 40 | 41 | //10 42 | 43 | //5:2 44 | }).start(); 45 | }); 46 | 47 | 48 | IntStream.range(0, 5) 49 | .forEach(i -> new Thread(() -> 50 | { 51 | for (; ; ) 52 | { 53 | bucket.takeThenConsume(x -> System.out.println(currentThread() + " W " + x)); 54 | } 55 | }).start() 56 | ); 57 | } 58 | } 59 | -------------------------------------------------------------------------------- /src/main/java/com/wangwenjun/guava/concurrent/ListenableFutureExample.java: -------------------------------------------------------------------------------- 1 | package com.wangwenjun.guava.concurrent; 2 | 3 | import com.google.common.util.concurrent.*; 4 | 5 | import javax.annotation.Nullable; 6 | import java.util.concurrent.*; 7 | 8 | /*************************************** 9 | * @author:Alex Wang 10 | * @Date:2017/11/12 11 | * QQ: 532500648 12 | * QQ群:463962286 13 | ***************************************/ 14 | public class ListenableFutureExample 15 | { 16 | public static void main(String[] args) throws ExecutionException, InterruptedException 17 | { 18 | ExecutorService service = Executors.newFixedThreadPool(2); 19 | 20 | /*Future future = service.submit(() -> 21 | { 22 | try 23 | { 24 | TimeUnit.SECONDS.sleep(5); 25 | } catch (InterruptedException e) 26 | { 27 | e.printStackTrace(); 28 | } 29 | 30 | return 10; 31 | }); 32 | 33 | Object result = future.get(); 34 | System.out.println(result);*/ 35 | 36 | /* ListeningExecutorService listeningExecutorService = MoreExecutors.listeningDecorator(service); 37 | ListenableFuture future = listeningExecutorService.submit(() -> 38 | { 39 | try 40 | { 41 | TimeUnit.SECONDS.sleep(5); 42 | } catch (InterruptedException e) 43 | { 44 | e.printStackTrace(); 45 | } 46 | 47 | return 100; 48 | }); 49 | 50 | // future.addListener(() -> System.out.println("I am finished"), service); 51 | 52 | Futures.addCallback(future, new MyCallBack(), service); 53 | System.out.println("=============");*/ 54 | 55 | CompletableFuture future = CompletableFuture.supplyAsync(() -> 56 | { 57 | try 58 | { 59 | TimeUnit.SECONDS.sleep(5); 60 | } catch (InterruptedException e) 61 | { 62 | e.printStackTrace(); 63 | } 64 | return 100; 65 | }, service).whenComplete((v, t) -> System.out.println("I am finished and the result is " + v)); 66 | } 67 | 68 | static class MyCallBack implements FutureCallback 69 | { 70 | 71 | @Override 72 | public void onSuccess(@Nullable Integer result) 73 | { 74 | System.out.println("I am finished and the result is " + result); 75 | } 76 | 77 | @Override 78 | public void onFailure(Throwable t) 79 | { 80 | t.printStackTrace(); 81 | } 82 | } 83 | } 84 | -------------------------------------------------------------------------------- /src/main/java/com/wangwenjun/guava/concurrent/MonitorExample.java: -------------------------------------------------------------------------------- 1 | package com.wangwenjun.guava.concurrent; 2 | 3 | import com.google.common.util.concurrent.Monitor; 4 | 5 | import java.util.LinkedList; 6 | import java.util.concurrent.TimeUnit; 7 | import java.util.concurrent.atomic.AtomicInteger; 8 | import java.util.concurrent.locks.Condition; 9 | import java.util.concurrent.locks.ReentrantLock; 10 | 11 | import static java.lang.Thread.currentThread; 12 | 13 | /*************************************** 14 | * @author:Alex Wang 15 | * @Date:2017/11/6 16 | * 532500648 17 | ***************************************/ 18 | public class MonitorExample 19 | { 20 | 21 | public static void main(String[] args) 22 | { 23 | final MonitorGuard mg = new MonitorGuard(); 24 | 25 | final AtomicInteger COUNTER = new AtomicInteger(0); 26 | 27 | for (int i = 0; i <= 3; i++) 28 | { 29 | new Thread(() -> 30 | { 31 | for (; ; ) 32 | try 33 | { 34 | int data = COUNTER.getAndIncrement(); 35 | System.out.println(currentThread() + " offer " + data); 36 | mg.offer(data); 37 | TimeUnit.MILLISECONDS.sleep(2); 38 | } catch (InterruptedException e) 39 | { 40 | e.printStackTrace(); 41 | } 42 | }).start(); 43 | } 44 | 45 | for (int i = 0; i <= 2; i++) 46 | { 47 | new Thread(() -> 48 | { 49 | for (; ; ) 50 | try 51 | { 52 | int data = mg.take(); 53 | System.out.println(currentThread() + " take " + data); 54 | TimeUnit.MILLISECONDS.sleep(1); 55 | } catch (InterruptedException e) 56 | { 57 | e.printStackTrace(); 58 | } 59 | }).start(); 60 | } 61 | } 62 | 63 | static class MonitorGuard 64 | { 65 | private final LinkedList queue = new LinkedList<>(); 66 | 67 | private final int MAX = 10; 68 | 69 | private final Monitor monitor = new Monitor(); 70 | 71 | private final Monitor.Guard CAN_OFFER = monitor.newGuard(() -> queue.size() < MAX); 72 | 73 | private final Monitor.Guard CAN_TAKE = monitor.newGuard(() -> !queue.isEmpty()); 74 | 75 | public void offer(int value) 76 | { 77 | try 78 | { 79 | monitor.enterWhen(CAN_OFFER); 80 | queue.addLast(value); 81 | } catch (InterruptedException e) 82 | { 83 | e.printStackTrace(); 84 | } finally 85 | { 86 | monitor.leave(); 87 | } 88 | } 89 | 90 | public int take() 91 | { 92 | try 93 | { 94 | monitor.enterWhen(CAN_TAKE); 95 | return queue.removeFirst(); 96 | } catch (InterruptedException e) 97 | { 98 | throw new RuntimeException(e); 99 | } finally 100 | { 101 | monitor.leave(); 102 | } 103 | } 104 | 105 | } 106 | 107 | static class LockCondition 108 | { 109 | private final ReentrantLock lock = new ReentrantLock(); 110 | 111 | private final Condition FULL_CONDITION = lock.newCondition(); 112 | 113 | private final Condition EMPTY_CONDITION = lock.newCondition(); 114 | 115 | private final LinkedList queue = new LinkedList<>(); 116 | 117 | private final int MAX = 10; 118 | 119 | public void offer(int value) 120 | { 121 | try 122 | { 123 | lock.lock(); 124 | while (queue.size() >= MAX) 125 | { 126 | FULL_CONDITION.await(); 127 | } 128 | 129 | queue.addLast(value); 130 | EMPTY_CONDITION.signalAll(); 131 | } catch (InterruptedException e) 132 | { 133 | e.printStackTrace(); 134 | } finally 135 | { 136 | lock.unlock(); 137 | } 138 | } 139 | 140 | public int take() 141 | { 142 | 143 | Integer value = null; 144 | try 145 | { 146 | lock.lock(); 147 | while (queue.isEmpty()) 148 | { 149 | EMPTY_CONDITION.await(); 150 | } 151 | 152 | value = queue.removeFirst(); 153 | FULL_CONDITION.signalAll(); 154 | } catch (InterruptedException e) 155 | { 156 | e.printStackTrace(); 157 | } finally 158 | { 159 | lock.unlock(); 160 | } 161 | 162 | return value; 163 | } 164 | } 165 | 166 | static class Synchronized 167 | { 168 | private final LinkedList queue = new LinkedList<>(); 169 | private final int MAX = 10; 170 | 171 | public void offer(int value) 172 | { 173 | synchronized (queue) 174 | { 175 | while (queue.size() >= MAX) 176 | { 177 | try 178 | { 179 | queue.wait(); 180 | } catch (InterruptedException e) 181 | { 182 | e.printStackTrace(); 183 | } 184 | } 185 | 186 | queue.addLast(value); 187 | queue.notifyAll(); 188 | } 189 | } 190 | 191 | public int take() 192 | { 193 | synchronized (queue) 194 | { 195 | while (queue.isEmpty()) 196 | { 197 | try 198 | { 199 | queue.wait(); 200 | } catch (InterruptedException e) 201 | { 202 | e.printStackTrace(); 203 | } 204 | } 205 | 206 | Integer value = queue.removeFirst(); 207 | queue.notifyAll(); 208 | return value; 209 | } 210 | } 211 | } 212 | } 213 | -------------------------------------------------------------------------------- /src/main/java/com/wangwenjun/guava/concurrent/RateLimiterExample.java: -------------------------------------------------------------------------------- 1 | package com.wangwenjun.guava.concurrent; 2 | 3 | import com.google.common.util.concurrent.RateLimiter; 4 | 5 | import java.util.concurrent.*; 6 | import java.util.stream.IntStream; 7 | 8 | import static java.lang.Thread.currentThread; 9 | 10 | /*************************************** 11 | * @author:Alex Wang 12 | * @Date:2017/11/8 13 | ***************************************/ 14 | public class RateLimiterExample 15 | { 16 | 17 | private final static RateLimiter limiter = RateLimiter.create(0.5d); 18 | 19 | private final static Semaphore semaphore = new Semaphore(3); 20 | 21 | public static void main(String[] args) 22 | { 23 | ExecutorService service = Executors.newFixedThreadPool(10); 24 | IntStream.range(0, 10).forEach(i -> 25 | service.submit(RateLimiterExample::testSemaphore) 26 | ); 27 | } 28 | 29 | private static void testLimiter() 30 | { 31 | System.out.println(currentThread() + " waiting " + limiter.acquire()); 32 | } 33 | 34 | private static void testSemaphore() 35 | { 36 | 37 | try 38 | { 39 | semaphore.acquire(); 40 | System.out.println(currentThread() + " is coming and do work."); 41 | TimeUnit.SECONDS.sleep(ThreadLocalRandom.current().nextInt(10)); 42 | } catch (InterruptedException e) 43 | { 44 | e.printStackTrace(); 45 | } finally 46 | { 47 | semaphore.release(); 48 | System.out.println(currentThread() + " release the semaphore."); 49 | } 50 | } 51 | } 52 | -------------------------------------------------------------------------------- /src/main/java/com/wangwenjun/guava/concurrent/TokenBucket.java: -------------------------------------------------------------------------------- 1 | package com.wangwenjun.guava.concurrent; 2 | 3 | import com.google.common.base.Stopwatch; 4 | import com.google.common.util.concurrent.RateLimiter; 5 | 6 | import java.util.concurrent.ThreadLocalRandom; 7 | import java.util.concurrent.TimeUnit; 8 | import java.util.concurrent.atomic.AtomicInteger; 9 | 10 | import static java.lang.Thread.currentThread; 11 | 12 | /*************************************** 13 | * @author:Alex Wang 14 | * @Date:2017/11/12 15 | * QQ: 532500648 16 | * QQ群:463962286 17 | ***************************************/ 18 | public class TokenBucket 19 | { 20 | 21 | private AtomicInteger phoneNumbers = new AtomicInteger(0); 22 | 23 | private final static int LIMIT = 100; 24 | 25 | private RateLimiter rateLimiter = RateLimiter.create(10); 26 | 27 | private final int saleLimit; 28 | 29 | public TokenBucket() 30 | { 31 | this(LIMIT); 32 | } 33 | 34 | public TokenBucket(int limit) 35 | { 36 | this.saleLimit = limit; 37 | } 38 | 39 | public int buy() 40 | { 41 | Stopwatch started = Stopwatch.createStarted(); 42 | boolean success = rateLimiter.tryAcquire(10, TimeUnit.SECONDS); 43 | if (success) 44 | { 45 | if (phoneNumbers.get() >= saleLimit) 46 | { 47 | throw new IllegalStateException("Not any phone can be sale, please wait to next time."); 48 | } 49 | int phoneNo = phoneNumbers.getAndIncrement(); 50 | handleOrder(); 51 | System.out.println(currentThread() + " user get the Mi phone: " + phoneNo + ",ELT:" + started.stop()); 52 | return phoneNo; 53 | } else 54 | { 55 | started.stop(); 56 | throw new RuntimeException("Sorry, occur exception when buy phone"); 57 | } 58 | } 59 | 60 | private void handleOrder() 61 | { 62 | try 63 | { 64 | TimeUnit.SECONDS.sleep(ThreadLocalRandom.current().nextInt(10)); 65 | } catch (InterruptedException e) 66 | { 67 | e.printStackTrace(); 68 | } 69 | } 70 | } 71 | -------------------------------------------------------------------------------- /src/main/java/com/wangwenjun/guava/concurrent/TokenBucketExample.java: -------------------------------------------------------------------------------- 1 | package com.wangwenjun.guava.concurrent; 2 | 3 | /*************************************** 4 | * @author:Alex Wang 5 | * @Date:2017/11/12 6 | * QQ: 532500648 7 | * QQ群:463962286 8 | ***************************************/ 9 | public class TokenBucketExample 10 | { 11 | 12 | public static void main(String[] args) 13 | { 14 | final TokenBucket tokenBucket = new TokenBucket(); 15 | for (int i = 0; i < 200; i++) 16 | { 17 | new Thread(tokenBucket::buy).start(); 18 | } 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /src/main/java/com/wangwenjun/guava/eventbus/AsyncEventBusExample.java: -------------------------------------------------------------------------------- 1 | package com.wangwenjun.guava.eventbus; 2 | 3 | import com.google.common.eventbus.AsyncEventBus; 4 | import com.wangwenjun.guava.eventbus.listeners.SimpleListener; 5 | 6 | import java.util.concurrent.Executor; 7 | import java.util.concurrent.Executors; 8 | 9 | /*************************************** 10 | * @author:Alex Wang 11 | * @Date:2017/10/21 12 | * 532500648 13 | ***************************************/ 14 | public class AsyncEventBusExample 15 | { 16 | public static void main(String[] args) 17 | { 18 | AsyncEventBus eventBus = new AsyncEventBus(new SeqExecutor()); 19 | eventBus.register(new SimpleListener()); 20 | eventBus.post("hello"); 21 | 22 | } 23 | 24 | static class SeqExecutor implements Executor 25 | { 26 | 27 | @Override 28 | public void execute(Runnable command) 29 | { 30 | command.run(); 31 | } 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /src/main/java/com/wangwenjun/guava/eventbus/ComEachOtherEventBusExample.java: -------------------------------------------------------------------------------- 1 | package com.wangwenjun.guava.eventbus; 2 | 3 | import com.google.common.eventbus.EventBus; 4 | import com.wangwenjun.guava.eventbus.service.QueryService; 5 | import com.wangwenjun.guava.eventbus.service.RequestQueryHandler; 6 | 7 | /*************************************** 8 | * @author:Alex Wang 9 | * @Date:2017/10/19 10 | * 532500648 11 | ***************************************/ 12 | public class ComEachOtherEventBusExample 13 | { 14 | 15 | public static void main(String[] args) 16 | { 17 | final EventBus eventBus = new EventBus(); 18 | QueryService queryService = new QueryService(eventBus); 19 | eventBus.register(new RequestQueryHandler(eventBus)); 20 | queryService.query("werwersdf"); 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /src/main/java/com/wangwenjun/guava/eventbus/DeadEventBusExample.java: -------------------------------------------------------------------------------- 1 | package com.wangwenjun.guava.eventbus; 2 | 3 | import com.google.common.eventbus.EventBus; 4 | import com.wangwenjun.guava.eventbus.listeners.DeadEventListener; 5 | 6 | /*************************************** 7 | * @author:Alex Wang 8 | * @Date:2017/10/19 9 | * 532500648 10 | ***************************************/ 11 | public class DeadEventBusExample 12 | { 13 | 14 | public static void main(String[] args) 15 | { 16 | 17 | final DeadEventListener deadEventListener = new DeadEventListener(); 18 | final EventBus eventBus = new EventBus("DeadEventBus") 19 | { 20 | @Override 21 | public String toString() 22 | { 23 | return "DEAD-EVENT-BUS"; 24 | } 25 | }; 26 | eventBus.register(deadEventListener); 27 | eventBus.post("Hello"); 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /src/main/java/com/wangwenjun/guava/eventbus/ExceptionEventBusExample.java: -------------------------------------------------------------------------------- 1 | package com.wangwenjun.guava.eventbus; 2 | 3 | import com.google.common.eventbus.EventBus; 4 | import com.wangwenjun.guava.eventbus.listeners.ExceptionListener; 5 | 6 | /*************************************** 7 | * @author:Alex Wang 8 | * @Date:2017/10/19 9 | * 532500648 10 | ***************************************/ 11 | public class ExceptionEventBusExample 12 | { 13 | public static void main(String[] args) 14 | { 15 | final EventBus eventBus = new EventBus((exception, context) -> 16 | { 17 | System.out.println(context.getEvent()); 18 | System.out.println(context.getEventBus()); 19 | System.out.println(context.getSubscriber()); 20 | System.out.println(context.getSubscriberMethod()); 21 | }); 22 | eventBus.register(new ExceptionListener()); 23 | 24 | eventBus.post("exception post"); 25 | } 26 | 27 | /* 28 | static class ExceptionHandler implements SubscriberExceptionHandler 29 | { 30 | 31 | @Override 32 | public void handleException(Throwable exception, SubscriberExceptionContext context) 33 | { 34 | System.out.println(context.getEvent()); 35 | System.out.println(context.getEventBus()); 36 | System.out.println(context.getSubscriber()); 37 | System.out.println(context.getSubscriberMethod()); 38 | } 39 | }*/ 40 | 41 | } 42 | -------------------------------------------------------------------------------- /src/main/java/com/wangwenjun/guava/eventbus/InheritEventsEventBusExample.java: -------------------------------------------------------------------------------- 1 | package com.wangwenjun.guava.eventbus; 2 | 3 | import com.google.common.eventbus.EventBus; 4 | import com.wangwenjun.guava.eventbus.events.Apple; 5 | import com.wangwenjun.guava.eventbus.events.Fruit; 6 | import com.wangwenjun.guava.eventbus.listeners.ConcreteListener; 7 | import com.wangwenjun.guava.eventbus.listeners.FruitEaterListener; 8 | 9 | /*************************************** 10 | * @author:Alex Wang 11 | * @Date:2017/10/18 12 | * 532500648 13 | ***************************************/ 14 | public class InheritEventsEventBusExample 15 | { 16 | public static void main(String[] args) 17 | { 18 | final EventBus eventBus = new EventBus(); 19 | eventBus.register(new FruitEaterListener()); 20 | eventBus.post(new Apple("apple")); 21 | System.out.println("============================"); 22 | eventBus.post(new Fruit("apple")); 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /src/main/java/com/wangwenjun/guava/eventbus/InheritListenersEventBusExample.java: -------------------------------------------------------------------------------- 1 | package com.wangwenjun.guava.eventbus; 2 | 3 | import com.google.common.eventbus.EventBus; 4 | import com.wangwenjun.guava.eventbus.listeners.ConcreteListener; 5 | import com.wangwenjun.guava.eventbus.listeners.MultipleEventListeners; 6 | 7 | /*************************************** 8 | * @author:Alex Wang 9 | * @Date:2017/10/18 10 | * 532500648 11 | ***************************************/ 12 | public class InheritListenersEventBusExample 13 | { 14 | public static void main(String[] args) 15 | { 16 | final EventBus eventBus = new EventBus(); 17 | eventBus.register(new ConcreteListener()); 18 | System.out.println("post the string event"); 19 | eventBus.post("I am string event"); 20 | System.out.println("post the int event"); 21 | eventBus.post(1000); 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /src/main/java/com/wangwenjun/guava/eventbus/MultipleEventBusExample.java: -------------------------------------------------------------------------------- 1 | package com.wangwenjun.guava.eventbus; 2 | 3 | import com.google.common.eventbus.EventBus; 4 | import com.wangwenjun.guava.eventbus.listeners.MultipleEventListeners; 5 | 6 | /*************************************** 7 | * @author:Alex Wang 8 | * @Date:2017/10/18 9 | * 532500648 10 | ***************************************/ 11 | public class MultipleEventBusExample 12 | { 13 | public static void main(String[] args) 14 | { 15 | final EventBus eventBus = new EventBus(); 16 | eventBus.register(new MultipleEventListeners()); 17 | System.out.println("post the string event"); 18 | eventBus.post("I am string event"); 19 | System.out.println("post the int event"); 20 | eventBus.post(1000); 21 | 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /src/main/java/com/wangwenjun/guava/eventbus/SimpleEventBusExample.java: -------------------------------------------------------------------------------- 1 | package com.wangwenjun.guava.eventbus; 2 | 3 | import com.google.common.eventbus.EventBus; 4 | import com.wangwenjun.guava.eventbus.listeners.SimpleListener; 5 | 6 | /*************************************** 7 | * @author:Alex Wang 8 | * @Date:2017/10/18 9 | * 532500648 10 | ***************************************/ 11 | public class SimpleEventBusExample 12 | { 13 | public static void main(String[] args) 14 | { 15 | final EventBus eventBus = new EventBus(); 16 | eventBus.register(new SimpleListener()); 17 | System.out.println("post the simple event."); 18 | eventBus.post("Simple Event"); 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /src/main/java/com/wangwenjun/guava/eventbus/events/Apple.java: -------------------------------------------------------------------------------- 1 | package com.wangwenjun.guava.eventbus.events; 2 | 3 | /*************************************** 4 | * @author:Alex Wang 5 | * @Date:2017/10/18 6 | * 532500648 7 | ***************************************/ 8 | public class Apple extends Fruit 9 | { 10 | public Apple(String name) 11 | { 12 | super(name); 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /src/main/java/com/wangwenjun/guava/eventbus/events/Fruit.java: -------------------------------------------------------------------------------- 1 | package com.wangwenjun.guava.eventbus.events; 2 | 3 | import com.google.common.base.MoreObjects; 4 | 5 | /*************************************** 6 | * @author:Alex Wang 7 | * @Date:2017/10/18 8 | * 532500648 9 | ***************************************/ 10 | public class Fruit 11 | { 12 | 13 | private final String name; 14 | 15 | public Fruit(String name) 16 | { 17 | this.name = name; 18 | } 19 | 20 | public String getName() 21 | { 22 | return name; 23 | } 24 | 25 | @Override 26 | public String toString() 27 | { 28 | return MoreObjects.toStringHelper(this).add("Name", name).toString(); 29 | } 30 | } -------------------------------------------------------------------------------- /src/main/java/com/wangwenjun/guava/eventbus/events/Request.java: -------------------------------------------------------------------------------- 1 | package com.wangwenjun.guava.eventbus.events; 2 | 3 | /*************************************** 4 | * @author:Alex Wang 5 | * @Date:2017/10/19 6 | * 532500648 7 | ***************************************/ 8 | public class Request 9 | { 10 | 11 | private final String orderNo; 12 | 13 | public Request(String orderNo) 14 | { 15 | this.orderNo = orderNo; 16 | } 17 | 18 | @Override 19 | public String toString() 20 | { 21 | return "Request{" + 22 | "orderNo='" + orderNo + '\'' + 23 | '}'; 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /src/main/java/com/wangwenjun/guava/eventbus/events/Response.java: -------------------------------------------------------------------------------- 1 | package com.wangwenjun.guava.eventbus.events; 2 | 3 | /*************************************** 4 | * @author:Alex Wang 5 | * @Date:2017/10/19 6 | * 532500648 7 | ***************************************/ 8 | public class Response 9 | { 10 | } 11 | -------------------------------------------------------------------------------- /src/main/java/com/wangwenjun/guava/eventbus/internal/Bus.java: -------------------------------------------------------------------------------- 1 | package com.wangwenjun.guava.eventbus.internal; 2 | 3 | /*************************************** 4 | * @author:Alex Wang 5 | * @Date:2017/10/21 6 | * 532500648 7 | ***************************************/ 8 | public interface Bus 9 | { 10 | 11 | void register(Object subscriber); 12 | 13 | void unregister(Object subscriber); 14 | 15 | void post(Object event); 16 | 17 | void post(Object Event, String topic); 18 | 19 | void close(); 20 | 21 | String getBusName(); 22 | } 23 | -------------------------------------------------------------------------------- /src/main/java/com/wangwenjun/guava/eventbus/internal/MyAsyncEventBus.java: -------------------------------------------------------------------------------- 1 | package com.wangwenjun.guava.eventbus.internal; 2 | 3 | import java.util.concurrent.ThreadPoolExecutor; 4 | 5 | /*************************************** 6 | * @author:Alex Wang 7 | * @Date:2017/10/21 8 | * 532500648 9 | ***************************************/ 10 | public class MyAsyncEventBus extends MyEventBus 11 | { 12 | 13 | public MyAsyncEventBus(String busName, MyEventExceptionHandler exceptionHandler, ThreadPoolExecutor executor) 14 | { 15 | super(busName, exceptionHandler, executor); 16 | } 17 | 18 | 19 | public MyAsyncEventBus(String busName, ThreadPoolExecutor executor) 20 | { 21 | this(busName, null, executor); 22 | } 23 | 24 | public MyAsyncEventBus(ThreadPoolExecutor executor) 25 | { 26 | this("default-async", null, executor); 27 | } 28 | 29 | public MyAsyncEventBus(MyEventExceptionHandler exceptionHandler, ThreadPoolExecutor executor) 30 | { 31 | this("default-async", exceptionHandler, executor); 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /src/main/java/com/wangwenjun/guava/eventbus/internal/MyDispatcher.java: -------------------------------------------------------------------------------- 1 | package com.wangwenjun.guava.eventbus.internal; 2 | 3 | import java.lang.reflect.Method; 4 | import java.util.concurrent.ConcurrentLinkedQueue; 5 | import java.util.concurrent.Executor; 6 | import java.util.concurrent.ExecutorService; 7 | 8 | /*************************************** 9 | * @author:Alex Wang 10 | * @Date:2017/10/21 11 | * 532500648 12 | ***************************************/ 13 | public class MyDispatcher 14 | { 15 | 16 | private final Executor executorService; 17 | 18 | private final MyEventExceptionHandler exceptionHandler; 19 | 20 | public static final Executor SEQ_EXECUTOR_SERVICE = SeqExecutorService.INSTANCE; 21 | 22 | public static final Executor PRE_THREAD_EXECUTOR_SERVICE = PreThreadExecutorService.INSTANCE; 23 | 24 | private MyDispatcher(Executor executorService, MyEventExceptionHandler exceptionHandler) 25 | { 26 | this.executorService = executorService; 27 | this.exceptionHandler = exceptionHandler; 28 | } 29 | 30 | 31 | public void dispatch(Bus bus, MyRegistry registry, Object event, String topic) 32 | { 33 | ConcurrentLinkedQueue subscribers = registry.scanSubscriber(topic); 34 | if (null == subscribers) 35 | { 36 | if (exceptionHandler != null) 37 | { 38 | exceptionHandler.handle(new IllegalArgumentException("The topic " + topic + " not bind yet"), 39 | new BaseMyEventContext(bus.getBusName(), null, event)); 40 | } 41 | 42 | return; 43 | } 44 | 45 | subscribers.stream().filter(subscriber -> !subscriber.isDisable()) 46 | .filter(subscriber -> 47 | { 48 | Method subscribeMethod = subscriber.getSubscribeMethod(); 49 | Class aClass = subscribeMethod.getParameterTypes()[0]; 50 | return (aClass.isAssignableFrom(event.getClass())); 51 | }).forEach(subscriber -> realInvokeSubscribe(subscriber, event, bus)); 52 | } 53 | 54 | private void realInvokeSubscribe(MySubscriber subscriber, Object event, Bus bus) 55 | { 56 | Method subscribeMethod = subscriber.getSubscribeMethod(); 57 | Object subscribeObject = subscriber.getSubscribeObject(); 58 | executorService.execute(() -> 59 | { 60 | try 61 | { 62 | subscribeMethod.invoke(subscribeObject, event); 63 | } catch (Exception e) 64 | { 65 | if (null != exceptionHandler) 66 | { 67 | exceptionHandler.handle(e, new BaseMyEventContext(bus.getBusName(), subscriber, event)); 68 | } 69 | } 70 | }); 71 | } 72 | 73 | public void close() 74 | { 75 | if (executorService instanceof ExecutorService) 76 | ((ExecutorService) executorService).shutdown(); 77 | } 78 | 79 | static MyDispatcher newDispatcher(MyEventExceptionHandler exceptionHandler, Executor executor) 80 | { 81 | return new MyDispatcher(executor, exceptionHandler); 82 | } 83 | 84 | static MyDispatcher seqDispatcher(MyEventExceptionHandler exceptionHandler) 85 | { 86 | return new MyDispatcher(SEQ_EXECUTOR_SERVICE, exceptionHandler); 87 | } 88 | 89 | static MyDispatcher perThreaDDispatcher(MyEventExceptionHandler exceptionHandler) 90 | { 91 | return new MyDispatcher(PRE_THREAD_EXECUTOR_SERVICE, exceptionHandler); 92 | } 93 | 94 | private static class SeqExecutorService implements Executor 95 | { 96 | 97 | private final static SeqExecutorService INSTANCE = new SeqExecutorService(); 98 | 99 | @Override 100 | public void execute(Runnable command) 101 | { 102 | command.run(); 103 | } 104 | } 105 | 106 | 107 | private static class PreThreadExecutorService implements Executor 108 | { 109 | 110 | private final static PreThreadExecutorService INSTANCE = new PreThreadExecutorService(); 111 | 112 | @Override 113 | public void execute(Runnable command) 114 | { 115 | new Thread(command).start(); 116 | } 117 | } 118 | 119 | private static class BaseMyEventContext implements MyEventContext 120 | { 121 | 122 | private final String eventBusName; 123 | 124 | private final MySubscriber subscriber; 125 | 126 | private final Object event; 127 | 128 | private BaseMyEventContext(String eventBusName, MySubscriber subscriber, Object event) 129 | { 130 | this.eventBusName = eventBusName; 131 | this.subscriber = subscriber; 132 | this.event = event; 133 | } 134 | 135 | @Override 136 | public String getSource() 137 | { 138 | return this.eventBusName; 139 | } 140 | 141 | @Override 142 | public Object getSubscriber() 143 | { 144 | return subscriber != null ? subscriber.getSubscribeObject() : null; 145 | } 146 | 147 | @Override 148 | public Method getSubscribe() 149 | { 150 | return subscriber != null ? subscriber.getSubscribeMethod() : null; 151 | } 152 | 153 | @Override 154 | public Object getEvent() 155 | { 156 | return this.event; 157 | } 158 | } 159 | } 160 | -------------------------------------------------------------------------------- /src/main/java/com/wangwenjun/guava/eventbus/internal/MyEventBus.java: -------------------------------------------------------------------------------- 1 | package com.wangwenjun.guava.eventbus.internal; 2 | 3 | import java.util.concurrent.Executor; 4 | 5 | /*************************************** 6 | * @author:Alex Wang 7 | * @Date:2017/10/21 8 | * 532500648 9 | ***************************************/ 10 | public class MyEventBus implements Bus 11 | { 12 | 13 | private final MyRegistry registry = new MyRegistry(); 14 | 15 | private String busName; 16 | 17 | private final static String DEFAULT_BUS_NAME = "default"; 18 | 19 | private final static String DEFAULT_TOPIC = "default-topic"; 20 | 21 | // private final MyEventExceptionHandler exceptionHandler; 22 | 23 | private final MyDispatcher dispatcher; 24 | 25 | public MyEventBus() 26 | { 27 | this(DEFAULT_BUS_NAME, null, MyDispatcher.SEQ_EXECUTOR_SERVICE); 28 | } 29 | 30 | public MyEventBus(String busName) 31 | { 32 | this(busName, null, MyDispatcher.SEQ_EXECUTOR_SERVICE); 33 | } 34 | 35 | MyEventBus(String busName, MyEventExceptionHandler exceptionHandler, Executor executor) 36 | { 37 | this.busName = busName; 38 | this.dispatcher = MyDispatcher.newDispatcher(exceptionHandler, executor); 39 | } 40 | 41 | public MyEventBus(MyEventExceptionHandler exceptionHandler) 42 | { 43 | this(DEFAULT_BUS_NAME, exceptionHandler, MyDispatcher.SEQ_EXECUTOR_SERVICE); 44 | } 45 | 46 | @Override 47 | public void register(Object subscriber) 48 | { 49 | this.registry.bind(subscriber); 50 | } 51 | 52 | @Override 53 | public void unregister(Object subscriber) 54 | { 55 | this.registry.unbind(subscriber); 56 | } 57 | 58 | @Override 59 | public void post(Object event) 60 | { 61 | this.post(event, DEFAULT_TOPIC); 62 | } 63 | 64 | @Override 65 | public void post(Object event, String topic) 66 | { 67 | this.dispatcher.dispatch(this, registry, event, topic); 68 | } 69 | 70 | @Override 71 | public void close() 72 | { 73 | this.dispatcher.close(); 74 | } 75 | 76 | @Override 77 | public String getBusName() 78 | { 79 | return this.busName; 80 | } 81 | } 82 | -------------------------------------------------------------------------------- /src/main/java/com/wangwenjun/guava/eventbus/internal/MyEventContext.java: -------------------------------------------------------------------------------- 1 | package com.wangwenjun.guava.eventbus.internal; 2 | 3 | import java.lang.reflect.Method; 4 | 5 | /*************************************** 6 | * @author:Alex Wang 7 | * @Date:2017/10/21 8 | * 532500648 9 | ***************************************/ 10 | public interface MyEventContext 11 | { 12 | 13 | String getSource(); 14 | 15 | Object getSubscriber(); 16 | 17 | Method getSubscribe(); 18 | 19 | Object getEvent(); 20 | } 21 | -------------------------------------------------------------------------------- /src/main/java/com/wangwenjun/guava/eventbus/internal/MyEventExceptionHandler.java: -------------------------------------------------------------------------------- 1 | package com.wangwenjun.guava.eventbus.internal; 2 | 3 | /*************************************** 4 | * @author:Alex Wang 5 | * @Date:2017/10/21 6 | * 532500648 7 | ***************************************/ 8 | public interface MyEventExceptionHandler 9 | { 10 | void handle(Throwable cause, MyEventContext context); 11 | } 12 | -------------------------------------------------------------------------------- /src/main/java/com/wangwenjun/guava/eventbus/internal/MyRegistry.java: -------------------------------------------------------------------------------- 1 | package com.wangwenjun.guava.eventbus.internal; 2 | 3 | /*************************************** 4 | * @author:Alex Wang 5 | * @Date:2017/10/21 6 | * 532500648 7 | ***************************************/ 8 | 9 | import java.lang.reflect.Method; 10 | import java.lang.reflect.Modifier; 11 | import java.util.ArrayList; 12 | import java.util.Arrays; 13 | import java.util.List; 14 | import java.util.concurrent.ConcurrentHashMap; 15 | import java.util.concurrent.ConcurrentLinkedDeque; 16 | import java.util.concurrent.ConcurrentLinkedQueue; 17 | 18 | /** 19 | *
20 |  * topic1->subscriber-subscribe
21 |  *       ->subscriber-subscribe
22 |  *       ->subscriber-subscribe
23 |  * topic2->subscriber-subscribe
24 |  *       ->subscriber-subscribe
25 |  *       ->subscriber-subscribe
26 |  *
27 |  * 
28 | */ 29 | class MyRegistry 30 | { 31 | 32 | private final ConcurrentHashMap> subscriberContainer 33 | = new ConcurrentHashMap<>(); 34 | 35 | public void bind(Object subscriber) 36 | { 37 | List subscribeMethods = getSubscribeMethods(subscriber); 38 | subscribeMethods.forEach(m -> tierSubscriber(subscriber, m)); 39 | } 40 | 41 | 42 | public void unbind(Object subscriber) 43 | { 44 | 45 | subscriberContainer.forEach((key, queue) -> 46 | queue.forEach(s -> 47 | { 48 | if (s.getSubscribeObject() == subscriber) 49 | { 50 | s.setDisable(true); 51 | } 52 | })); 53 | } 54 | 55 | public ConcurrentLinkedQueue scanSubscriber(final String topic) 56 | { 57 | return subscriberContainer.get(topic); 58 | } 59 | 60 | private void tierSubscriber(Object subscriber, Method method) 61 | { 62 | final MySubscribe mySubscribe = method.getDeclaredAnnotation(MySubscribe.class); 63 | String topic = mySubscribe.topic(); 64 | subscriberContainer.computeIfAbsent(topic, key -> new ConcurrentLinkedQueue<>()); 65 | subscriberContainer.get(topic).add(new MySubscriber(subscriber, method)); 66 | 67 | } 68 | 69 | private List getSubscribeMethods(Object subscriber) 70 | { 71 | final List methods = new ArrayList<>(); 72 | Class temp = subscriber.getClass(); 73 | while (temp != null) 74 | { 75 | Method[] declaredMethods = temp.getDeclaredMethods(); 76 | Arrays.stream(declaredMethods) 77 | .filter(m -> m.isAnnotationPresent(MySubscribe.class) && m.getParameterCount() == 1 && m.getModifiers() == Modifier.PUBLIC) 78 | .forEach(methods::add); 79 | temp = temp.getSuperclass(); 80 | } 81 | return methods; 82 | } 83 | } 84 | -------------------------------------------------------------------------------- /src/main/java/com/wangwenjun/guava/eventbus/internal/MySubscribe.java: -------------------------------------------------------------------------------- 1 | package com.wangwenjun.guava.eventbus.internal; 2 | 3 | import java.lang.annotation.ElementType; 4 | import java.lang.annotation.Retention; 5 | import java.lang.annotation.RetentionPolicy; 6 | import java.lang.annotation.Target; 7 | 8 | /*************************************** 9 | * @author:Alex Wang 10 | * @Date:2017/10/21 11 | * 532500648 12 | ***************************************/ 13 | @Retention(RetentionPolicy.RUNTIME) 14 | @Target(ElementType.METHOD) 15 | public @interface MySubscribe 16 | { 17 | String topic() default "default-topic"; 18 | } 19 | -------------------------------------------------------------------------------- /src/main/java/com/wangwenjun/guava/eventbus/internal/MySubscriber.java: -------------------------------------------------------------------------------- 1 | package com.wangwenjun.guava.eventbus.internal; 2 | 3 | import java.lang.reflect.Method; 4 | 5 | /*************************************** 6 | * @author:Alex Wang 7 | * @Date:2017/10/21 8 | * 532500648 9 | ***************************************/ 10 | public class MySubscriber 11 | { 12 | 13 | private final Object subscribeObject; 14 | 15 | private final Method subscribeMethod; 16 | 17 | private boolean disable = false; 18 | 19 | public MySubscriber(Object subscribeObject, Method subscribeMethod) 20 | { 21 | this.subscribeObject = subscribeObject; 22 | this.subscribeMethod = subscribeMethod; 23 | } 24 | 25 | public Object getSubscribeObject() 26 | { 27 | return subscribeObject; 28 | } 29 | 30 | public Method getSubscribeMethod() 31 | { 32 | return subscribeMethod; 33 | } 34 | 35 | public boolean isDisable() 36 | { 37 | return disable; 38 | } 39 | 40 | public void setDisable(boolean disable) 41 | { 42 | this.disable = disable; 43 | } 44 | } 45 | -------------------------------------------------------------------------------- /src/main/java/com/wangwenjun/guava/eventbus/listeners/AbstractListener.java: -------------------------------------------------------------------------------- 1 | package com.wangwenjun.guava.eventbus.listeners; 2 | 3 | import com.google.common.eventbus.Subscribe; 4 | import org.slf4j.Logger; 5 | import org.slf4j.LoggerFactory; 6 | 7 | /*************************************** 8 | * @author:Alex Wang 9 | * @Date:2017/10/18 10 | * 532500648 11 | ***************************************/ 12 | public abstract class AbstractListener 13 | { 14 | 15 | private final static Logger LOGGER = LoggerFactory.getLogger(AbstractListener.class); 16 | 17 | @Subscribe 18 | public void commonTask(String event) 19 | { 20 | if (LOGGER.isInfoEnabled()) 21 | { 22 | LOGGER.info("The event [{}] will be handle by {}.{}", event, this.getClass().getSimpleName(), "commonTask"); 23 | } 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /src/main/java/com/wangwenjun/guava/eventbus/listeners/BaseListener.java: -------------------------------------------------------------------------------- 1 | package com.wangwenjun.guava.eventbus.listeners; 2 | 3 | import com.google.common.eventbus.Subscribe; 4 | import org.slf4j.Logger; 5 | import org.slf4j.LoggerFactory; 6 | 7 | /*************************************** 8 | * @author:Alex Wang 9 | * @Date:2017/10/18 10 | * 532500648 11 | ***************************************/ 12 | public class BaseListener extends AbstractListener 13 | { 14 | private final static Logger LOGGER = LoggerFactory.getLogger(BaseListener.class); 15 | 16 | @Subscribe 17 | public void baseTask(String event) 18 | { 19 | if (LOGGER.isInfoEnabled()) 20 | { 21 | LOGGER.info("The event [{}] will be handle by {}.{}", event, this.getClass().getSimpleName(), "baseTask"); 22 | } 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /src/main/java/com/wangwenjun/guava/eventbus/listeners/ConcreteListener.java: -------------------------------------------------------------------------------- 1 | package com.wangwenjun.guava.eventbus.listeners; 2 | 3 | import com.google.common.eventbus.Subscribe; 4 | import org.slf4j.Logger; 5 | import org.slf4j.LoggerFactory; 6 | 7 | /*************************************** 8 | * @author:Alex Wang 9 | * @Date:2017/10/18 10 | * 532500648 11 | ***************************************/ 12 | public class ConcreteListener extends BaseListener 13 | { 14 | private final static Logger LOGGER = LoggerFactory.getLogger(ConcreteListener.class); 15 | 16 | @Subscribe 17 | public void conTask(String event) 18 | { 19 | if (LOGGER.isInfoEnabled()) 20 | { 21 | LOGGER.info("The event [{}] will be handle by {}.{}", event, this.getClass().getSimpleName(), "conTask"); 22 | } 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /src/main/java/com/wangwenjun/guava/eventbus/listeners/DeadEventListener.java: -------------------------------------------------------------------------------- 1 | package com.wangwenjun.guava.eventbus.listeners; 2 | 3 | import com.google.common.eventbus.DeadEvent; 4 | import com.google.common.eventbus.Subscribe; 5 | 6 | /*************************************** 7 | * @author:Alex Wang 8 | * @Date:2017/10/19 9 | * 532500648 10 | ***************************************/ 11 | public class DeadEventListener 12 | { 13 | @Subscribe 14 | public void handle(DeadEvent event) 15 | { 16 | System.out.println(event.getSource()); 17 | System.out.println(event.getEvent()); 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /src/main/java/com/wangwenjun/guava/eventbus/listeners/ExceptionListener.java: -------------------------------------------------------------------------------- 1 | package com.wangwenjun.guava.eventbus.listeners; 2 | 3 | import com.google.common.eventbus.Subscribe; 4 | import org.slf4j.Logger; 5 | import org.slf4j.LoggerFactory; 6 | 7 | /*************************************** 8 | * @author:Alex Wang 9 | * @Date:2017/10/19 10 | * 532500648 11 | ***************************************/ 12 | public class ExceptionListener 13 | { 14 | 15 | private final static Logger LOGGER = LoggerFactory.getLogger(ExceptionListener.class); 16 | 17 | @Subscribe 18 | public void m1(String event) 19 | { 20 | LOGGER.info("============m1======={}", event); 21 | } 22 | 23 | 24 | @Subscribe 25 | public void m2(String event) 26 | { 27 | LOGGER.info("============m2======={}", event); 28 | } 29 | 30 | 31 | @Subscribe 32 | public void m3(String event) 33 | { 34 | LOGGER.info("============m3======={}", event); 35 | throw new RuntimeException(); 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /src/main/java/com/wangwenjun/guava/eventbus/listeners/FruitEaterListener.java: -------------------------------------------------------------------------------- 1 | package com.wangwenjun.guava.eventbus.listeners; 2 | 3 | import com.google.common.eventbus.Subscribe; 4 | import com.wangwenjun.guava.eventbus.events.Apple; 5 | import com.wangwenjun.guava.eventbus.events.Fruit; 6 | import org.slf4j.Logger; 7 | import org.slf4j.LoggerFactory; 8 | 9 | /*************************************** 10 | * @author:Alex Wang 11 | * @Date:2017/10/18 12 | * 532500648 13 | ***************************************/ 14 | public class FruitEaterListener 15 | { 16 | 17 | private final static Logger LOGGER = LoggerFactory.getLogger(FruitEaterListener.class); 18 | 19 | @Subscribe 20 | public void eat(Fruit event) 21 | { 22 | if (LOGGER.isInfoEnabled()) 23 | { 24 | LOGGER.info("Fruit eat [{}].", event); 25 | } 26 | } 27 | 28 | @Subscribe 29 | public void eat(Apple event) 30 | { 31 | if (LOGGER.isInfoEnabled()) 32 | { 33 | LOGGER.info("Apple eat [{}].", event); 34 | } 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /src/main/java/com/wangwenjun/guava/eventbus/listeners/MultipleEventListeners.java: -------------------------------------------------------------------------------- 1 | package com.wangwenjun.guava.eventbus.listeners; 2 | 3 | import com.google.common.eventbus.Subscribe; 4 | import org.slf4j.Logger; 5 | import org.slf4j.LoggerFactory; 6 | 7 | /*************************************** 8 | * @author:Alex Wang 9 | * @Date:2017/10/18 10 | * 532500648 11 | ***************************************/ 12 | public class MultipleEventListeners 13 | { 14 | 15 | private final static Logger LOGGER = LoggerFactory.getLogger(MultipleEventListeners.class); 16 | 17 | @Subscribe 18 | public void task1(String event) 19 | { 20 | if (LOGGER.isInfoEnabled()) 21 | { 22 | LOGGER.info("the event [{}] received and will take a action by ==task1== ", event); 23 | } 24 | } 25 | 26 | @Subscribe 27 | public void task2(String event) 28 | { 29 | if (LOGGER.isInfoEnabled()) 30 | { 31 | LOGGER.info("the event [{}] received and will take a action by ==task2== ", event); 32 | } 33 | } 34 | 35 | @Subscribe 36 | public void intTask(Integer event) 37 | { 38 | if (LOGGER.isInfoEnabled()) 39 | { 40 | LOGGER.info("the event [{}] received and will take a action by ==intTask== ", event); 41 | } 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /src/main/java/com/wangwenjun/guava/eventbus/listeners/SimpleListener.java: -------------------------------------------------------------------------------- 1 | package com.wangwenjun.guava.eventbus.listeners; 2 | 3 | import com.google.common.eventbus.Subscribe; 4 | import org.slf4j.Logger; 5 | import org.slf4j.LoggerFactory; 6 | 7 | import java.util.concurrent.TimeUnit; 8 | 9 | /*************************************** 10 | * @author:Alex Wang 11 | * @Date:2017/10/18 12 | * 532500648 13 | ***************************************/ 14 | public class SimpleListener 15 | { 16 | private final static Logger LOGGER = LoggerFactory.getLogger(SimpleListener.class); 17 | 18 | @Subscribe 19 | public void doAction(final String event) 20 | { 21 | if (LOGGER.isInfoEnabled()) 22 | { 23 | LOGGER.info("Received event [{}] and will take a action", event); 24 | } 25 | } 26 | 27 | @Subscribe 28 | public void doAction1(final String event) 29 | { 30 | 31 | try 32 | { 33 | TimeUnit.MINUTES.sleep(10); 34 | } catch (InterruptedException e) 35 | { 36 | e.printStackTrace(); 37 | } 38 | if (LOGGER.isInfoEnabled()) 39 | { 40 | LOGGER.info("Received event [{}] and will take a action1", event); 41 | } 42 | } 43 | 44 | @Subscribe 45 | public void doAction2(final String event) 46 | { 47 | if (LOGGER.isInfoEnabled()) 48 | { 49 | LOGGER.info("Received event [{}] and will take a action2", event); 50 | } 51 | } 52 | 53 | @Subscribe 54 | public void doAction3(final String event) 55 | { 56 | if (LOGGER.isInfoEnabled()) 57 | { 58 | LOGGER.info("Received event [{}] and will take a action2", event); 59 | } 60 | } 61 | 62 | @Subscribe 63 | public void doAction4(final String event) 64 | { 65 | if (LOGGER.isInfoEnabled()) 66 | { 67 | LOGGER.info("Received event [{}] and will take a action2", event); 68 | } 69 | } 70 | } 71 | -------------------------------------------------------------------------------- /src/main/java/com/wangwenjun/guava/eventbus/monitor/DirectoryTargetMonitor.java: -------------------------------------------------------------------------------- 1 | package com.wangwenjun.guava.eventbus.monitor; 2 | 3 | import com.google.common.eventbus.EventBus; 4 | import org.slf4j.Logger; 5 | import org.slf4j.LoggerFactory; 6 | 7 | import java.nio.file.*; 8 | 9 | /*************************************** 10 | * @author:Alex Wang 11 | * @Date:2017/10/19 12 | * 532500648 13 | ***************************************/ 14 | public class DirectoryTargetMonitor implements TargetMonitor 15 | { 16 | 17 | private final static Logger LOGGER = LoggerFactory.getLogger(DirectoryTargetMonitor.class); 18 | 19 | private WatchService watchService; 20 | 21 | private final EventBus eventBus; 22 | 23 | private final Path path; 24 | 25 | private volatile boolean start = false; 26 | 27 | public DirectoryTargetMonitor(final EventBus eventBus, final String targetPath) 28 | { 29 | this(eventBus, targetPath, ""); 30 | } 31 | 32 | public DirectoryTargetMonitor(final EventBus eventBus, final String targetPath, final String... morePaths) 33 | { 34 | this.eventBus = eventBus; 35 | this.path = Paths.get(targetPath, morePaths); 36 | } 37 | 38 | 39 | @Override 40 | public void startMonitor() throws Exception 41 | { 42 | this.watchService = FileSystems.getDefault().newWatchService(); 43 | this.path.register(watchService, StandardWatchEventKinds.ENTRY_MODIFY, 44 | StandardWatchEventKinds.ENTRY_DELETE, StandardWatchEventKinds.ENTRY_CREATE); 45 | LOGGER.info("The directory [{}] is monitoring... ", path); 46 | 47 | this.start = true; 48 | while (start) 49 | { 50 | WatchKey watchKey = null; 51 | try 52 | { 53 | watchKey = watchService.take(); 54 | watchKey.pollEvents().forEach(event -> 55 | { 56 | WatchEvent.Kind kind = event.kind(); 57 | Path path = (Path) event.context(); 58 | Path child = DirectoryTargetMonitor.this.path.resolve(path); 59 | eventBus.post(new FileChangeEvent(child, kind)); 60 | }); 61 | } catch (Exception e) 62 | { 63 | this.start = false; 64 | } finally 65 | { 66 | if (watchKey != null) 67 | watchKey.reset(); 68 | } 69 | } 70 | } 71 | 72 | @Override 73 | public void stopMonitor() throws Exception 74 | { 75 | LOGGER.info("The directory [{}] monitor will be stop...", path); 76 | Thread.currentThread().interrupt(); 77 | this.start = false; 78 | this.watchService.close(); 79 | LOGGER.info("The directory [{}] monitor will be stop done.", path); 80 | } 81 | } 82 | -------------------------------------------------------------------------------- /src/main/java/com/wangwenjun/guava/eventbus/monitor/FileChangeEvent.java: -------------------------------------------------------------------------------- 1 | package com.wangwenjun.guava.eventbus.monitor; 2 | 3 | import java.nio.file.Path; 4 | import java.nio.file.WatchEvent; 5 | 6 | /*************************************** 7 | * @author:Alex Wang 8 | * @Date:2017/10/19 9 | * 532500648 10 | ***************************************/ 11 | public class FileChangeEvent 12 | { 13 | 14 | private final Path path; 15 | 16 | private final WatchEvent.Kind kind; 17 | 18 | public FileChangeEvent(Path path, WatchEvent.Kind kind) 19 | { 20 | this.path = path; 21 | this.kind = kind; 22 | } 23 | 24 | public Path getPath() 25 | { 26 | return path; 27 | } 28 | 29 | public WatchEvent.Kind getKind() 30 | { 31 | return kind; 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /src/main/java/com/wangwenjun/guava/eventbus/monitor/FileChangeListener.java: -------------------------------------------------------------------------------- 1 | package com.wangwenjun.guava.eventbus.monitor; 2 | 3 | import com.google.common.eventbus.Subscribe; 4 | import org.slf4j.Logger; 5 | import org.slf4j.LoggerFactory; 6 | 7 | /*************************************** 8 | * @author:Alex Wang 9 | * @Date:2017/10/19 10 | * 532500648 11 | ***************************************/ 12 | public class FileChangeListener 13 | { 14 | 15 | private final static Logger LOGGER = LoggerFactory.getLogger(FileChangeListener.class); 16 | 17 | @Subscribe 18 | public void onChange(FileChangeEvent event) 19 | { 20 | LOGGER.info("{}-{}", event.getPath(), event.getKind()); 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /src/main/java/com/wangwenjun/guava/eventbus/monitor/MonitorClient.java: -------------------------------------------------------------------------------- 1 | package com.wangwenjun.guava.eventbus.monitor; 2 | 3 | import com.google.common.eventbus.EventBus; 4 | 5 | import java.util.concurrent.Executors; 6 | import java.util.concurrent.ScheduledExecutorService; 7 | import java.util.concurrent.TimeUnit; 8 | 9 | /*************************************** 10 | * @author:Alex Wang 11 | * @Date:2017/10/19 12 | * 532500648 13 | ***************************************/ 14 | 15 | /** 16 | * tail 17 | * Apache Flume 1.7 Spooling 18 | *

19 | * .position 20 | */ 21 | public class MonitorClient 22 | { 23 | public static void main(String[] args) throws Exception 24 | { 25 | final EventBus eventBus = new EventBus(); 26 | eventBus.register(new FileChangeListener()); 27 | 28 | TargetMonitor monitor = new DirectoryTargetMonitor(eventBus, "G:\\Teaching\\汪文君Google Guava实战视频\\monitor"); 29 | ScheduledExecutorService executorService = Executors.newSingleThreadScheduledExecutor(); 30 | executorService.schedule(() -> 31 | { 32 | try 33 | { 34 | monitor.stopMonitor(); 35 | } catch (Exception e) 36 | { 37 | e.printStackTrace(); 38 | } 39 | }, 2, TimeUnit.SECONDS); 40 | executorService.shutdown(); 41 | monitor.startMonitor(); 42 | 43 | } 44 | } 45 | 46 | -------------------------------------------------------------------------------- /src/main/java/com/wangwenjun/guava/eventbus/monitor/TargetMonitor.java: -------------------------------------------------------------------------------- 1 | package com.wangwenjun.guava.eventbus.monitor; 2 | 3 | /*************************************** 4 | * @author:Alex Wang 5 | * @Date:2017/10/19 6 | * 532500648 7 | ***************************************/ 8 | public interface TargetMonitor 9 | { 10 | 11 | void startMonitor() throws Exception; 12 | 13 | void stopMonitor() throws Exception; 14 | } 15 | -------------------------------------------------------------------------------- /src/main/java/com/wangwenjun/guava/eventbus/service/QueryService.java: -------------------------------------------------------------------------------- 1 | package com.wangwenjun.guava.eventbus.service; 2 | 3 | import com.google.common.eventbus.EventBus; 4 | import com.google.common.eventbus.Subscribe; 5 | import com.wangwenjun.guava.eventbus.events.Request; 6 | import com.wangwenjun.guava.eventbus.events.Response; 7 | import org.slf4j.Logger; 8 | import org.slf4j.LoggerFactory; 9 | 10 | /*************************************** 11 | * @author:Alex Wang 12 | * @Date:2017/10/19 13 | * 532500648 14 | ***************************************/ 15 | public class QueryService 16 | { 17 | 18 | private final static Logger LOGGER = LoggerFactory.getLogger(QueryService.class); 19 | 20 | private final EventBus eventBus; 21 | 22 | public QueryService(EventBus eventBus) 23 | { 24 | this.eventBus = eventBus; 25 | this.eventBus.register(this); 26 | } 27 | 28 | public void query(String orderNo) 29 | { 30 | LOGGER.info("Received the orderNo [{}]", orderNo); 31 | this.eventBus.post(new Request(orderNo)); 32 | } 33 | 34 | @Subscribe 35 | public void handleResponse(Response response) 36 | { 37 | LOGGER.info("{}", response); 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /src/main/java/com/wangwenjun/guava/eventbus/service/RequestQueryHandler.java: -------------------------------------------------------------------------------- 1 | package com.wangwenjun.guava.eventbus.service; 2 | 3 | import com.google.common.eventbus.EventBus; 4 | import com.google.common.eventbus.Subscribe; 5 | import com.wangwenjun.guava.eventbus.events.Request; 6 | import com.wangwenjun.guava.eventbus.events.Response; 7 | import org.slf4j.Logger; 8 | import org.slf4j.LoggerFactory; 9 | 10 | /*************************************** 11 | * @author:Alex Wang 12 | * @Date:2017/10/19 13 | * 532500648 14 | ***************************************/ 15 | public class RequestQueryHandler 16 | { 17 | 18 | private final static Logger LOGGER = LoggerFactory.getLogger(RequestQueryHandler.class); 19 | 20 | private final EventBus eventBus; 21 | 22 | public RequestQueryHandler(EventBus eventBus) 23 | { 24 | this.eventBus = eventBus; 25 | } 26 | 27 | @Subscribe 28 | public void doQuery(Request request) 29 | { 30 | LOGGER.info("start query the orderNo [{}]", request.toString()); 31 | Response response = new Response(); 32 | this.eventBus.post(response); 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /src/main/java/com/wangwenjun/guava/eventbus/test/MyAsyncBusExample.java: -------------------------------------------------------------------------------- 1 | package com.wangwenjun.guava.eventbus.test; 2 | 3 | import com.wangwenjun.guava.eventbus.internal.MyAsyncEventBus; 4 | 5 | import java.util.concurrent.Executors; 6 | import java.util.concurrent.ThreadPoolExecutor; 7 | 8 | /*************************************** 9 | * @author:Alex Wang 10 | * @Date:2017/10/21 11 | * 532500648 12 | ***************************************/ 13 | public class MyAsyncBusExample 14 | { 15 | 16 | public static void main(String[] args) 17 | { 18 | MyAsyncEventBus eventBus = new MyAsyncEventBus((ThreadPoolExecutor) Executors.newFixedThreadPool(4)); 19 | eventBus.register(new MySimpleListener()); 20 | eventBus.register(new MySimpleListener2()); 21 | eventBus.post(123131, "alex-topic"); 22 | eventBus.post("hello"); 23 | 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /src/main/java/com/wangwenjun/guava/eventbus/test/MyEventBusExample.java: -------------------------------------------------------------------------------- 1 | package com.wangwenjun.guava.eventbus.test; 2 | 3 | import com.wangwenjun.guava.eventbus.internal.MyEventBus; 4 | 5 | /*************************************** 6 | * @author:Alex Wang 7 | * @Date:2017/10/21 8 | * 532500648 9 | ***************************************/ 10 | public class MyEventBusExample 11 | { 12 | public static void main(String[] args) 13 | { 14 | MyEventBus myEventBus = new MyEventBus((cause, context) -> 15 | { 16 | cause.printStackTrace(); 17 | System.out.println("=========================================="); 18 | System.out.println(context.getSource()); 19 | System.out.println(context.getSubscribe()); 20 | System.out.println(context.getEvent()); 21 | System.out.println(context.getSubscriber()); 22 | }); 23 | myEventBus.register(new MySimpleListener()); 24 | myEventBus.register(new MySimpleListener2()); 25 | myEventBus.post(123131, "alex-topic"); 26 | // myEventBus.post(123131, "test-topic"); 27 | 28 | 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /src/main/java/com/wangwenjun/guava/eventbus/test/MySimpleListener.java: -------------------------------------------------------------------------------- 1 | package com.wangwenjun.guava.eventbus.test; 2 | 3 | import com.wangwenjun.guava.eventbus.internal.MySubscribe; 4 | 5 | /*************************************** 6 | * @author:Alex Wang 7 | * @Date:2017/10/21 8 | * 532500648 9 | ***************************************/ 10 | public class MySimpleListener 11 | { 12 | 13 | @MySubscribe 14 | public void test1(String x) 15 | { 16 | System.out.println("MySimpleListener===test1==" + x); 17 | } 18 | 19 | @MySubscribe(topic = "alex-topic") 20 | public void test2(Integer x) 21 | { 22 | System.out.println("MySimpleListener===test2==" + x); 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /src/main/java/com/wangwenjun/guava/eventbus/test/MySimpleListener2.java: -------------------------------------------------------------------------------- 1 | package com.wangwenjun.guava.eventbus.test; 2 | 3 | import com.wangwenjun.guava.eventbus.internal.MySubscribe; 4 | 5 | import java.util.concurrent.TimeUnit; 6 | 7 | /*************************************** 8 | * @author:Alex Wang 9 | * @Date:2017/10/21 10 | * 532500648 11 | ***************************************/ 12 | public class MySimpleListener2 13 | { 14 | 15 | @MySubscribe 16 | public void test1(String x) 17 | { 18 | System.out.println("MySimpleListener2===test1==" + x); 19 | } 20 | 21 | @MySubscribe(topic = "alex-topic") 22 | public void test2(Integer x) 23 | { 24 | try 25 | { 26 | TimeUnit.MINUTES.sleep(10); 27 | } catch (InterruptedException e) 28 | { 29 | e.printStackTrace(); 30 | } 31 | System.out.println("MySimpleListener2===test2==" + x); 32 | } 33 | 34 | @MySubscribe(topic = "test-topic") 35 | public void test3(Integer x) 36 | { 37 | throw new RuntimeException(); 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /src/main/java/com/wangwenjun/guava/functional/FunctionExample.java: -------------------------------------------------------------------------------- 1 | package com.wangwenjun.guava.functional; 2 | 3 | import com.google.common.base.Function; 4 | import com.google.common.base.Functions; 5 | import com.google.common.base.Preconditions; 6 | 7 | import javax.annotation.Nullable; 8 | import java.io.IOException; 9 | import java.net.ServerSocket; 10 | 11 | /*************************************** 12 | * @author:Alex Wang 13 | * @Date:2017/10/9 14 | * @QQ: 532500648 15 | ***************************************/ 16 | public class FunctionExample { 17 | public static void main(String[] args) throws IOException { 18 | Function function = new Function() { 19 | 20 | @Nullable 21 | @Override 22 | public Integer apply(@Nullable String input) { 23 | Preconditions.checkNotNull(input, "The input Stream should not be null."); 24 | return input.length(); 25 | } 26 | }; 27 | 28 | System.out.println(function.apply("Hello")); 29 | 30 | process("Hello", new Handler.LengthDoubleHandler()); 31 | System.out.println(Functions.toStringFunction().apply(new ServerSocket(8888))); 32 | 33 | 34 | Function compose = Functions.compose(new Function() { 35 | @Nullable 36 | @Override 37 | public Double apply(@Nullable Integer input) { 38 | return input * 1.0D; 39 | 40 | } 41 | }, new Function() { 42 | 43 | @Nullable 44 | @Override 45 | public Integer apply(@Nullable String input) { 46 | return input.length(); 47 | } 48 | }); 49 | 50 | System.out.println(compose.apply("Hello")); 51 | 52 | } 53 | 54 | interface Handler { 55 | 56 | OUT handle(IN input); 57 | 58 | 59 | class LengthDoubleHandler implements Handler { 60 | 61 | @Override 62 | public Integer handle(String input) { 63 | return input.length() * 2; 64 | } 65 | } 66 | } 67 | 68 | private static void process(String text, Handler handler) { 69 | System.out.println(handler.handle(text)); 70 | } 71 | } 72 | -------------------------------------------------------------------------------- /src/main/java/com/wangwenjun/guava/io/Base64.java: -------------------------------------------------------------------------------- 1 | package com.wangwenjun.guava.io; 2 | 3 | import com.google.common.base.Preconditions; 4 | 5 | /*************************************** 6 | * @author:Alex Wang 7 | * @Date:2017/10/15 8 | * @QQ: 532500648 9 | ***************************************/ 10 | public final class Base64 { 11 | 12 | private final static String CODE_STRING = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; 13 | 14 | private final static char[] CODE_DICT = CODE_STRING.toCharArray(); 15 | 16 | private Base64() { 17 | } 18 | 19 | public static String encode(String plain) { 20 | Preconditions.checkNotNull(plain); 21 | StringBuilder result = new StringBuilder(); 22 | String binaryString = toBinary(plain); 23 | 24 | int delta = 6 - binaryString.length() % 6;//should append 25 | 26 | for (int i = 0; i < delta && delta != 6; i++) { 27 | binaryString += "0"; 28 | } 29 | 30 | for (int index = 0; index < binaryString.length() / 6; index++) { 31 | int begin = index * 6; 32 | String encodeString = binaryString.substring(begin, begin + 6); 33 | char encodeChar = CODE_DICT[Integer.valueOf(encodeString, 2)]; 34 | result.append(encodeChar); 35 | } 36 | 37 | if (delta != 6) { 38 | for (int i = 0; i < delta / 2; i++) { 39 | result.append("="); 40 | } 41 | } 42 | 43 | return result.toString(); 44 | } 45 | 46 | private static String toBinary(final String source) { 47 | final StringBuilder binaryResult = new StringBuilder(); 48 | for (int index = 0; index < source.length(); index++) { 49 | String charBin = Integer.toBinaryString(source.charAt(index)); 50 | int delta = 8 - charBin.length(); 51 | for (int d = 0; d < delta; d++) { 52 | charBin = "0" + charBin; 53 | } 54 | 55 | binaryResult.append(charBin); 56 | } 57 | 58 | return binaryResult.toString(); 59 | } 60 | 61 | public static String decode(final String encrypt) { 62 | StringBuilder resultBuilder = new StringBuilder(); 63 | 64 | String temp = encrypt; 65 | int equalIndex = temp.indexOf("="); 66 | if (equalIndex > 0) { 67 | temp = temp.substring(0, equalIndex); 68 | } 69 | 70 | String base64Binary = toBase64Binary(temp); 71 | for (int i = 0; i < base64Binary.length() / 8; i++) { 72 | int begin = i * 8; 73 | String str = base64Binary.substring(begin, begin + 8); 74 | char c = Character.toChars(Integer.valueOf(str, 2))[0]; 75 | resultBuilder.append(c); 76 | } 77 | 78 | return resultBuilder.toString(); 79 | } 80 | 81 | private static String toBase64Binary(final String source) { 82 | final StringBuilder binaryResult = new StringBuilder(); 83 | for (int index = 0; index < source.length(); index++) { 84 | int i = CODE_STRING.indexOf(source.charAt(index)); 85 | String charBin = Integer.toBinaryString(i); 86 | int delta = 6 - charBin.length(); 87 | for (int d = 0; d < delta; d++) { 88 | charBin = "0" + charBin; 89 | } 90 | 91 | binaryResult.append(charBin); 92 | } 93 | 94 | return binaryResult.toString(); 95 | } 96 | 97 | 98 | public static void main(String[] args) { 99 | System.out.println(encode("hello")); 100 | System.out.println(encode("a")); 101 | System.out.println(encode("12a")); 102 | System.out.println("======================="); 103 | System.out.println(decode("aGVsbG8=")); 104 | System.out.println(decode("YQ==")); 105 | System.out.println(decode("MTJh")); 106 | } 107 | } 108 | -------------------------------------------------------------------------------- /src/main/java/com/wangwenjun/guava/io/package-info.java: -------------------------------------------------------------------------------- 1 | /** 2 | * @author:Alex Wang 3 | * @Date:2017/10/14 4 | * @QQ: 532500648 5 | *

6 | * {@link com.wangwenjun.guava.io.FilesTest} 7 | */ 8 | 9 | package com.wangwenjun.guava.io; -------------------------------------------------------------------------------- /src/main/java/com/wangwenjun/guava/utilities/ElapsedExample.java: -------------------------------------------------------------------------------- 1 | package com.wangwenjun.guava.utilities; 2 | 3 | import java.util.concurrent.TimeUnit; 4 | 5 | /*************************************** 6 | * @author:Alex Wang 7 | * @Date:2017/10/11 8 | * @QQ: 532500648 9 | ***************************************/ 10 | public class ElapsedExample { 11 | 12 | public static void main(String[] args) throws InterruptedException { 13 | process("3463542353"); 14 | } 15 | 16 | /** 17 | * splunk 18 | * @param orderNo 19 | * @throws InterruptedException 20 | */ 21 | private static void process(String orderNo) throws InterruptedException { 22 | 23 | System.out.printf("start process the order %s\n", orderNo); 24 | long startNano = System.nanoTime(); 25 | TimeUnit.SECONDS.sleep(1); 26 | 27 | System.out.printf("The orderNo %s process successful and elapsed %d ns.\n", orderNo, (System.nanoTime() - startNano)); 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /src/main/java/com/wangwenjun/guava/utilities/ObjectsExample.java: -------------------------------------------------------------------------------- 1 | package com.wangwenjun.guava.utilities; 2 | 3 | import com.google.common.base.MoreObjects; 4 | import com.google.common.base.Objects; 5 | import com.google.common.collect.ComparisonChain; 6 | 7 | import java.util.Calendar; 8 | 9 | 10 | /*************************************** 11 | * @author:Alex Wang 12 | * @Date:2017/10/7 13 | * @QQ: 532500648 14 | ***************************************/ 15 | public class ObjectsExample { 16 | 17 | public static void main(String[] args) { 18 | final Guava guava = new Guava("Google", "23.0", Calendar.getInstance()); 19 | System.out.println(guava); 20 | System.out.println(guava.hashCode()); 21 | 22 | Calendar calendar = Calendar.getInstance(); 23 | calendar.add(Calendar.YEAR, 1); 24 | final Guava guava2 = new Guava("Google", "23.0", calendar); 25 | System.out.println(guava.compareTo(guava2)); 26 | } 27 | 28 | static class Guava implements Comparable { 29 | private final String manufacturer; 30 | private final String version; 31 | private final Calendar releaseDate; 32 | 33 | public Guava(String manufacturer, String version, Calendar releaseDate) { 34 | this.manufacturer = manufacturer; 35 | this.version = version; 36 | this.releaseDate = releaseDate; 37 | } 38 | 39 | @Override 40 | public String toString() { 41 | return MoreObjects.toStringHelper(this).omitNullValues() 42 | .add("manufacturer", this.manufacturer) 43 | .add("version", this.version) 44 | .add("releaseDate", this.releaseDate).toString(); 45 | } 46 | 47 | @Override 48 | public int hashCode() { 49 | return Objects.hashCode(manufacturer, version, releaseDate); 50 | } 51 | 52 | @Override 53 | public boolean equals(Object obj) { 54 | if (this == obj) return true; 55 | if (obj == null || getClass() != obj.getClass()) return false; 56 | 57 | Guava guava = (Guava) obj; 58 | 59 | return Objects.equal(this.manufacturer, guava.manufacturer) 60 | && Objects.equal(this.version, guava.version) 61 | && Objects.equal(this.releaseDate, guava.releaseDate); 62 | } 63 | 64 | @Override 65 | public int compareTo(Guava o) { 66 | return ComparisonChain.start().compare(this.manufacturer, o.manufacturer) 67 | .compare(this.version, o.version).compare(this.releaseDate, o.releaseDate).result(); 68 | } 69 | 70 | 71 | 72 | /*@Override 73 | public boolean equals(Object o) { 74 | if (this == o) return true; 75 | if (o == null || getClass() != o.getClass()) return false; 76 | 77 | Guava guava = (Guava) o; 78 | 79 | if (manufacturer != null ? !manufacturer.equals(guava.manufacturer) : guava.manufacturer != null) 80 | return false; 81 | if (version != null ? !version.equals(guava.version) : guava.version != null) return false; 82 | return releaseDate != null ? releaseDate.equals(guava.releaseDate) : guava.releaseDate == null; 83 | } 84 | 85 | @Override 86 | public int hashCode() { 87 | int result = manufacturer != null ? manufacturer.hashCode() : 0; 88 | result = 31 * result + (version != null ? version.hashCode() : 0); 89 | result = 31 * result + (releaseDate != null ? releaseDate.hashCode() : 0); 90 | return result; 91 | } 92 | 93 | @Override 94 | public String toString() { 95 | return "Guava{" + 96 | "manufacturer='" + manufacturer + '\'' + 97 | ", version='" + version + '\'' + 98 | ", releaseDate=" + releaseDate + 99 | '}'; 100 | }*/ 101 | } 102 | } 103 | -------------------------------------------------------------------------------- /src/main/java/com/wangwenjun/guava/utilities/StopWatchExample.java: -------------------------------------------------------------------------------- 1 | package com.wangwenjun.guava.utilities; 2 | 3 | import com.google.common.base.Stopwatch; 4 | import org.slf4j.Logger; 5 | import org.slf4j.LoggerFactory; 6 | 7 | import java.sql.Time; 8 | import java.util.concurrent.TimeUnit; 9 | 10 | /*************************************** 11 | * @author:Alex Wang 12 | * @Date:2017/10/11 13 | * @QQ: 532500648 14 | ***************************************/ 15 | public class StopWatchExample { 16 | private final static Logger LOGGER = LoggerFactory.getLogger(StopWatchExample.class); 17 | 18 | public static void main(String[] args) throws InterruptedException { 19 | process("3463542353"); 20 | } 21 | 22 | /** 23 | * drools 24 | * @param orderNo 25 | * @throws InterruptedException 26 | */ 27 | private static void process(String orderNo) throws InterruptedException { 28 | 29 | LOGGER.info("start process the order [{}]", orderNo); 30 | Stopwatch stopwatch = Stopwatch.createStarted(); 31 | TimeUnit.MILLISECONDS.sleep(100); 32 | 33 | LOGGER.info("The orderNo [{}] process successful and elapsed [{}] min.", orderNo, stopwatch.stop().elapsed(TimeUnit.MINUTES)); 34 | 35 | /** 36 | * 37 | */ 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /src/main/java/com/wangwenjun/guava/utilities/package-info.java: -------------------------------------------------------------------------------- 1 | /*************************************** 2 | * @author:Alex Wang 3 | * @Date:2017/10/6 4 | * @QQ: 532500648 5 | * 6 | * The utilities of Joiner will be demo by test case {@link JoinerTest} 7 | * The utilities of Splitter will be demo by test case {@link SplitterTest} 8 | * The utilities of PreConditions will be demo by test case {@link PreConditionsTest} 9 | ***************************************/ 10 | package com.wangwenjun.guava.utilities; -------------------------------------------------------------------------------- /src/main/resources/io/source.txt: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/wangwenjun/guava_programming/804e50450d626ec9b74dc2a9adf95f8628c6be4d/src/main/resources/io/source.txt -------------------------------------------------------------------------------- /src/main/resources/logback.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | %d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n 6 | 7 | 8 | 9 | 10 | 11 | 12 | -------------------------------------------------------------------------------- /src/test/java/com/wangwenjun/guava/cache/CacheLoaderTest.java: -------------------------------------------------------------------------------- 1 | package com.wangwenjun.guava.cache; 2 | 3 | import com.google.common.cache.CacheBuilder; 4 | import com.google.common.cache.CacheLoader; 5 | import com.google.common.cache.LoadingCache; 6 | import com.google.common.cache.Weigher; 7 | import org.junit.Test; 8 | 9 | import java.util.concurrent.ExecutionException; 10 | import java.util.concurrent.TimeUnit; 11 | 12 | import static org.hamcrest.core.IsEqual.equalTo; 13 | import static org.hamcrest.core.IsNull.notNullValue; 14 | import static org.hamcrest.core.IsNull.nullValue; 15 | import static org.junit.Assert.assertThat; 16 | 17 | /*************************************** 18 | * @author:Alex Wang 19 | * @Date:2017/11/18 20 | * QQ: 532500648 21 | * QQ群:463962286 22 | ***************************************/ 23 | public class CacheLoaderTest 24 | { 25 | 26 | private boolean isTrue = false; 27 | 28 | @Test 29 | public void testBasic() throws ExecutionException, InterruptedException 30 | { 31 | LoadingCache cache = CacheBuilder.newBuilder().maximumSize(10) 32 | .expireAfterAccess(30, TimeUnit.MILLISECONDS) 33 | .build(createCacheLoader()); 34 | 35 | Employee employee = cache.get("Alex"); 36 | assertThat(employee, notNullValue()); 37 | assertLoadFromDBThenReset(); 38 | employee = cache.get("Alex"); 39 | assertThat(employee, notNullValue()); 40 | assertLoadFromCache(); 41 | 42 | TimeUnit.MILLISECONDS.sleep(31); 43 | employee = cache.get("Alex"); 44 | 45 | assertThat(employee, notNullValue()); 46 | assertLoadFromDBThenReset(); 47 | } 48 | 49 | @Test 50 | public void testEvictionBySize() 51 | { 52 | CacheLoader cacheLoader = createCacheLoader(); 53 | LoadingCache cache = CacheBuilder.newBuilder() 54 | .maximumSize(3).build(cacheLoader); 55 | 56 | cache.getUnchecked("Alex"); 57 | assertLoadFromDBThenReset(); 58 | cache.getUnchecked("Jack"); 59 | assertLoadFromDBThenReset(); 60 | 61 | cache.getUnchecked("Gavin"); 62 | assertLoadFromDBThenReset(); 63 | 64 | assertThat(cache.size(), equalTo(3L)); 65 | cache.getUnchecked("Susan"); 66 | assertThat(cache.getIfPresent("Alex"), nullValue()); 67 | 68 | assertThat(cache.getIfPresent("Susan"), notNullValue()); 69 | } 70 | 71 | @Test 72 | public void testEvictionByWeight() 73 | { 74 | Weigher weigher = (key, employee) -> 75 | employee.getName().length() + employee.getEmpID().length() + employee.getDept().length(); 76 | 77 | LoadingCache cache = CacheBuilder.newBuilder() 78 | .maximumWeight(45) 79 | .concurrencyLevel(1) 80 | .weigher(weigher) 81 | .build(createCacheLoader()); 82 | 83 | cache.getUnchecked("Gavin"); 84 | assertLoadFromDBThenReset(); 85 | 86 | cache.getUnchecked("Kevin"); 87 | assertLoadFromDBThenReset(); 88 | 89 | cache.getUnchecked("Allen"); 90 | assertLoadFromDBThenReset(); 91 | assertThat(cache.size(), equalTo(3L)); 92 | assertThat(cache.getIfPresent("Gavin"), notNullValue()); 93 | 94 | cache.getUnchecked("Jason"); 95 | 96 | assertThat(cache.getIfPresent("Kevin"), nullValue()); 97 | assertThat(cache.size(), equalTo(3L)); 98 | } 99 | 100 | private CacheLoader createCacheLoader() 101 | { 102 | return new CacheLoader() 103 | { 104 | @Override 105 | public Employee load(String key) throws Exception 106 | { 107 | return findEmployeeByName(key); 108 | } 109 | }; 110 | } 111 | 112 | 113 | private void assertLoadFromDBThenReset() 114 | { 115 | assertThat(true, equalTo(isTrue)); 116 | this.isTrue = false; 117 | } 118 | 119 | private void assertLoadFromCache() 120 | { 121 | assertThat(false, equalTo(isTrue)); 122 | } 123 | 124 | private Employee findEmployeeByName(final String name) 125 | { 126 | //System.out.println("The employee " + name + " is load from DB."); 127 | isTrue = true; 128 | return new Employee(name, name, name); 129 | } 130 | } -------------------------------------------------------------------------------- /src/test/java/com/wangwenjun/guava/cache/CacheLoaderTest2.java: -------------------------------------------------------------------------------- 1 | package com.wangwenjun.guava.cache; 2 | 3 | import com.google.common.cache.CacheBuilder; 4 | import com.google.common.cache.CacheLoader; 5 | import com.google.common.cache.LoadingCache; 6 | import org.junit.Test; 7 | 8 | import java.util.concurrent.TimeUnit; 9 | 10 | import static org.hamcrest.core.IsEqual.equalTo; 11 | import static org.hamcrest.core.IsNull.notNullValue; 12 | import static org.hamcrest.core.IsNull.nullValue; 13 | import static org.junit.Assert.assertThat; 14 | 15 | /*************************************** 16 | * @author:Alex Wang 17 | * @Date:2017/11/18 18 | * QQ: 532500648 19 | * QQ群:463962286 20 | ***************************************/ 21 | public class CacheLoaderTest2 22 | { 23 | 24 | /** 25 | * TTL->time to live 26 | * Access time => Write/Update/Read 27 | * 28 | * @throws InterruptedException 29 | */ 30 | @Test 31 | public void testEvictionByAccessTime() throws InterruptedException 32 | { 33 | LoadingCache cache = CacheBuilder.newBuilder() 34 | .expireAfterAccess(2, TimeUnit.SECONDS) 35 | .build(this.createCacheLoader()); 36 | assertThat(cache.getUnchecked("Alex"), notNullValue()); 37 | assertThat(cache.size(), equalTo(1L)); 38 | 39 | TimeUnit.SECONDS.sleep(3); 40 | assertThat(cache.getIfPresent("Alex"), nullValue()); 41 | 42 | assertThat(cache.getUnchecked("Guava"), notNullValue()); 43 | 44 | TimeUnit.SECONDS.sleep(1); 45 | assertThat(cache.getIfPresent("Guava"), notNullValue()); 46 | TimeUnit.SECONDS.sleep(1); 47 | assertThat(cache.getIfPresent("Guava"), notNullValue()); 48 | 49 | TimeUnit.SECONDS.sleep(1); 50 | assertThat(cache.getIfPresent("Guava"), notNullValue()); 51 | } 52 | 53 | /** 54 | * Write time => write/update 55 | */ 56 | @Test 57 | public void testEvictionByWriteTime() throws InterruptedException 58 | { 59 | LoadingCache cache = CacheBuilder.newBuilder() 60 | .expireAfterWrite(2, TimeUnit.SECONDS) 61 | .build(this.createCacheLoader()); 62 | 63 | assertThat(cache.getUnchecked("Alex"), notNullValue()); 64 | assertThat(cache.size(), equalTo(1L)); 65 | 66 | assertThat(cache.getUnchecked("Guava"), notNullValue()); 67 | 68 | TimeUnit.SECONDS.sleep(1); 69 | assertThat(cache.getIfPresent("Guava"), notNullValue()); 70 | TimeUnit.MILLISECONDS.sleep(990); 71 | assertThat(cache.getIfPresent("Guava"), notNullValue()); 72 | 73 | TimeUnit.SECONDS.sleep(1); 74 | assertThat(cache.getIfPresent("Guava"), nullValue()); 75 | } 76 | 77 | /** 78 | * Strong/soft/weak/Phantom reference 79 | */ 80 | @Test 81 | public void testWeakKey() throws InterruptedException 82 | { 83 | LoadingCache cache = CacheBuilder.newBuilder() 84 | .expireAfterWrite(2, TimeUnit.SECONDS) 85 | .weakValues() 86 | .weakKeys() 87 | .build(this.createCacheLoader()); 88 | assertThat(cache.getUnchecked("Alex"), notNullValue()); 89 | assertThat(cache.getUnchecked("Guava"), notNullValue()); 90 | 91 | //active method 92 | //Thread Active design pattern 93 | System.gc(); 94 | 95 | TimeUnit.MILLISECONDS.sleep(100); 96 | assertThat(cache.getIfPresent("Alex"), nullValue()); 97 | } 98 | 99 | @Test 100 | public void testSoftKey() throws InterruptedException 101 | { 102 | LoadingCache cache = CacheBuilder.newBuilder() 103 | .expireAfterWrite(2, TimeUnit.SECONDS) 104 | .softValues() 105 | .build(this.createCacheLoader()); 106 | int i = 0; 107 | for (; ; ) 108 | { 109 | cache.put("Alex" + i, new Employee("Alex" + 1, "Alex" + 1, "Alex" + 1)); 110 | System.out.println("The Employee [" + (i++) + "] is store into cache."); 111 | TimeUnit.MILLISECONDS.sleep(600); 112 | } 113 | } 114 | 115 | private CacheLoader createCacheLoader() 116 | { 117 | return CacheLoader.from(key -> new Employee(key, key, key)); 118 | } 119 | } 120 | -------------------------------------------------------------------------------- /src/test/java/com/wangwenjun/guava/cache/CacheLoaderTest3.java: -------------------------------------------------------------------------------- 1 | package com.wangwenjun.guava.cache; 2 | 3 | import com.google.common.base.Optional; 4 | import com.google.common.cache.*; 5 | import org.junit.Test; 6 | 7 | import java.util.HashMap; 8 | import java.util.Map; 9 | import java.util.concurrent.TimeUnit; 10 | import java.util.concurrent.atomic.AtomicInteger; 11 | 12 | import static org.hamcrest.core.Is.is; 13 | import static org.hamcrest.core.IsEqual.equalTo; 14 | import static org.hamcrest.core.IsNull.notNullValue; 15 | import static org.hamcrest.core.IsNull.nullValue; 16 | import static org.junit.Assert.assertThat; 17 | import static org.junit.Assert.fail; 18 | 19 | /*************************************** 20 | * @author:Alex Wang 21 | * @Date:2018/1/9 22 | * QQ: 532500648 23 | * QQ群:463962286 24 | ***************************************/ 25 | public class CacheLoaderTest3 26 | { 27 | 28 | @Test 29 | public void testLoadNullValue() 30 | { 31 | CacheLoader cacheLoader = CacheLoader 32 | .from(k -> k.equals("null") ? null : new Employee(k, k, k)); 33 | LoadingCache loadingCache = CacheBuilder.newBuilder().build(cacheLoader); 34 | 35 | Employee alex = loadingCache.getUnchecked("Alex"); 36 | 37 | assertThat(alex.getName(), equalTo("Alex")); 38 | try 39 | { 40 | assertThat(loadingCache.getUnchecked("null"), nullValue()); 41 | fail("should not process to here."); 42 | } catch (Exception e) 43 | { 44 | // (expected = CacheLoader.InvalidCacheLoadException.class) 45 | assertThat(e instanceof CacheLoader.InvalidCacheLoadException, equalTo(true)); 46 | } 47 | } 48 | 49 | @Test 50 | public void testLoadNullValueUseOptional() 51 | { 52 | CacheLoader> loader = new CacheLoader>() 53 | { 54 | @Override 55 | public Optional load(String key) throws Exception 56 | { 57 | if (key.equals("null")) 58 | return Optional.fromNullable(null); 59 | else 60 | return Optional.fromNullable(new Employee(key, key, key)); 61 | } 62 | }; 63 | 64 | LoadingCache> cache = CacheBuilder.newBuilder().build(loader); 65 | assertThat(cache.getUnchecked("Alex").get(), notNullValue()); 66 | assertThat(cache.getUnchecked("null").orNull(), nullValue()); 67 | 68 | Employee def = cache.getUnchecked("null").or(new Employee("default", "default", "default")); 69 | assertThat(def.getName().length(), equalTo(7)); 70 | } 71 | 72 | 73 | @Test 74 | public void testCacheRefresh() throws InterruptedException 75 | { 76 | AtomicInteger counter = new AtomicInteger(0); 77 | CacheLoader cacheLoader = CacheLoader 78 | .from(k -> 79 | { 80 | counter.incrementAndGet(); 81 | return System.currentTimeMillis(); 82 | }); 83 | 84 | LoadingCache cache = CacheBuilder.newBuilder() 85 | // .refreshAfterWrite(2, TimeUnit.SECONDS) 86 | .build(cacheLoader); 87 | 88 | Long result1 = cache.getUnchecked("Alex"); 89 | TimeUnit.SECONDS.sleep(3); 90 | Long result2 = cache.getUnchecked("Alex"); 91 | assertThat(counter.get(), equalTo(1)); 92 | // assertThat(result1.longValue() != result2.longValue(), equalTo(true)); 93 | } 94 | 95 | @Test 96 | public void testCachePreLoad() 97 | { 98 | CacheLoader loader = CacheLoader.from(String::toUpperCase); 99 | LoadingCache cache = CacheBuilder.newBuilder().build(loader); 100 | 101 | Map preData = new HashMap() 102 | { 103 | { 104 | put("alex", "ALEX"); 105 | put("hello", "hello"); 106 | } 107 | }; 108 | 109 | cache.putAll(preData); 110 | assertThat(cache.size(), equalTo(2L)); 111 | assertThat(cache.getUnchecked("alex"), equalTo("ALEX")); 112 | assertThat(cache.getUnchecked("hello"), equalTo("hello")); 113 | } 114 | 115 | @Test 116 | public void testCacheRemovedNotification() 117 | { 118 | CacheLoader loader = CacheLoader.from(String::toUpperCase); 119 | RemovalListener listener = notification -> 120 | { 121 | if (notification.wasEvicted()) 122 | { 123 | RemovalCause cause = notification.getCause(); 124 | assertThat(cause, is(RemovalCause.SIZE)); 125 | assertThat(notification.getKey(), equalTo("Alex")); 126 | } 127 | }; 128 | 129 | LoadingCache cache = CacheBuilder.newBuilder() 130 | // 131 | .maximumSize(3) 132 | // 133 | .removalListener(listener) 134 | // 135 | .build(loader); 136 | cache.getUnchecked("Alex"); 137 | cache.getUnchecked("Eachur"); 138 | cache.getUnchecked("Jack"); 139 | cache.getUnchecked("Jenny"); 140 | } 141 | } 142 | -------------------------------------------------------------------------------- /src/test/java/com/wangwenjun/guava/cache/CacheLoaderTest4.java: -------------------------------------------------------------------------------- 1 | package com.wangwenjun.guava.cache; 2 | 3 | import com.google.common.cache.*; 4 | import org.junit.Test; 5 | 6 | import static org.hamcrest.core.IsEqual.equalTo; 7 | import static org.junit.Assert.assertThat; 8 | 9 | /*************************************** 10 | * @author:Alex Wang 11 | * @Date:2018/1/13 12 | * QQ: 532500648 13 | * QQ群:463962286 14 | ***************************************/ 15 | public class CacheLoaderTest4 16 | { 17 | 18 | @Test 19 | public void testCacheStat() 20 | { 21 | CacheLoader loader = CacheLoader.from(String::toUpperCase); 22 | LoadingCache cache = CacheBuilder.newBuilder().maximumSize(5).recordStats().build(loader); 23 | assertCache(cache); 24 | } 25 | 26 | @Test 27 | public void testCacheSpec() 28 | { 29 | String spec = "maximumSize=5,recordStats"; 30 | CacheBuilderSpec builderSpec = CacheBuilderSpec.parse(spec); 31 | CacheLoader loader = CacheLoader.from(String::toUpperCase); 32 | LoadingCache cache = CacheBuilder.from(builderSpec).build(loader); 33 | 34 | assertCache(cache); 35 | } 36 | 37 | private void assertCache(LoadingCache cache) 38 | { 39 | assertThat(cache.getUnchecked("alex"), equalTo("ALEX"));//ALEX 40 | CacheStats stats = cache.stats(); 41 | System.out.println(stats.hashCode()); 42 | assertThat(stats.hitCount(), equalTo(0L)); 43 | assertThat(stats.missCount(), equalTo(1L)); 44 | 45 | assertThat(cache.getUnchecked("alex"), equalTo("ALEX")); 46 | 47 | stats = cache.stats(); 48 | System.out.println(stats.hashCode()); 49 | assertThat(stats.hitCount(), equalTo(1L)); 50 | assertThat(stats.missCount(), equalTo(1L)); 51 | 52 | System.out.println(stats.missRate()); 53 | System.out.println(stats.hitRate()); 54 | } 55 | } 56 | -------------------------------------------------------------------------------- /src/test/java/com/wangwenjun/guava/collections/BiMapExampleTest.java: -------------------------------------------------------------------------------- 1 | package com.wangwenjun.guava.collections; 2 | 3 | import com.google.common.collect.BiMap; 4 | import com.google.common.collect.HashBiMap; 5 | import org.junit.Test; 6 | 7 | import static org.hamcrest.core.Is.is; 8 | import static org.hamcrest.core.IsEqual.equalTo; 9 | import static org.junit.Assert.*; 10 | 11 | /*************************************** 12 | * @author:Alex Wang 13 | * @Date:2018/1/14 14 | * QQ: 532500648 15 | * QQ群:463962286 16 | ***************************************/ 17 | public class BiMapExampleTest 18 | { 19 | 20 | @Test 21 | public void testCreateAndPut() 22 | { 23 | HashBiMap biMap = HashBiMap.create(); 24 | biMap.put("1", "2"); 25 | biMap.put("1", "3"); 26 | assertThat(biMap.containsKey("1"), is(true)); 27 | assertThat(biMap.size(), equalTo(1)); 28 | 29 | try 30 | { 31 | biMap.put("2", "3"); 32 | fail(); 33 | } catch (Exception e) 34 | { 35 | e.printStackTrace(); 36 | } 37 | } 38 | 39 | @Test 40 | public void testBiMapInverse() 41 | { 42 | HashBiMap biMap = HashBiMap.create(); 43 | biMap.put("1", "2"); 44 | biMap.put("2", "3"); 45 | biMap.put("3", "4"); 46 | 47 | assertThat(biMap.containsKey("1"), is(true)); 48 | assertThat(biMap.containsKey("2"), is(true)); 49 | assertThat(biMap.containsKey("3"), is(true)); 50 | assertThat(biMap.size(), equalTo(3)); 51 | 52 | BiMap inverseKey = biMap.inverse(); 53 | assertThat(inverseKey.containsKey("2"), is(true)); 54 | assertThat(inverseKey.containsKey("3"), is(true)); 55 | assertThat(inverseKey.containsKey("4"), is(true)); 56 | assertThat(inverseKey.size(), equalTo(3)); 57 | } 58 | 59 | @Test 60 | public void testCreateAndForcePut() 61 | { 62 | HashBiMap biMap = HashBiMap.create(); 63 | biMap.put("1", "2"); 64 | assertThat(biMap.containsKey("1"), is(true)); 65 | biMap.forcePut("2", "2"); 66 | assertThat(biMap.containsKey("1"), is(false)); 67 | assertThat(biMap.containsKey("2"), is(true)); 68 | } 69 | } -------------------------------------------------------------------------------- /src/test/java/com/wangwenjun/guava/collections/FluentIterableExampleTest.java: -------------------------------------------------------------------------------- 1 | package com.wangwenjun.guava.collections; 2 | 3 | import com.google.common.base.Joiner; 4 | import com.google.common.base.Optional; 5 | import com.google.common.collect.FluentIterable; 6 | import com.google.common.collect.Lists; 7 | import org.junit.Test; 8 | 9 | import java.util.ArrayList; 10 | import java.util.List; 11 | 12 | import static org.hamcrest.core.Is.is; 13 | import static org.hamcrest.core.IsEqual.equalTo; 14 | import static org.junit.Assert.*; 15 | 16 | /*************************************** 17 | * @author:Alex Wang 18 | * @Date:2018/1/13 19 | * QQ: 532500648 20 | * QQ群:463962286 21 | ***************************************/ 22 | public class FluentIterableExampleTest 23 | { 24 | 25 | private FluentIterable build() 26 | { 27 | ArrayList list = Lists.newArrayList("Alex", "Wang", "Guava", "Scala"); 28 | return FluentIterable.from(list); 29 | } 30 | 31 | @Test 32 | public void testFilter() 33 | { 34 | FluentIterable fit = build(); 35 | assertThat(fit.size(), equalTo(4)); 36 | 37 | FluentIterable result = fit.filter(e -> e != null && e.length() > 4); 38 | assertThat(result.size(), equalTo(2)); 39 | } 40 | 41 | @Test 42 | public void testAppend() 43 | { 44 | FluentIterable fit = build(); 45 | ArrayList append = Lists.newArrayList("APPEND"); 46 | assertThat(fit.size(), equalTo(4)); 47 | FluentIterable appendFI = fit.append(append); 48 | assertThat(appendFI.size(), equalTo(5)); 49 | assertThat(appendFI.contains("APPEND"), is(true)); 50 | 51 | appendFI = appendFI.append("APPEND2"); 52 | assertThat(appendFI.size(), equalTo(6)); 53 | assertThat(appendFI.contains("APPEND2"), is(true)); 54 | assertThat(appendFI.contains("Alex"), is(true)); 55 | } 56 | 57 | @Test 58 | public void testMatch() 59 | { 60 | FluentIterable fit = build(); 61 | boolean result = fit.allMatch(e -> e != null && e.length() >= 4); 62 | assertThat(result, is(true)); 63 | 64 | result = fit.anyMatch(e -> e != null && e.length() == 5); 65 | assertThat(result, is(true)); 66 | 67 | Optional optional = fit.firstMatch(e -> e != null && e.length() == 5); 68 | assertThat(optional.isPresent(), is(true)); 69 | assertThat(optional.get(), equalTo("Guava")); 70 | } 71 | 72 | @Test 73 | public void testFirst$Last() 74 | { 75 | FluentIterable fit = build(); 76 | Optional optional = fit.first(); 77 | assertThat(optional.isPresent(), is(true)); 78 | assertThat(optional.get(), equalTo("Alex")); 79 | 80 | optional = fit.last(); 81 | assertThat(optional.isPresent(), is(true)); 82 | assertThat(optional.get(), equalTo("Scala")); 83 | } 84 | 85 | @Test 86 | public void testLimit() 87 | { 88 | FluentIterable fit = build(); 89 | FluentIterable limit = fit.limit(3); 90 | System.out.println(limit); 91 | assertThat(limit.contains("Scala"), is(false)); 92 | 93 | limit = fit.limit(300); 94 | System.out.println(limit); 95 | assertThat(limit.contains("Scala"), is(true)); 96 | 97 | } 98 | 99 | /** 100 | * DSL 101 | */ 102 | @Test 103 | public void testCopyIn() 104 | { 105 | FluentIterable fit = build(); 106 | ArrayList list = Lists.newArrayList("Java"); 107 | ArrayList result = fit.copyInto(list); 108 | 109 | assertThat(result.size(), equalTo(5)); 110 | assertThat(result.contains("Scala"), is(true)); 111 | } 112 | 113 | @Test 114 | public void testCycle() 115 | { 116 | FluentIterable fit = build(); 117 | FluentIterable cycle = fit.cycle().limit(20); 118 | cycle.forEach(System.out::println); 119 | } 120 | 121 | @Test 122 | public void testTransform() 123 | { 124 | FluentIterable fit = build(); 125 | fit.transform(e -> e.length()).forEach(System.out::println); 126 | } 127 | 128 | @Test 129 | public void testTransformAndConcat() 130 | { 131 | FluentIterable fit = build(); 132 | List list = Lists.newArrayList(1); 133 | FluentIterable result = fit.transformAndConcat(e -> list); 134 | result.forEach(System.out::println); 135 | } 136 | 137 | /** 138 | * A----->API---->B(Server) 139 | * 1,2 140 | */ 141 | @Test 142 | public void testTransformAndConcatInAction() 143 | { 144 | ArrayList cTypes = Lists.newArrayList(1, 2); 145 | FluentIterable.from(cTypes).transformAndConcat(this::search) 146 | .forEach(System.out::println); 147 | } 148 | 149 | @Test 150 | public void testJoin() 151 | { 152 | FluentIterable fit = build(); 153 | String result = fit.join(Joiner.on(',')); 154 | assertThat(result, equalTo("Alex,Wang,Guava,Scala")); 155 | } 156 | 157 | 158 | private List search(int type) 159 | { 160 | if (type == 1) 161 | { 162 | return Lists.newArrayList(new Customer(type, "Alex"), new Customer(type, "Tina")); 163 | } else 164 | { 165 | return Lists.newArrayList(new Customer(type, "Wang"), new Customer(type, "Wen"), new Customer(type, "Jun")); 166 | } 167 | } 168 | 169 | class Customer 170 | { 171 | final int type; 172 | final String name; 173 | 174 | Customer(int type, String name) 175 | { 176 | this.type = type; 177 | this.name = name; 178 | } 179 | 180 | @Override 181 | public String toString() 182 | { 183 | return "Customer{" + 184 | "type=" + type + 185 | ", name='" + name + '\'' + 186 | '}'; 187 | } 188 | } 189 | } -------------------------------------------------------------------------------- /src/test/java/com/wangwenjun/guava/collections/ImmutableCollectionsTest.java: -------------------------------------------------------------------------------- 1 | package com.wangwenjun.guava.collections; 2 | 3 | import com.google.common.collect.ImmutableList; 4 | import com.google.common.collect.ImmutableMap; 5 | import org.junit.Test; 6 | 7 | import java.util.Arrays; 8 | 9 | import static junit.framework.Assert.fail; 10 | import static org.hamcrest.core.Is.is; 11 | import static org.hamcrest.core.IsNull.notNullValue; 12 | import static org.junit.Assert.assertThat; 13 | 14 | /*************************************** 15 | * @author:Alex Wang 16 | * @Date:2018/1/15 17 | * QQ: 532500648 18 | * QQ群:463962286 19 | ***************************************/ 20 | public class ImmutableCollectionsTest 21 | { 22 | 23 | @Test(expected = UnsupportedOperationException.class) 24 | public void testOf() 25 | { 26 | ImmutableList list = ImmutableList.of(1, 2, 3); 27 | assertThat(list, notNullValue()); 28 | list.add(4); 29 | fail(); 30 | } 31 | 32 | @Test 33 | public void testCopy() 34 | { 35 | Integer[] array = {1, 2, 3, 4, 5}; 36 | System.out.println(ImmutableList.copyOf(array)); 37 | } 38 | 39 | @Test 40 | public void testBuilder() 41 | { 42 | ImmutableList list = ImmutableList.builder() 43 | .add(1) 44 | .add(2, 3, 4).addAll(Arrays.asList(5, 6)) 45 | .build(); 46 | System.out.println(list); 47 | } 48 | 49 | @Test 50 | public void testImmutableMap() 51 | { 52 | ImmutableMap map = ImmutableMap.builder().put("Oracle", "12c") 53 | .put("Mysql", "7.0").build(); 54 | System.out.println(map); 55 | try 56 | { 57 | map.put("Scala", "2.3.0"); 58 | fail(); 59 | } catch (Exception e) 60 | { 61 | assertThat(e instanceof UnsupportedOperationException, is(true)); 62 | } 63 | } 64 | } -------------------------------------------------------------------------------- /src/test/java/com/wangwenjun/guava/collections/ListsExampleTest.java: -------------------------------------------------------------------------------- 1 | package com.wangwenjun.guava.collections; 2 | 3 | import com.google.common.base.Joiner; 4 | import com.google.common.collect.FluentIterable; 5 | import com.google.common.collect.Lists; 6 | import org.junit.Test; 7 | 8 | import java.util.ArrayList; 9 | import java.util.HashSet; 10 | import java.util.List; 11 | 12 | import static org.hamcrest.core.IsEqual.equalTo; 13 | import static org.junit.Assert.assertThat; 14 | 15 | /*************************************** 16 | * @author:Alex Wang 17 | * @Date:2018/1/13 18 | * QQ: 532500648 19 | * QQ群:463962286 20 | ***************************************/ 21 | public class ListsExampleTest 22 | { 23 | 24 | @Test 25 | public void testCartesianProduct() 26 | { 27 | 28 | List> result = Lists.cartesianProduct( 29 | Lists.newArrayList("1", "2"), 30 | Lists.newArrayList("A", "B") 31 | ); 32 | System.out.println(result); 33 | } 34 | 35 | @Test 36 | public void testTransform() 37 | { 38 | ArrayList sourceList = Lists.newArrayList("Scala", "Guava", "Lists"); 39 | Lists.transform(sourceList, e -> e.toUpperCase()).forEach(System.out::println); 40 | 41 | 42 | } 43 | 44 | @Test 45 | public void testNewArrayListWithCapacity() 46 | { 47 | ArrayList result = Lists.newArrayListWithCapacity(10); 48 | result.add("x"); 49 | result.add("y"); 50 | result.add("z"); 51 | System.out.println(result); 52 | 53 | 54 | } 55 | 56 | //Apache NIFI 57 | //Hotworks HDF 58 | @Test 59 | public void testNewArrayListWithExpectedSize(){ 60 | Lists.newArrayListWithExpectedSize(5); 61 | } 62 | 63 | @Test 64 | public void testReverse(){ 65 | ArrayList list = Lists.newArrayList("1", "2", "3"); 66 | assertThat(Joiner.on(",").join(list),equalTo("1,2,3")); 67 | 68 | List result = Lists.reverse(list); 69 | assertThat(Joiner.on(",").join(result),equalTo("3,2,1")); 70 | } 71 | 72 | @Test 73 | public void testPartition(){ 74 | ArrayList list = Lists.newArrayList("1", "2", "3","4"); 75 | List> result = Lists.partition(list, 30); 76 | System.out.println(result.get(0)); 77 | } 78 | } -------------------------------------------------------------------------------- /src/test/java/com/wangwenjun/guava/collections/MapsExampleTest.java: -------------------------------------------------------------------------------- 1 | package com.wangwenjun.guava.collections; 2 | 3 | import com.google.common.collect.ImmutableMap; 4 | import com.google.common.collect.Lists; 5 | import com.google.common.collect.Maps; 6 | import com.google.common.collect.Sets; 7 | import org.junit.Test; 8 | 9 | import java.util.ArrayList; 10 | import java.util.Map; 11 | 12 | import static org.hamcrest.core.Is.is; 13 | import static org.junit.Assert.assertThat; 14 | 15 | /*************************************** 16 | * @author:Alex Wang 17 | * @Date:2018/1/14 18 | * QQ: 532500648 19 | * QQ群:463962286 20 | ***************************************/ 21 | public class MapsExampleTest 22 | { 23 | 24 | @Test 25 | public void testCreate() 26 | { 27 | ArrayList valueList = Lists.newArrayList("1", "2", "3"); 28 | ImmutableMap map = Maps.uniqueIndex(valueList, v -> v + "_key"); 29 | System.out.println(map); 30 | Map map2 = Maps.asMap(Sets.newHashSet("1", "2", "3"), k -> k + "_value"); 31 | System.out.println(map2); 32 | } 33 | 34 | @Test 35 | public void testTransform() 36 | { 37 | Map map = Maps.asMap(Sets.newHashSet("1", "2", "3"), k -> k + "_value"); 38 | Map newMap = Maps.transformValues(map, v -> v + "_transform"); 39 | System.out.println(newMap); 40 | assertThat(newMap.containsValue("1_value_transform"), is(true)); 41 | } 42 | 43 | @Test 44 | public void testFilter() 45 | { 46 | Map map = Maps.asMap(Sets.newHashSet("1", "2", "3"), k -> k + "_value"); 47 | Map newMap = Maps.filterKeys(map, k -> Lists.newArrayList("1", "2").contains(k)); 48 | assertThat(newMap.containsKey("3"), is(false)); 49 | } 50 | } -------------------------------------------------------------------------------- /src/test/java/com/wangwenjun/guava/collections/MultimapsExampleTest.java: -------------------------------------------------------------------------------- 1 | package com.wangwenjun.guava.collections; 2 | 3 | import com.google.common.collect.LinkedListMultimap; 4 | import com.google.common.collect.Maps; 5 | import com.google.common.collect.Multimaps; 6 | import org.junit.Test; 7 | 8 | import java.util.HashMap; 9 | 10 | import static org.hamcrest.core.IsEqual.equalTo; 11 | import static org.junit.Assert.*; 12 | 13 | /*************************************** 14 | * @author:Alex Wang 15 | * @Date:2018/1/14 16 | * QQ: 532500648 17 | * QQ群:463962286 18 | ***************************************/ 19 | public class MultimapsExampleTest 20 | { 21 | 22 | @Test 23 | public void testBasic() 24 | { 25 | LinkedListMultimap multipleMap = LinkedListMultimap.create(); 26 | HashMap hashMap = Maps.newHashMap(); 27 | hashMap.put("1", "1"); 28 | hashMap.put("1", "2"); 29 | assertThat(hashMap.size(), equalTo(1)); 30 | 31 | 32 | multipleMap.put("1", "1"); 33 | multipleMap.put("1", "2"); 34 | assertThat(multipleMap.size(), equalTo(2)); 35 | System.out.println(multipleMap.get("1")); 36 | } 37 | } -------------------------------------------------------------------------------- /src/test/java/com/wangwenjun/guava/collections/OrderingExampleTest.java: -------------------------------------------------------------------------------- 1 | package com.wangwenjun.guava.collections; 2 | 3 | import com.google.common.collect.Ordering; 4 | import org.junit.Test; 5 | 6 | import java.util.Arrays; 7 | import java.util.Collections; 8 | import java.util.List; 9 | 10 | import static org.hamcrest.core.Is.is; 11 | import static org.junit.Assert.*; 12 | 13 | /*************************************** 14 | * @author:Alex Wang 15 | * @Date:2018/1/15 16 | * QQ: 532500648 17 | * QQ群:463962286 18 | ***************************************/ 19 | public class OrderingExampleTest 20 | { 21 | 22 | @Test 23 | public void testJDKOrder() 24 | { 25 | List list = Arrays.asList(1, 5, 3, 8, 2); 26 | System.out.println(list); 27 | Collections.sort(list); 28 | System.out.println(list); 29 | } 30 | 31 | @Test(expected = NullPointerException.class) 32 | public void testJDKOrderIssue() 33 | { 34 | List list = Arrays.asList(1, 5, null, 3, 8, 2); 35 | System.out.println(list); 36 | Collections.sort(list); 37 | System.out.println(list); 38 | } 39 | 40 | @Test 41 | public void testOrderNaturalByNullFirst() 42 | { 43 | List list = Arrays.asList(1, 5, null, 3, 8, 2); 44 | Collections.sort(list, Ordering.natural().nullsFirst()); 45 | System.out.println(list); 46 | } 47 | 48 | @Test 49 | public void testOrderNaturalByNullLast() 50 | { 51 | List list = Arrays.asList(1, 5, null, 3, 8, 2); 52 | Collections.sort(list, Ordering.natural().nullsLast()); 53 | System.out.println(list); 54 | } 55 | 56 | @Test 57 | public void testOrderNatural() 58 | { 59 | List list = Arrays.asList(1, 5, 3, 8, 2); 60 | Collections.sort(list); 61 | assertThat(Ordering.natural().isOrdered(list), is(true)); 62 | } 63 | 64 | 65 | @Test 66 | public void testOrderReverse() 67 | { 68 | List list = Arrays.asList(1, 5, 3, 8, 2); 69 | Collections.sort(list, Ordering.natural().reverse()); 70 | System.out.println(list); 71 | } 72 | } -------------------------------------------------------------------------------- /src/test/java/com/wangwenjun/guava/collections/RangeExampleTest.java: -------------------------------------------------------------------------------- 1 | package com.wangwenjun.guava.collections; 2 | 3 | import com.google.common.collect.*; 4 | import org.junit.Test; 5 | 6 | import java.util.NavigableMap; 7 | import java.util.TreeMap; 8 | 9 | import static org.hamcrest.core.Is.is; 10 | import static org.hamcrest.core.IsEqual.equalTo; 11 | import static org.junit.Assert.*; 12 | 13 | /*************************************** 14 | * @author:Alex Wang 15 | * @Date:2018/1/14 16 | * QQ: 532500648 17 | * QQ群:463962286 18 | ***************************************/ 19 | public class RangeExampleTest 20 | { 21 | /** 22 | * {x|a<=x<=b} 23 | */ 24 | @Test 25 | public void testClosedRange() 26 | { 27 | Range closedRange = Range.closed(0, 9); 28 | System.out.println(closedRange); 29 | 30 | assertThat(closedRange.contains(5), is(true)); 31 | assertThat(closedRange.lowerEndpoint(), equalTo(0)); 32 | assertThat(closedRange.upperEndpoint(), equalTo(9)); 33 | } 34 | 35 | /** 36 | * {x|a openRange = Range.open(0, 9); 42 | System.out.println(openRange); 43 | 44 | assertThat(openRange.contains(5), is(true)); 45 | 46 | assertThat(openRange.lowerEndpoint(), equalTo(0)); 47 | assertThat(openRange.upperEndpoint(), equalTo(9)); 48 | assertThat(openRange.contains(0), is(false)); 49 | assertThat(openRange.contains(9), is(false)); 50 | } 51 | 52 | /** 53 | * {x|a openClosedRange = Range.openClosed(0, 9); 59 | System.out.println(openClosedRange); 60 | 61 | assertThat(openClosedRange.contains(5), is(true)); 62 | 63 | assertThat(openClosedRange.lowerEndpoint(), equalTo(0)); 64 | assertThat(openClosedRange.upperEndpoint(), equalTo(9)); 65 | assertThat(openClosedRange.contains(0), is(false)); 66 | assertThat(openClosedRange.contains(9), is(true)); 67 | } 68 | 69 | 70 | /** 71 | * {x|a<=x closedOpen = Range.closedOpen(0, 9); 77 | System.out.println(closedOpen); 78 | 79 | assertThat(closedOpen.contains(5), is(true)); 80 | 81 | assertThat(closedOpen.lowerEndpoint(), equalTo(0)); 82 | assertThat(closedOpen.upperEndpoint(), equalTo(9)); 83 | assertThat(closedOpen.contains(0), is(true)); 84 | assertThat(closedOpen.contains(9), is(false)); 85 | } 86 | 87 | /** 88 | * {x|x>a} 89 | */ 90 | @Test 91 | public void testGreaterThan() 92 | { 93 | Range range = Range.greaterThan(10); 94 | assertThat(range.contains(10), is(false)); 95 | assertThat(range.contains(Integer.MAX_VALUE), is(true)); 96 | } 97 | 98 | @Test 99 | public void testMapRange() 100 | { 101 | TreeMap treeMap = Maps.newTreeMap(); 102 | 103 | treeMap.put("Scala", 1); 104 | treeMap.put("Guava", 2); 105 | treeMap.put("Java", 3); 106 | treeMap.put("Kafka", 4); 107 | System.out.println(treeMap); 108 | 109 | NavigableMap result = Maps.subMap(treeMap, Range.openClosed("Guava", "Java")); 110 | System.out.println(result); 111 | } 112 | 113 | @Test 114 | public void testOtherMethod() 115 | { 116 | Range atLeastRange = Range.atLeast(2); 117 | System.out.println(atLeastRange); 118 | assertThat(atLeastRange.contains(2), is(true)); 119 | System.out.println(Range.lessThan(10)); 120 | System.out.println(Range.atMost(5)); 121 | System.out.println(Range.all()); 122 | System.out.println(Range.downTo(10, BoundType.CLOSED)); 123 | System.out.println(Range.upTo(10, BoundType.CLOSED)); 124 | } 125 | 126 | @Test 127 | public void testRangeMap() 128 | { 129 | RangeMap gradeScale = TreeRangeMap.create(); 130 | gradeScale.put(Range.closed(0, 60), "E"); 131 | gradeScale.put(Range.closed(61, 70), "D"); 132 | gradeScale.put(Range.closed(71, 80), "C"); 133 | gradeScale.put(Range.closed(81, 90), "B"); 134 | gradeScale.put(Range.closed(91, 100), "A"); 135 | 136 | assertThat(gradeScale.get(77), equalTo("C")); 137 | } 138 | } -------------------------------------------------------------------------------- /src/test/java/com/wangwenjun/guava/collections/SetsExampleTest.java: -------------------------------------------------------------------------------- 1 | package com.wangwenjun.guava.collections; 2 | 3 | import com.google.common.collect.Lists; 4 | import com.google.common.collect.Sets; 5 | import org.junit.Test; 6 | 7 | import java.util.ArrayList; 8 | import java.util.HashSet; 9 | import java.util.List; 10 | import java.util.Set; 11 | 12 | import static org.hamcrest.core.IsEqual.equalTo; 13 | import static org.junit.Assert.assertThat; 14 | 15 | /*************************************** 16 | * @author:Alex Wang 17 | * @Date:2018/1/14 18 | * QQ: 532500648 19 | * QQ群:463962286 20 | ***************************************/ 21 | public class SetsExampleTest 22 | { 23 | 24 | @Test 25 | public void testCreate() 26 | { 27 | HashSet set = Sets.newHashSet(1, 2, 3); 28 | assertThat(set.size(), equalTo(3)); 29 | 30 | ArrayList list = Lists.newArrayList(1, 1, 2, 3); 31 | assertThat(list.size(), equalTo(4)); 32 | 33 | HashSet set2 = Sets.newHashSet(list); 34 | assertThat(set2.size(), equalTo(3)); 35 | 36 | 37 | } 38 | 39 | @Test 40 | public void testCartesianProduct() 41 | { 42 | 43 | Set> set = Sets.cartesianProduct(Sets.newHashSet(1, 2), Sets.newHashSet(3, 4), Sets.newHashSet(5, 6)); 44 | 45 | System.out.println(set); 46 | 47 | 48 | } 49 | 50 | @Test 51 | public void testCombinations() 52 | { 53 | HashSet set = Sets.newHashSet(1, 2, 3); 54 | Set> combinations = Sets.combinations(set, 2); 55 | combinations.forEach(System.out::println); 56 | } 57 | 58 | @Test 59 | public void testDiff() 60 | { 61 | HashSet set1 = Sets.newHashSet(1, 2, 3); 62 | HashSet set2 = Sets.newHashSet(1, 4, 6); 63 | Sets.SetView diffResult1 = Sets.difference(set1, set2); 64 | System.out.println(diffResult1); 65 | Sets.SetView diffResult2 = Sets.difference(set2, set1); 66 | System.out.println(diffResult2); 67 | 68 | 69 | } 70 | 71 | @Test 72 | public void testIntersection() 73 | { 74 | HashSet set1 = Sets.newHashSet(1, 2, 3); 75 | HashSet set2 = Sets.newHashSet(1, 4, 6); 76 | Sets.intersection(set1, set2).forEach(System.out::println); 77 | } 78 | 79 | @Test 80 | public void testUnionSection() 81 | { 82 | HashSet set1 = Sets.newHashSet(1, 2, 3); 83 | HashSet set2 = Sets.newHashSet(1, 4, 6); 84 | Sets.union(set1, set2).forEach(System.out::println); 85 | } 86 | } 87 | -------------------------------------------------------------------------------- /src/test/java/com/wangwenjun/guava/collections/TableExampleTest.java: -------------------------------------------------------------------------------- 1 | package com.wangwenjun.guava.collections; 2 | 3 | import com.google.common.collect.HashBasedTable; 4 | import com.google.common.collect.Table; 5 | import org.junit.Test; 6 | 7 | import java.util.Map; 8 | import java.util.Set; 9 | 10 | import static org.hamcrest.core.Is.is; 11 | import static org.hamcrest.core.IsEqual.equalTo; 12 | import static org.junit.Assert.*; 13 | 14 | /*************************************** 15 | * @author:Alex Wang 16 | * @Date:2018/1/14 17 | * QQ: 532500648 18 | * QQ群:463962286 19 | ***************************************/ 20 | public class TableExampleTest 21 | { 22 | //ArrayTable 23 | //TreeBaseTable 24 | //HashBaseTable 25 | //ImmutableTable 26 | 27 | @Test 28 | public void test() 29 | { 30 | Table table = HashBasedTable.create(); 31 | table.put("Language", "Java", "1.8"); 32 | table.put("Language", "Scala", "2.3"); 33 | table.put("Database", "Oracle", "12C"); 34 | table.put("Database", "Mysql", "7.0"); 35 | System.out.println(table); 36 | 37 | Map language = table.row("Language"); 38 | assertThat(language.containsKey("Java"), is(true)); 39 | //Map> 40 | assertThat(table.row("Language").get("Java"), equalTo("1.8")); 41 | Map result = table.column("Java"); 42 | System.out.println(result); 43 | 44 | Set> cells = table.cellSet(); 45 | System.out.println(cells); 46 | } 47 | } -------------------------------------------------------------------------------- /src/test/java/com/wangwenjun/guava/io/BaseEncodingTest.java: -------------------------------------------------------------------------------- 1 | package com.wangwenjun.guava.io; 2 | 3 | import com.google.common.io.BaseEncoding; 4 | import org.junit.Test; 5 | 6 | import static org.hamcrest.core.IsEqual.equalTo; 7 | import static org.junit.Assert.assertThat; 8 | 9 | /*************************************** 10 | * @author:Alex Wang 11 | * @Date:2017/10/15 12 | * @QQ: 532500648 13 | ***************************************/ 14 | public class BaseEncodingTest { 15 | @Test 16 | public void testBase64Encode() { 17 | BaseEncoding baseEncoding = BaseEncoding.base64(); 18 | System.out.println(baseEncoding.encode("hello".getBytes())); 19 | System.out.println(baseEncoding.encode("a".getBytes())); 20 | } 21 | 22 | @Test 23 | public void testBase64Decode() { 24 | BaseEncoding baseEncoding = BaseEncoding.base64(); 25 | System.out.println(new String(baseEncoding.decode("aGVsbG8="))); 26 | } 27 | 28 | @Test 29 | public void testMyBase64Encode() { 30 | System.out.println(Base64.encode("hello")); 31 | assertThat(Base64.encode("hello"), equalTo(BaseEncoding.base64().encode("hello".getBytes()))); 32 | assertThat(Base64.encode("alex"), equalTo(BaseEncoding.base64().encode("alex".getBytes()))); 33 | assertThat(Base64.encode("wangwenjun"), equalTo(BaseEncoding.base64().encode("wangwenjun".getBytes()))); 34 | assertThat(Base64.encode("scala"), equalTo(BaseEncoding.base64().encode("scala".getBytes()))); 35 | assertThat(Base64.encode("kafka"), equalTo(BaseEncoding.base64().encode("kafka".getBytes()))); 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /src/test/java/com/wangwenjun/guava/io/ByteSinkTest.java: -------------------------------------------------------------------------------- 1 | package com.wangwenjun.guava.io; 2 | 3 | import com.google.common.hash.HashFunction; 4 | import com.google.common.hash.Hashing; 5 | import com.google.common.io.ByteSink; 6 | import com.google.common.io.ByteSource; 7 | import com.google.common.io.Files; 8 | import org.junit.Test; 9 | 10 | import java.io.File; 11 | import java.io.IOException; 12 | 13 | 14 | import static org.hamcrest.core.Is.is; 15 | import static org.hamcrest.core.IsEqual.equalTo; 16 | import static org.junit.Assert.assertThat; 17 | 18 | /*************************************** 19 | * @author:Alex Wang 20 | * @Date:2017/10/14 21 | * @QQ: 532500648 22 | ***************************************/ 23 | public class ByteSinkTest { 24 | 25 | private final String path = "C:\\Users\\wangwenjun\\IdeaProjects\\guava_programming\\src\\test\\resources\\io\\ByteSinkTest.dat"; 26 | 27 | @Test 28 | public void testByteSink() throws IOException { 29 | File file = new File(path); 30 | file.deleteOnExit(); 31 | ByteSink byteSink = Files.asByteSink(file); 32 | byte[] bytes = {0x01, 0x02}; 33 | byteSink.write(bytes); 34 | 35 | byte[] expected = Files.toByteArray(file); 36 | 37 | assertThat(expected, is(bytes)); 38 | } 39 | 40 | @Test 41 | public void testFromSourceToSink() throws IOException { 42 | String source = "C:\\Users\\wangwenjun\\IdeaProjects\\guava_programming\\src\\test\\resources\\io\\files.PNG"; 43 | String target = "C:\\Users\\wangwenjun\\IdeaProjects\\guava_programming\\src\\test\\resources\\io\\files-2.PNG"; 44 | File sourceFile = new File(source); 45 | File targetFile = new File(target); 46 | targetFile.deleteOnExit(); 47 | ByteSource byteSource = Files.asByteSource(sourceFile); 48 | byteSource.copyTo(Files.asByteSink(targetFile)); 49 | 50 | assertThat(targetFile.exists(), equalTo(true)); 51 | 52 | assertThat( 53 | Files.asByteSource(sourceFile).hash(Hashing.sha256()).toString(), 54 | equalTo(Files.asByteSource(targetFile).hash(Hashing.sha256()).toString()) 55 | ); 56 | 57 | 58 | } 59 | } 60 | -------------------------------------------------------------------------------- /src/test/java/com/wangwenjun/guava/io/ByteSourceTest.java: -------------------------------------------------------------------------------- 1 | package com.wangwenjun.guava.io; 2 | 3 | import com.google.common.io.ByteSource; 4 | import com.google.common.io.Files; 5 | import org.junit.Test; 6 | 7 | import java.io.File; 8 | import java.io.IOException; 9 | 10 | import static org.hamcrest.core.Is.is; 11 | import static org.junit.Assert.assertThat; 12 | 13 | /*************************************** 14 | * @author:Alex Wang 15 | * @Date:2017/10/14 16 | * @QQ: 532500648 17 | ***************************************/ 18 | public class ByteSourceTest { 19 | 20 | private final String path = "C:\\Users\\wangwenjun\\IdeaProjects\\guava_programming\\src\\test\\resources\\io\\files.PNG"; 21 | 22 | @Test 23 | public void testAsByteSource() throws IOException { 24 | File file = new File(path); 25 | ByteSource byteSource = Files.asByteSource(file); 26 | byte[] readBytes = byteSource.read(); 27 | assertThat(readBytes, is(Files.toByteArray(file))); 28 | } 29 | 30 | @Test 31 | public void testSliceByteSource() throws IOException { 32 | ByteSource byteSource = ByteSource.wrap(new byte[]{0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09}); 33 | ByteSource sliceByteSource = byteSource.slice(5, 5); 34 | byte[] bytes = sliceByteSource.read(); 35 | for (byte b : bytes) { 36 | System.out.println(b); 37 | } 38 | } 39 | 40 | } -------------------------------------------------------------------------------- /src/test/java/com/wangwenjun/guava/io/CharSinkTest.java: -------------------------------------------------------------------------------- 1 | package com.wangwenjun.guava.io; 2 | 3 | import org.junit.Test; 4 | 5 | /*************************************** 6 | * @author:Alex Wang 7 | * @Date:2017/10/14 8 | * @QQ: 532500648 9 | ***************************************/ 10 | public class CharSinkTest { 11 | 12 | /** 13 | * CharSource---->Reader 14 | *

15 | * CharSink------>Writer 16 | */ 17 | @Test 18 | public void testCharSink() { 19 | 20 | } 21 | 22 | } -------------------------------------------------------------------------------- /src/test/java/com/wangwenjun/guava/io/CharSourceTest.java: -------------------------------------------------------------------------------- 1 | package com.wangwenjun.guava.io; 2 | 3 | import com.google.common.collect.ImmutableList; 4 | import com.google.common.io.CharSource; 5 | import com.google.common.io.Files; 6 | import org.junit.Test; 7 | 8 | import java.io.IOException; 9 | import java.io.InputStreamReader; 10 | 11 | import static org.hamcrest.core.IsEqual.equalTo; 12 | import static org.junit.Assert.assertThat; 13 | 14 | /*************************************** 15 | * @author:Alex Wang 16 | * @Date:2017/10/14 17 | * @QQ: 532500648 18 | ***************************************/ 19 | public class CharSourceTest { 20 | 21 | @Test 22 | public void testCharSourceWrap() throws IOException { 23 | CharSource charSource = CharSource.wrap("i am the CharSource"); 24 | String resultAsRead = charSource.read(); 25 | assertThat(resultAsRead, equalTo("i am the CharSource")); 26 | ImmutableList list = charSource.readLines(); 27 | assertThat(list.size(), equalTo(1)); 28 | assertThat(charSource.length(), equalTo(19L)); 29 | assertThat(charSource.isEmpty(), equalTo(false)); 30 | assertThat(charSource.lengthIfKnown().get(), equalTo(19L)); 31 | } 32 | 33 | @Test 34 | public void testConcat() throws IOException { 35 | CharSource charSource = CharSource.concat( 36 | CharSource.wrap("i am the CharSource1\n"), 37 | CharSource.wrap("i am the CharSource2") 38 | ); 39 | 40 | System.out.println(charSource.readLines().size()); 41 | charSource.lines().forEach(System.out::println); 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /src/test/java/com/wangwenjun/guava/io/CharStreamsTest.java: -------------------------------------------------------------------------------- 1 | package com.wangwenjun.guava.io; 2 | 3 | import org.junit.Test; 4 | 5 | /*************************************** 6 | * @author:Alex Wang 7 | * @Date:2017/10/14 8 | * @QQ: 532500648 9 | ***************************************/ 10 | public class CharStreamsTest { 11 | 12 | @Test 13 | public void testCharStreams() { 14 | 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /src/test/java/com/wangwenjun/guava/io/CloserTest.java: -------------------------------------------------------------------------------- 1 | package com.wangwenjun.guava.io; 2 | 3 | import com.google.common.io.ByteSource; 4 | import com.google.common.io.Closer; 5 | import com.google.common.io.Files; 6 | import org.junit.Test; 7 | 8 | import java.io.File; 9 | import java.io.IOException; 10 | import java.io.InputStream; 11 | 12 | /*************************************** 13 | * @author:Alex Wang 14 | * @Date:2017/10/14 15 | * @QQ: 532500648 16 | ***************************************/ 17 | public class CloserTest { 18 | 19 | @Test 20 | public void testCloser() throws IOException { 21 | ByteSource byteSource = Files.asByteSource(new File("C:\\Users\\wangwenjun\\IdeaProjects\\guava_programming\\src\\test\\resources\\io\\files.PNG")); 22 | Closer closer = Closer.create(); 23 | try { 24 | InputStream inputStream = closer.register(byteSource.openStream()); 25 | } catch (Throwable e) { 26 | throw closer.rethrow(e); 27 | } finally { 28 | closer.close(); 29 | } 30 | } 31 | 32 | @Test(expected = RuntimeException.class) 33 | public void testTryCatchFinally() { 34 | try { 35 | 36 | System.out.println("work area."); 37 | throw new IllegalArgumentException(); 38 | } catch (Exception e) { 39 | System.out.println("exception area"); 40 | throw new RuntimeException(); 41 | } finally { 42 | System.out.println("finally area"); 43 | } 44 | } 45 | 46 | @Test 47 | public void testTryCatch() { 48 | Throwable t = null; 49 | try { 50 | throw new RuntimeException("1"); 51 | } catch (Exception e) { 52 | t = e; 53 | throw e; 54 | } finally { 55 | try { 56 | //close 57 | throw new RuntimeException("2"); 58 | } catch (Exception e) { 59 | t.addSuppressed(e); 60 | } 61 | } 62 | } 63 | } 64 | -------------------------------------------------------------------------------- /src/test/java/com/wangwenjun/guava/io/FilesTest.java: -------------------------------------------------------------------------------- 1 | package com.wangwenjun.guava.io; 2 | 3 | import com.google.common.base.Charsets; 4 | import com.google.common.base.Joiner; 5 | import com.google.common.collect.FluentIterable; 6 | import com.google.common.hash.HashCode; 7 | import com.google.common.hash.Hashing; 8 | import com.google.common.io.*; 9 | import org.junit.After; 10 | import org.junit.Test; 11 | 12 | import java.io.File; 13 | import java.io.IOException; 14 | import java.nio.file.Paths; 15 | import java.nio.file.StandardCopyOption; 16 | import java.util.ArrayList; 17 | import java.util.List; 18 | 19 | import static org.hamcrest.core.IsEqual.equalTo; 20 | import static org.junit.Assert.assertThat; 21 | 22 | 23 | /*************************************** 24 | * @author:Alex Wang 25 | * @Date:2017/10/14 26 | * @QQ: 532500648 27 | ***************************************/ 28 | public class FilesTest { 29 | 30 | private final String SOURCE_FILE = "C:\\Users\\wangwenjun\\IdeaProjects\\guava_programming\\src\\test\\resources\\io\\source.txt"; 31 | private final String TARGET_FILE = "C:\\Users\\wangwenjun\\IdeaProjects\\guava_programming\\src\\test\\resources\\io\\target.txt"; 32 | 33 | /** 34 | * TODO alex will finish this in the future. 35 | * 36 | * @throws IOException 37 | */ 38 | @Test 39 | public void testCopyFileWithGuava() throws IOException { 40 | File targetFile = new File(TARGET_FILE); 41 | File sourceFile = new File(SOURCE_FILE); 42 | Files.copy(sourceFile, targetFile); 43 | assertThat(targetFile.exists(), equalTo(true)); 44 | HashCode sourceHashCode = Files.asByteSource(sourceFile).hash(Hashing.sha256()); 45 | HashCode targetHashCode = Files.asByteSource(targetFile).hash(Hashing.sha256()); 46 | assertThat(sourceHashCode.toString(), equalTo(targetHashCode.toString())); 47 | } 48 | 49 | @Test 50 | public void testCopyFileWithJDKNio2() throws IOException { 51 | java.nio.file.Files.copy( 52 | Paths.get("C:\\Users\\wangwenjun\\IdeaProjects\\guava_programming\\src\\test\\resources", "io", "source.txt"), 53 | Paths.get("C:\\Users\\wangwenjun\\IdeaProjects\\guava_programming\\src\\test\\resources", "io", "target.txt"), 54 | StandardCopyOption.REPLACE_EXISTING 55 | ); 56 | File targetFile = new File(TARGET_FILE); 57 | 58 | assertThat(targetFile.exists(), equalTo(true)); 59 | } 60 | 61 | @Test 62 | public void testMoveFile() throws IOException { 63 | try { 64 | //prepare for data. 65 | Files.move(new File(SOURCE_FILE), new File(TARGET_FILE)); 66 | assertThat(new File(TARGET_FILE).exists(), equalTo(true)); 67 | assertThat(new File(SOURCE_FILE).exists(), equalTo(false)); 68 | } finally { 69 | Files.move(new File(TARGET_FILE), new File(SOURCE_FILE)); 70 | } 71 | } 72 | 73 | @Test 74 | public void testToString() throws IOException { 75 | 76 | final String expectedString = "today we will share the guava io knowledge.\n" + 77 | "but only for the basic usage. if you wanted to get the more details information\n" + 78 | "please read the guava document or source code.\n" + 79 | "\n" + 80 | "The guava source code is very cleanly and nice."; 81 | 82 | List strings = Files.readLines(new File(SOURCE_FILE), Charsets.UTF_8); 83 | 84 | String result = Joiner.on("\n").join(strings); 85 | assertThat(result, equalTo(expectedString)); 86 | } 87 | 88 | @Test 89 | public void testToProcessString() throws IOException { 90 | /*Files.readLines(new File(SOURCE_FILE), Charsets.UTF_8, new LineProcessor() { 91 | })Files.as;*/ 92 | /** 93 | * [43, 79, 46, 0, 47] 94 | */ 95 | LineProcessor> lineProcessor = new LineProcessor>() { 96 | 97 | private final List lengthList = new ArrayList<>(); 98 | 99 | @Override 100 | public boolean processLine(String line) throws IOException { 101 | if (line.length() == 0) return false; 102 | lengthList.add(line.length()); 103 | return true; 104 | } 105 | 106 | @Override 107 | public List getResult() { 108 | return lengthList; 109 | } 110 | }; 111 | List result = Files.asCharSource(new File(SOURCE_FILE), Charsets.UTF_8).readLines(lineProcessor); 112 | 113 | System.out.println(result); 114 | } 115 | 116 | @Test 117 | public void testFileSha() throws IOException { 118 | 119 | File file = new File(SOURCE_FILE); 120 | // Files.hash(file, Hashing.goodFastHash(128)); 121 | HashCode hashCode = Files.asByteSource(file).hash(Hashing.sha256()); 122 | System.out.println(hashCode); 123 | } 124 | 125 | @Test 126 | public void testFileWrite() throws IOException { 127 | String testPath = "C:\\Users\\wangwenjun\\IdeaProjects\\guava_programming\\src\\test\\resources\\io\\testFileWrite.txt"; 128 | File testFile = new File(testPath); 129 | testFile.deleteOnExit(); 130 | String content1 = "content 1"; 131 | Files.asCharSink(testFile, Charsets.UTF_8).write(content1); 132 | String actully = Files.asCharSource(testFile, Charsets.UTF_8).read(); 133 | 134 | assertThat(actully, equalTo(content1)); 135 | 136 | String content2 = "content 2"; 137 | Files.asCharSink(testFile, Charsets.UTF_8).write(content2); 138 | actully = Files.asCharSource(testFile, Charsets.UTF_8).read(); 139 | assertThat(actully, equalTo(content2)); 140 | } 141 | 142 | @Test 143 | public void testFileAppend() throws IOException { 144 | String testPath = "C:\\Users\\wangwenjun\\IdeaProjects\\guava_programming\\src\\test\\resources\\io\\testFileAppend.txt"; 145 | File testFile = new File(testPath); 146 | testFile.deleteOnExit(); 147 | CharSink charSink = Files.asCharSink(testFile, Charsets.UTF_8, FileWriteMode.APPEND); 148 | charSink.write("content1"); 149 | String actullay = Files.asCharSource(testFile, Charsets.UTF_8).read(); 150 | assertThat(actullay, equalTo("content1")); 151 | 152 | charSink.write("content2"); 153 | actullay = Files.asCharSource(testFile, Charsets.UTF_8).read(); 154 | assertThat(actullay, equalTo("content1content2")); 155 | } 156 | 157 | @Test 158 | public void testTouchFile() throws IOException { 159 | File touchFile = new File("C:\\Users\\wangwenjun\\IdeaProjects\\guava_programming\\src\\test\\resources\\io\\touch.txt"); 160 | touchFile.deleteOnExit(); 161 | Files.touch(touchFile); 162 | assertThat(touchFile.exists(), equalTo(true)); 163 | } 164 | 165 | @Test 166 | public void testRecursive() { 167 | List list = new ArrayList<>(); 168 | this.recursiveList(new File("C:\\Users\\wangwenjun\\IdeaProjects\\guava_programming\\src\\main"), list); 169 | list.forEach(System.out::println); 170 | } 171 | 172 | private void recursiveList(File root, List fileList) { 173 | /*if (root.isHidden()) 174 | return; 175 | fileList.add(root); 176 | if (!root.isFile()) { 177 | File[] files = root.listFiles(); 178 | for (File f : files) { 179 | recursiveList(f, fileList); 180 | } 181 | }*/ 182 | 183 | 184 | if (root.isHidden()) return; 185 | if (root.isFile()) 186 | fileList.add(root); 187 | else { 188 | File[] files = root.listFiles(); 189 | for (File f : files) { 190 | recursiveList(f, fileList); 191 | } 192 | } 193 | } 194 | 195 | @Test 196 | public void testTreeFilesPreOrderTraversal() { 197 | File root = new File("C:\\Users\\wangwenjun\\IdeaProjects\\guava_programming\\src\\main"); 198 | // FluentIterable files = Files.fileTreeTraverser().preOrderTraversal(root); 199 | FluentIterable files = Files.fileTreeTraverser().preOrderTraversal(root).filter(File::isFile); 200 | files.stream().forEach(System.out::println); 201 | } 202 | 203 | @Test 204 | public void testTreeFilesPostOrderTraversal() { 205 | File root = new File("C:\\Users\\wangwenjun\\IdeaProjects\\guava_programming\\src\\main"); 206 | FluentIterable files = Files.fileTreeTraverser().postOrderTraversal(root); 207 | files.stream().forEach(System.out::println); 208 | } 209 | 210 | @Test 211 | public void testTreeFilesBreadthFirstTraversal() { 212 | File root = new File("C:\\Users\\wangwenjun\\IdeaProjects\\guava_programming\\src\\main"); 213 | FluentIterable files = Files.fileTreeTraverser().breadthFirstTraversal(root); 214 | files.stream().forEach(System.out::println); 215 | } 216 | 217 | @Test 218 | public void testTreeFilesChild() { 219 | File root = new File("C:\\Users\\wangwenjun\\IdeaProjects\\guava_programming\\src\\main"); 220 | Iterable children = Files.fileTreeTraverser().children(root); 221 | 222 | children.forEach(System.out::println); 223 | } 224 | 225 | @After 226 | public void tearDown() { 227 | File targetFile = new File(TARGET_FILE); 228 | if (targetFile.exists()) 229 | targetFile.delete(); 230 | } 231 | } 232 | -------------------------------------------------------------------------------- /src/test/java/com/wangwenjun/guava/utilities/JoinerTest.java: -------------------------------------------------------------------------------- 1 | package com.wangwenjun.guava.utilities; 2 | 3 | import com.google.common.base.Joiner; 4 | import com.google.common.io.Files; 5 | import org.junit.Test; 6 | 7 | import java.io.File; 8 | import java.io.FileWriter; 9 | import java.io.IOException; 10 | import java.util.Arrays; 11 | import java.util.List; 12 | import java.util.Map; 13 | 14 | import static com.google.common.collect.ImmutableMap.of; 15 | import static java.util.stream.Collectors.joining; 16 | import static org.hamcrest.core.IsEqual.equalTo; 17 | import static org.hamcrest.core.IsSame.sameInstance; 18 | import static org.junit.Assert.assertThat; 19 | import static org.junit.Assert.fail; 20 | 21 | /*************************************** 22 | * @author:Alex Wang 23 | * @Date:2017/10/6 24 | * @QQ: 532500648 25 | ***************************************/ 26 | public class JoinerTest { 27 | 28 | 29 | private final List stringList = Arrays.asList( 30 | "Google", "Guava", "Java", "Scala", "Kafka" 31 | ); 32 | 33 | private final List stringListWithNullValue = Arrays.asList( 34 | "Google", "Guava", "Java", "Scala", null 35 | ); 36 | 37 | private final Map stringMap = of("Hello", "Guava", "Java", "Scala"); 38 | 39 | 40 | private final String targetFileName = "G:\\Teaching\\汪文君Google Guava实战视频\\guava-joiner.txt"; 41 | private final String targetFileNameToMap = "G:\\Teaching\\汪文君Google Guava实战视频\\guava-joiner-map.txt"; 42 | 43 | @Test 44 | public void testJoinOnJoin() { 45 | String result = Joiner.on("#").join(stringList); 46 | assertThat(result, equalTo("Google#Guava#Java#Scala#Kafka")); 47 | } 48 | 49 | @Test(expected = NullPointerException.class) 50 | public void testJoinOnJoinWithNullValue() { 51 | String result = Joiner.on("#").join(stringListWithNullValue); 52 | assertThat(result, equalTo("Google#Guava#Java#Scala#Kafka")); 53 | } 54 | 55 | @Test 56 | public void testJoinOnJoinWithNullValueButSkip() { 57 | String result = Joiner.on("#").skipNulls().join(stringListWithNullValue); 58 | assertThat(result, equalTo("Google#Guava#Java#Scala")); 59 | } 60 | 61 | 62 | @Test 63 | public void testJoin_On_Join_WithNullValue_UseDefaultValue() { 64 | String result = Joiner.on("#").useForNull("DEFAULT").join(stringListWithNullValue); 65 | assertThat(result, equalTo("Google#Guava#Java#Scala#DEFAULT")); 66 | } 67 | 68 | @Test 69 | public void testJoin_On_Append_To_StringBuilder() { 70 | final StringBuilder builder = new StringBuilder(); 71 | StringBuilder resultBuilder = Joiner.on("#").useForNull("DEFAULT").appendTo(builder, stringListWithNullValue); 72 | assertThat(resultBuilder, sameInstance(builder)); 73 | assertThat(resultBuilder.toString(), equalTo("Google#Guava#Java#Scala#DEFAULT")); 74 | assertThat(builder.toString(), equalTo("Google#Guava#Java#Scala#DEFAULT")); 75 | } 76 | 77 | @Test 78 | public void testJoin_On_Append_To_Writer() { 79 | 80 | try (FileWriter writer = new FileWriter(new File(targetFileName))) { 81 | Joiner.on("#").useForNull("DEFAULT").appendTo(writer, stringListWithNullValue); 82 | assertThat(Files.isFile().test(new File(targetFileName)), equalTo(true)); 83 | } catch (IOException e) { 84 | fail("append to the writer occur fetal error."); 85 | } 86 | } 87 | 88 | @Test 89 | public void testJoiningByStreamSkipNullValues() { 90 | String result = stringListWithNullValue.stream().filter(item -> item != null && !item.isEmpty()).collect(joining("#")); 91 | assertThat(result, equalTo("Google#Guava#Java#Scala")); 92 | } 93 | 94 | 95 | @Test 96 | public void testJoiningByStreamWithDefaultValue() { 97 | String result = stringListWithNullValue.stream().map(this::defaultValue).collect(joining("#")); 98 | assertThat(result, equalTo("Google#Guava#Java#Scala#DEFAULT")); 99 | } 100 | 101 | private String defaultValue(final String item) { 102 | return item == null || item.isEmpty() ? "DEFAULT" : item; 103 | } 104 | 105 | @Test 106 | public void testJoinOnWithMap() { 107 | assertThat(Joiner.on('#').withKeyValueSeparator("=").join(stringMap), equalTo("Hello=Guava#Java=Scala")); 108 | } 109 | 110 | 111 | @Test 112 | public void testJoinOnWithMapToAppendable() { 113 | try (FileWriter writer = new FileWriter(new File(targetFileNameToMap))) { 114 | Joiner.on("#").withKeyValueSeparator("=").appendTo(writer, stringMap); 115 | assertThat(Files.isFile().test(new File(targetFileNameToMap)), equalTo(true)); 116 | } catch (IOException e) { 117 | fail("append to the writer occur fetal error."); 118 | } 119 | } 120 | } 121 | -------------------------------------------------------------------------------- /src/test/java/com/wangwenjun/guava/utilities/PreconditionsTest.java: -------------------------------------------------------------------------------- 1 | package com.wangwenjun.guava.utilities; 2 | 3 | import com.google.common.base.Preconditions; 4 | import com.google.common.collect.ImmutableList; 5 | import org.junit.Test; 6 | 7 | import java.util.List; 8 | import java.util.Objects; 9 | 10 | import static org.hamcrest.core.Is.is; 11 | import static org.hamcrest.core.IsEqual.equalTo; 12 | import static org.junit.Assert.assertThat; 13 | import static org.junit.Assert.fail; 14 | 15 | /*************************************** 16 | * @author:Alex Wang 17 | * @Date:2017/10/7 18 | * @QQ: 532500648 19 | ***************************************/ 20 | 21 | /** 22 | * Precondition 23 | * Objects 24 | * assert key word(statement) 25 | */ 26 | public class PreconditionsTest { 27 | 28 | 29 | @Test(expected = NullPointerException.class) 30 | public void testCheckNotNull() { 31 | checkNotNull(null); 32 | } 33 | 34 | @Test 35 | public void testCheckNotNullWithMessage() { 36 | try { 37 | checkNotNullWithMessage(null); 38 | } catch (Exception e) { 39 | assertThat(e, is(NullPointerException.class)); 40 | assertThat(e.getMessage(), equalTo("The list should not be null")); 41 | } 42 | } 43 | 44 | @Test 45 | public void testCheckNotNullWithFormatMessage() { 46 | try { 47 | checkNotNullWithFormatMessage(null); 48 | } catch (Exception e) { 49 | assertThat(e, is(NullPointerException.class)); 50 | assertThat(e.getMessage(), equalTo("The list should not be null and the size must be 2")); 51 | } 52 | } 53 | 54 | @Test 55 | public void testCheckArguments() { 56 | final String type = "A"; 57 | try { 58 | Preconditions.checkArgument(type.equals("B")); 59 | } catch (Exception e) { 60 | assertThat(e, is(IllegalArgumentException.class)); 61 | } 62 | } 63 | 64 | @Test 65 | public void testCheckState() { 66 | try { 67 | final String state = "A"; 68 | Preconditions.checkState(state.equals("B"), "The state is illegal."); 69 | fail("should not process to here."); 70 | } catch (Exception e) { 71 | assertThat(e, is(IllegalStateException.class)); 72 | } 73 | } 74 | 75 | @Test 76 | public void testCheckIndex() { 77 | try { 78 | List list = ImmutableList.of(); 79 | Preconditions.checkElementIndex(10, list.size()); 80 | } catch (Exception e) { 81 | assertThat(e, is(IndexOutOfBoundsException.class)); 82 | } 83 | } 84 | 85 | @Test(expected = NullPointerException.class) 86 | public void testByObjects() { 87 | Objects.requireNonNull(null); 88 | } 89 | 90 | @Test(expected = AssertionError.class) 91 | public void testAssert() { 92 | List list = null; 93 | assert list != null; 94 | } 95 | 96 | @Test 97 | public void testAssertWithMessage() { 98 | try { 99 | List list = null; 100 | assert list != null : "The list should not be null."; 101 | } catch (Error e) { 102 | assertThat(e, is(AssertionError.class)); 103 | assertThat(e.getMessage(), equalTo("The list should not be null.")); 104 | } 105 | } 106 | 107 | private void checkNotNull(final List list) { 108 | Preconditions.checkNotNull(list); 109 | } 110 | 111 | private void checkNotNullWithMessage(final List list) { 112 | Preconditions.checkNotNull(list, "The list should not be null"); 113 | } 114 | 115 | private void checkNotNullWithFormatMessage(final List list) { 116 | Preconditions.checkNotNull(list, "The list should not be null and the size must be %s", 2); 117 | } 118 | } 119 | -------------------------------------------------------------------------------- /src/test/java/com/wangwenjun/guava/utilities/SplitterTest.java: -------------------------------------------------------------------------------- 1 | package com.wangwenjun.guava.utilities; 2 | 3 | import com.google.common.base.Splitter; 4 | import org.junit.Test; 5 | 6 | import java.util.List; 7 | import java.util.Map; 8 | import java.util.regex.Pattern; 9 | 10 | import static org.hamcrest.core.IsEqual.equalTo; 11 | import static org.hamcrest.core.IsNull.notNullValue; 12 | import static org.junit.Assert.assertThat; 13 | 14 | /*************************************** 15 | * @author:Alex Wang 16 | * @Date:2017/10/7 17 | * @QQ: 532500648 18 | ***************************************/ 19 | public class SplitterTest { 20 | 21 | @Test 22 | public void testSplitOnSplit() { 23 | List result = Splitter.on("|").splitToList("hello|world"); 24 | assertThat(result, notNullValue()); 25 | assertThat(result.size(), equalTo(2)); 26 | assertThat(result.get(0), equalTo("hello")); 27 | assertThat(result.get(1), equalTo("world")); 28 | } 29 | 30 | @Test 31 | public void testSplit_On_Split_OmitEmpty() { 32 | List result = Splitter.on("|").splitToList("hello|world|||"); 33 | assertThat(result, notNullValue()); 34 | assertThat(result.size(), equalTo(5)); 35 | 36 | result = Splitter.on("|").omitEmptyStrings().splitToList("hello|world|||"); 37 | assertThat(result, notNullValue()); 38 | assertThat(result.size(), equalTo(2)); 39 | } 40 | 41 | @Test 42 | public void testSplit_On_Split_OmitEmpty_TrimResult() { 43 | List result = Splitter.on("|").omitEmptyStrings().splitToList("hello | world|||"); 44 | assertThat(result, notNullValue()); 45 | assertThat(result.size(), equalTo(2)); 46 | assertThat(result.get(0), equalTo("hello ")); 47 | assertThat(result.get(1), equalTo(" world")); 48 | 49 | result = Splitter.on("|").trimResults().omitEmptyStrings().splitToList("hello | world|||"); 50 | assertThat(result.get(0), equalTo("hello")); 51 | assertThat(result.get(1), equalTo("world")); 52 | } 53 | 54 | /** 55 | * aaaabbbbccccdddd 56 | */ 57 | @Test 58 | public void testSplitFixLength() { 59 | List result = Splitter.fixedLength(4).splitToList("aaaabbbbccccdddd"); 60 | assertThat(result, notNullValue()); 61 | assertThat(result.size(), equalTo(4)); 62 | assertThat(result.get(0), equalTo("aaaa")); 63 | assertThat(result.get(3), equalTo("dddd")); 64 | } 65 | 66 | @Test 67 | public void testSplitOnSplitLimit() { 68 | List result = Splitter.on("#").limit(3).splitToList("hello#world#java#google#scala"); 69 | assertThat(result, notNullValue()); 70 | assertThat(result.size(), equalTo(3)); 71 | assertThat(result.get(0), equalTo("hello")); 72 | assertThat(result.get(1), equalTo("world")); 73 | assertThat(result.get(2), equalTo("java#google#scala")); 74 | } 75 | 76 | 77 | @Test 78 | public void testSplitOnPatternString() { 79 | List result = Splitter.onPattern("\\|").trimResults().omitEmptyStrings().splitToList("hello | world|||"); 80 | assertThat(result, notNullValue()); 81 | assertThat(result.size(), equalTo(2)); 82 | assertThat(result.get(0), equalTo("hello")); 83 | assertThat(result.get(1), equalTo("world")); 84 | } 85 | 86 | @Test 87 | public void testSplitOnPattern() { 88 | List result = Splitter.on(Pattern.compile("\\|")).trimResults().omitEmptyStrings().splitToList("hello | world|||"); 89 | assertThat(result, notNullValue()); 90 | assertThat(result.size(), equalTo(2)); 91 | assertThat(result.get(0), equalTo("hello")); 92 | assertThat(result.get(1), equalTo("world")); 93 | } 94 | 95 | 96 | @Test 97 | public void testSplitOnSplitToMap() { 98 | Map result = Splitter.on(Pattern.compile("\\|")).trimResults() 99 | .omitEmptyStrings().withKeyValueSeparator("=").split("hello=HELLO| world=WORLD|||"); 100 | assertThat(result, notNullValue()); 101 | assertThat(result.size(), equalTo(2)); 102 | assertThat(result.get("hello"),equalTo("HELLO")); 103 | assertThat(result.get("world"),equalTo("WORLD")); 104 | 105 | } 106 | } 107 | -------------------------------------------------------------------------------- /src/test/java/com/wangwenjun/guava/utilities/StringsTest.java: -------------------------------------------------------------------------------- 1 | package com.wangwenjun.guava.utilities; 2 | 3 | import com.google.common.base.CharMatcher; 4 | import com.google.common.base.Charsets; 5 | import com.google.common.base.Strings; 6 | import org.junit.Test; 7 | 8 | import java.nio.charset.Charset; 9 | 10 | import static org.hamcrest.core.IsEqual.equalTo; 11 | import static org.hamcrest.core.IsNull.nullValue; 12 | import static org.junit.Assert.assertThat; 13 | 14 | /*************************************** 15 | * @author:Alex Wang 16 | * @Date:2017/10/7 17 | * @QQ: 532500648 18 | ***************************************/ 19 | public class StringsTest { 20 | 21 | @Test 22 | public void testStringsMethod() { 23 | assertThat(Strings.emptyToNull(""), nullValue()); 24 | assertThat(Strings.nullToEmpty(null), equalTo("")); 25 | assertThat(Strings.nullToEmpty("hello"), equalTo("hello")); 26 | assertThat(Strings.commonPrefix("Hello", "Hit"), equalTo("H")); 27 | assertThat(Strings.commonPrefix("Hello", "Xit"), equalTo("")); 28 | assertThat(Strings.commonSuffix("Hello", "Echo"), equalTo("o")); 29 | assertThat(Strings.repeat("Alex", 3), equalTo("AlexAlexAlex")); 30 | assertThat(Strings.isNullOrEmpty(null), equalTo(true)); 31 | assertThat(Strings.isNullOrEmpty(""), equalTo(true)); 32 | 33 | assertThat(Strings.padStart("Alex", 3, 'H'), equalTo("Alex")); 34 | assertThat(Strings.padStart("Alex", 5, 'H'), equalTo("HAlex")); 35 | assertThat(Strings.padEnd("Alex", 5, 'H'), equalTo("AlexH")); 36 | } 37 | 38 | @Test 39 | public void testCharsets() { 40 | Charset charset = Charset.forName("UTF-8"); 41 | assertThat(Charsets.UTF_8, equalTo(charset)); 42 | } 43 | 44 | /** 45 | * functor 46 | */ 47 | @Test 48 | public void testCharMatcher() { 49 | assertThat(CharMatcher.javaDigit().matches('5'), equalTo(true)); 50 | assertThat(CharMatcher.javaDigit().matches('x'), equalTo(false)); 51 | 52 | assertThat(CharMatcher.is('A').countIn("Alex Sharing the Google Guava to Us"), equalTo(1)); 53 | assertThat(CharMatcher.breakingWhitespace().collapseFrom(" hello Guava ", '*'), equalTo("*hello*Guava*")); 54 | assertThat(CharMatcher.javaDigit().or(CharMatcher.whitespace()).removeFrom("hello 234 world"), equalTo("helloworld")); 55 | assertThat(CharMatcher.javaDigit().or(CharMatcher.whitespace()).retainFrom("hello 234 world"), equalTo(" 234 ")); 56 | 57 | } 58 | 59 | public Integer text(){ 60 | return 0; 61 | } 62 | } 63 | -------------------------------------------------------------------------------- /src/test/resources/io/files.PNG: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/wangwenjun/guava_programming/804e50450d626ec9b74dc2a9adf95f8628c6be4d/src/test/resources/io/files.PNG -------------------------------------------------------------------------------- /src/test/resources/io/source.txt: -------------------------------------------------------------------------------- 1 | today we will share the guava io knowledge. 2 | but only for the basic usage. if you wanted to get the more details information 3 | please read the guava document or source code. 4 | 5 | The guava source code is very cleanly and nice. --------------------------------------------------------------------------------