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