├── .gitignore
├── LICENSE.txt
├── README.md
├── docker
├── Dockerfile
└── launch.sh
├── pom.xml
└── src
└── main
├── java
└── org
│ └── infinispan
│ └── tutorial
│ └── embedded
│ ├── CacheListener.java
│ ├── CachingWeatherService.java
│ ├── ClusterListener.java
│ ├── LocationWeather.java
│ ├── OpenWeatherMapService.java
│ ├── RandomWeatherService.java
│ ├── SerializationContextInitializer.java
│ ├── WeatherApp.java
│ └── WeatherService.java
└── resources
├── logging.properties
└── weatherapp-infinispan.xml
/.gitignore:
--------------------------------------------------------------------------------
1 | *.class
2 |
3 | # Package Files #
4 | *.jar
5 | *.war
6 | *.ear
7 |
8 | target
9 |
10 | .settings
11 | .project
12 | .classpath
13 |
14 | *.iml
15 | *.ipr
16 | *.iws
17 | .idea
18 |
19 | # virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml
20 | hs_err_pid*
21 |
--------------------------------------------------------------------------------
/LICENSE.txt:
--------------------------------------------------------------------------------
1 |
2 | Apache License
3 | Version 2.0, January 2004
4 | http://www.apache.org/licenses/
5 |
6 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7 |
8 | 1. Definitions.
9 |
10 | "License" shall mean the terms and conditions for use, reproduction,
11 | and distribution as defined by Sections 1 through 9 of this document.
12 |
13 | "Licensor" shall mean the copyright owner or entity authorized by
14 | the copyright owner that is granting the License.
15 |
16 | "Legal Entity" shall mean the union of the acting entity and all
17 | other entities that control, are controlled by, or are under common
18 | control with that entity. For the purposes of this definition,
19 | "control" means (i) the power, direct or indirect, to cause the
20 | direction or management of such entity, whether by contract or
21 | otherwise, or (ii) ownership of fifty percent (50%) or more of the
22 | outstanding shares, or (iii) beneficial ownership of such entity.
23 |
24 | "You" (or "Your") shall mean an individual or Legal Entity
25 | exercising permissions granted by this License.
26 |
27 | "Source" form shall mean the preferred form for making modifications,
28 | including but not limited to software source code, documentation
29 | source, and configuration files.
30 |
31 | "Object" form shall mean any form resulting from mechanical
32 | transformation or translation of a Source form, including but
33 | not limited to compiled object code, generated documentation,
34 | and conversions to other media types.
35 |
36 | "Work" shall mean the work of authorship, whether in Source or
37 | Object form, made available under the License, as indicated by a
38 | copyright notice that is included in or attached to the work
39 | (an example is provided in the Appendix below).
40 |
41 | "Derivative Works" shall mean any work, whether in Source or Object
42 | form, that is based on (or derived from) the Work and for which the
43 | editorial revisions, annotations, elaborations, or other modifications
44 | represent, as a whole, an original work of authorship. For the purposes
45 | of this License, Derivative Works shall not include works that remain
46 | separable from, or merely link (or bind by name) to the interfaces of,
47 | the Work and Derivative Works thereof.
48 |
49 | "Contribution" shall mean any work of authorship, including
50 | the original version of the Work and any modifications or additions
51 | to that Work or Derivative Works thereof, that is intentionally
52 | submitted to Licensor for inclusion in the Work by the copyright owner
53 | or by an individual or Legal Entity authorized to submit on behalf of
54 | the copyright owner. For the purposes of this definition, "submitted"
55 | means any form of electronic, verbal, or written communication sent
56 | to the Licensor or its representatives, including but not limited to
57 | communication on electronic mailing lists, source code control systems,
58 | and issue tracking systems that are managed by, or on behalf of, the
59 | Licensor for the purpose of discussing and improving the Work, but
60 | excluding communication that is conspicuously marked or otherwise
61 | designated in writing by the copyright owner as "Not a Contribution."
62 |
63 | "Contributor" shall mean Licensor and any individual or Legal Entity
64 | on behalf of whom a Contribution has been received by Licensor and
65 | subsequently incorporated within the Work.
66 |
67 | 2. Grant of Copyright License. Subject to the terms and conditions of
68 | this License, each Contributor hereby grants to You a perpetual,
69 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70 | copyright license to reproduce, prepare Derivative Works of,
71 | publicly display, publicly perform, sublicense, and distribute the
72 | Work and such Derivative Works in Source or Object form.
73 |
74 | 3. Grant of Patent License. Subject to the terms and conditions of
75 | this License, each Contributor hereby grants to You a perpetual,
76 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77 | (except as stated in this section) patent license to make, have made,
78 | use, offer to sell, sell, import, and otherwise transfer the Work,
79 | where such license applies only to those patent claims licensable
80 | by such Contributor that are necessarily infringed by their
81 | Contribution(s) alone or by combination of their Contribution(s)
82 | with the Work to which such Contribution(s) was submitted. If You
83 | institute patent litigation against any entity (including a
84 | cross-claim or counterclaim in a lawsuit) alleging that the Work
85 | or a Contribution incorporated within the Work constitutes direct
86 | or contributory patent infringement, then any patent licenses
87 | granted to You under this License for that Work shall terminate
88 | as of the date such litigation is filed.
89 |
90 | 4. Redistribution. You may reproduce and distribute copies of the
91 | Work or Derivative Works thereof in any medium, with or without
92 | modifications, and in Source or Object form, provided that You
93 | meet the following conditions:
94 |
95 | (a) You must give any other recipients of the Work or
96 | Derivative Works a copy of this License; and
97 |
98 | (b) You must cause any modified files to carry prominent notices
99 | stating that You changed the files; and
100 |
101 | (c) You must retain, in the Source form of any Derivative Works
102 | that You distribute, all copyright, patent, trademark, and
103 | attribution notices from the Source form of the Work,
104 | excluding those notices that do not pertain to any part of
105 | the Derivative Works; and
106 |
107 | (d) If the Work includes a "NOTICE" text file as part of its
108 | distribution, then any Derivative Works that You distribute must
109 | include a readable copy of the attribution notices contained
110 | within such NOTICE file, excluding those notices that do not
111 | pertain to any part of the Derivative Works, in at least one
112 | of the following places: within a NOTICE text file distributed
113 | as part of the Derivative Works; within the Source form or
114 | documentation, if provided along with the Derivative Works; or,
115 | within a display generated by the Derivative Works, if and
116 | wherever such third-party notices normally appear. The contents
117 | of the NOTICE file are for informational purposes only and
118 | do not modify the License. You may add Your own attribution
119 | notices within Derivative Works that You distribute, alongside
120 | or as an addendum to the NOTICE text from the Work, provided
121 | that such additional attribution notices cannot be construed
122 | as modifying the License.
123 |
124 | You may add Your own copyright statement to Your modifications and
125 | may provide additional or different license terms and conditions
126 | for use, reproduction, or distribution of Your modifications, or
127 | for any such Derivative Works as a whole, provided Your use,
128 | reproduction, and distribution of the Work otherwise complies with
129 | the conditions stated in this License.
130 |
131 | 5. Submission of Contributions. Unless You explicitly state otherwise,
132 | any Contribution intentionally submitted for inclusion in the Work
133 | by You to the Licensor shall be under the terms and conditions of
134 | this License, without any additional terms or conditions.
135 | Notwithstanding the above, nothing herein shall supersede or modify
136 | the terms of any separate license agreement you may have executed
137 | with Licensor regarding such Contributions.
138 |
139 | 6. Trademarks. This License does not grant permission to use the trade
140 | names, trademarks, service marks, or product names of the Licensor,
141 | except as required for reasonable and customary use in describing the
142 | origin of the Work and reproducing the content of the NOTICE file.
143 |
144 | 7. Disclaimer of Warranty. Unless required by applicable law or
145 | agreed to in writing, Licensor provides the Work (and each
146 | Contributor provides its Contributions) on an "AS IS" BASIS,
147 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148 | implied, including, without limitation, any warranties or conditions
149 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150 | PARTICULAR PURPOSE. You are solely responsible for determining the
151 | appropriateness of using or redistributing the Work and assume any
152 | risks associated with Your exercise of permissions under this License.
153 |
154 | 8. Limitation of Liability. In no event and under no legal theory,
155 | whether in tort (including negligence), contract, or otherwise,
156 | unless required by applicable law (such as deliberate and grossly
157 | negligent acts) or agreed to in writing, shall any Contributor be
158 | liable to You for damages, including any direct, indirect, special,
159 | incidental, or consequential damages of any character arising as a
160 | result of this License or out of the use or inability to use the
161 | Work (including but not limited to damages for loss of goodwill,
162 | work stoppage, computer failure or malfunction, or any and all
163 | other commercial damages or losses), even if such Contributor
164 | has been advised of the possibility of such damages.
165 |
166 | 9. Accepting Warranty or Additional Liability. While redistributing
167 | the Work or Derivative Works thereof, You may choose to offer,
168 | and charge a fee for, acceptance of support, warranty, indemnity,
169 | or other liability obligations and/or rights consistent with this
170 | License. However, in accepting such obligations, You may act only
171 | on Your own behalf and on Your sole responsibility, not on behalf
172 | of any other Contributor, and only if You agree to indemnify,
173 | defend, and hold each Contributor harmless for any liability
174 | incurred by, or claims asserted against, such Contributor by reason
175 | of your accepting any such warranty or additional liability.
176 |
177 | END OF TERMS AND CONDITIONS
178 |
179 | APPENDIX: How to apply the Apache License to your work.
180 |
181 | To apply the Apache License to your work, attach the following
182 | boilerplate notice, with the fields enclosed by brackets "[]"
183 | replaced with your own identifying information. (Don't include
184 | the brackets!) The text should be enclosed in the appropriate
185 | comment syntax for the file format. We also recommend that a
186 | file or class name and description of purpose be included on the
187 | same "printed page" as the copyright notice for easier
188 | identification within third-party archives.
189 |
190 | Copyright [yyyy] [name of copyright owner]
191 |
192 | Licensed under the Apache License, Version 2.0 (the "License");
193 | you may not use this file except in compliance with the License.
194 | You may obtain a copy of the License at
195 |
196 | http://www.apache.org/licenses/LICENSE-2.0
197 |
198 | Unless required by applicable law or agreed to in writing, software
199 | distributed under the License is distributed on an "AS IS" BASIS,
200 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201 | See the License for the specific language governing permissions and
202 | limitations under the License.
203 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # Infinispan Embedded Tutorial: Weather App
2 |
3 | ## Overview
4 |
5 | This is a tutorial which explains how to use Infinispan embedded in your own
6 | application. The application will retrieve the current weather conditions for
7 | some cities and store them in a cache, for quicker retrieval. It will also
8 | show how to configure the cache for expiration, so that entries get removed as
9 | they age. It will then demonstrate how to cluster multiple nodes together and
10 | reacting to events in the cluster. Finally, a computation of average temperatures
11 | per country will show the power of the map/reduce functionality.
12 |
13 | Each tagged commit is a separate lesson teaching a single aspect of Infinispan.
14 |
15 | The tutorial instructions are at http://infinispan.org/tutorials/embedded/
16 |
17 | N.B. The tutorial connects to OpenWeatherMap (http://openweathermap.org) to
18 | retrieve current weather data. The service requires obtaining a free API key.
19 | Before launching the application, ensure you've set the OWMAPIKEY environment
20 | variable to your API key.
21 | If you don't want to register for the service, if you don't have an Internet
22 | connection or you are having trouble connecting to the service, just don't set
23 | the environment variable, and it will use the RandomWeatherService.
24 |
25 | ## Prerequisites
26 |
27 | ### Git
28 |
29 | - A good place to learn about setting up git is [here][git-github]
30 | - Git [home][git-home] (download, documentation)
31 |
32 | ### JDK
33 |
34 | - Get a [JDK][jdk-download]. You will need version 1.8 or higher
35 |
36 | ### Maven
37 |
38 | - Get [Maven][maven-download]. You will need version 3.2 or higher
39 |
40 | ## Commits / Tutorial Outline
41 |
42 | You can check out any point of the tutorial using
43 | git checkout step-?
44 |
45 | To see the changes between any two lessons use the git diff command.
46 | git diff step-?..step-?
47 |
48 | ### step-0/setup
49 |
50 | - The initial implementation of the Weather application
51 |
52 | ### step-1/cache-manager
53 |
54 | - Adding Infinispan to the project and initializing a cache manager
55 |
56 | ### step-2/cache-put-get
57 |
58 | - Add caching to the weather service
59 |
60 | ### step-3/expiration
61 |
62 | - Store the entries in the cache with an expiration time
63 |
64 | ### step-4/cachemanager-configuration
65 |
66 | - Configure the features of the default cache
67 |
68 | ### step-5/clustering
69 |
70 | - Add a transport to the CacheManager so that it supports clustering
71 |
72 | ### step-6/cachemanager-listener
73 |
74 | - Use CacheManager events to detect changes in the cluster
75 |
76 | ### step-7/cache-listener
77 |
78 | - Detect changes to the cache with a clustered listener
79 |
80 | ### step-8/grouping
81 |
82 | - Group related entries on the same nodes for efficiency
83 |
84 | ### step-9/externalizer
85 |
86 | - Implement a custom externalizer for our value class
87 |
88 | ### step-10/streams
89 |
90 | - Use Distributed Streams to compute temperature averages per country
91 |
92 | ### step-11/declarative-configuration
93 |
94 | - Use the XML configuration instead of the programmatic API
95 |
96 | ## Building and running the tutorial
97 |
98 | - Run `mvn clean package` to rebuild the application
99 | - Run `mvn exec:exec` to execute the application. In case you're running a clustered step, run this from
100 | multiple terminals, where each instance will represent a node
101 | - Run `mvn clean package docker:build` to build docker image, and then run `docker run infinispan-embedded-tutorial/infinispan-embedded-tutorial` in 2 different terminals to simulate multiple nodes of distributed cache
102 |
103 | ## Application Directory Layout
104 |
105 | docker/ -->
106 | src/ -->
107 | main/ -->
108 | java/ -->
109 | resources/ -->
110 |
111 | ## Contact
112 |
113 | For more information on Infinispan please check out http://infinispan.org/
114 |
115 | [jdk-download]: http://www.oracle.com/technetwork/articles/javase/index-jsp-138363.html
116 | [git-home]: http://git-scm.com
117 | [git-github]: http://help.github.com/set-up-git-redirect
118 | [maven-download]: http://maven.apache.org/download.html
119 |
120 |
--------------------------------------------------------------------------------
/docker/Dockerfile:
--------------------------------------------------------------------------------
1 | FROM jboss/base-jdk:8
2 |
3 | USER root
4 | RUN yum install -y iproute
5 | ADD launch.sh /usr/bin/launch.sh
6 | RUN chmod +x /usr/bin/launch.sh
7 | RUN mkdir -p /opt/infinispan-embedded-tutorial/
8 | RUN chown jboss:jboss /opt/infinispan-embedded-tutorial/
9 |
10 | USER jboss
11 | ADD infinispan-embedded-tutorial-1.0.0-SNAPSHOT-jar-with-dependencies.jar /opt/infinispan-embedded-tutorial/infinispan-embedded-tutorial.jar
12 |
13 | ENTRYPOINT /usr/bin/launch.sh
14 |
15 |
--------------------------------------------------------------------------------
/docker/launch.sh:
--------------------------------------------------------------------------------
1 | #!/bin/bash
2 |
3 | IPADDR=$(ip a s | sed -ne '/127.0.0.1/!{s/^[ \t]*inet[ \t]*\([0-9.]\+\)\/.*$/\1/p}')
4 | echo $IPADDR
5 |
6 | /usr/bin/java -Djava.net.preferIPv4Stack=true -Djgroups.bind_addr=$IPADDR -jar /opt/infinispan-embedded-tutorial/infinispan-embedded-tutorial.jar
7 |
8 |
--------------------------------------------------------------------------------
/pom.xml:
--------------------------------------------------------------------------------
1 |
2 | 4.0.0
3 | org.infinispan.tutorial
4 | infinispan-embedded-tutorial
5 | 1.0.0-SNAPSHOT
6 | Infinispan Tutorial: Embedded tutorial
7 |
8 |
9 | 11.0.0.Final
10 | 1.3.1
11 | 4.3.3.Final
12 |
13 |
14 |
15 |
16 |
17 | org.infinispan
18 | infinispan-bom
19 | ${version.infinispan}
20 | pom
21 | import
22 |
23 |
24 |
25 |
26 |
27 |
28 | org.infinispan
29 | infinispan-core
30 |
31 |
32 | org.infinispan.protostream
33 | protostream-processor
34 | ${version.protostream}
35 |
36 |
37 | javax.annotation
38 | javax.annotation-api
39 | ${version.javax.annotation.javax.annotation-api}
40 |
41 |
42 |
43 |
44 |
45 |
46 | org.apache.maven.plugins
47 | maven-compiler-plugin
48 | 3.8.1
49 |
50 | 1.8
51 | 1.8
52 |
53 |
54 |
55 | org.apache.maven.plugins
56 | maven-assembly-plugin
57 |
58 |
59 | package
60 |
61 | single
62 |
63 |
64 |
65 |
66 |
67 | jar-with-dependencies
68 |
69 |
70 |
71 | org.infinispan.tutorial.embedded.WeatherApp
72 |
73 |
74 |
75 |
76 |
77 | org.codehaus.mojo
78 | exec-maven-plugin
79 | 1.6.0
80 |
81 |
82 |
83 | exec
84 |
85 |
86 |
87 |
88 | java
89 |
90 | -Djava.net.preferIPv4Stack=true
91 | -Djava.util.logging.config.file=src/main/resources/logging.properties
92 | -classpath
93 |
94 | org.infinispan.tutorial.embedded.WeatherApp
95 |
96 |
97 |
98 |
99 | com.spotify
100 | docker-maven-plugin
101 | 1.2.0
102 |
103 | false
104 | infinispan-embedded-tutorial/${project.artifactId}
105 |
106 | ${project.version}
107 |
108 | ${project.basedir}/docker
109 |
110 |
111 | /
112 | ${project.build.directory}
113 | ${project.build.finalName}-jar-with-dependencies.jar
114 |
115 |
116 |
117 |
118 |
119 |
120 |
121 |
122 |
--------------------------------------------------------------------------------
/src/main/java/org/infinispan/tutorial/embedded/CacheListener.java:
--------------------------------------------------------------------------------
1 | package org.infinispan.tutorial.embedded;
2 |
3 | import org.infinispan.notifications.Listener;
4 | import org.infinispan.notifications.cachelistener.annotation.CacheEntryCreated;
5 | import org.infinispan.notifications.cachelistener.event.CacheEntryCreatedEvent;
6 |
7 | @Listener(clustered = true)
8 | public class CacheListener {
9 |
10 | @CacheEntryCreated
11 | public void entryCreated(CacheEntryCreatedEvent event) {
12 | if (!event.isOriginLocal()) {
13 | System.out.printf("-- Entry for %s modified by another node in the cluster\n", event.getKey());
14 | }
15 | }
16 | }
17 |
--------------------------------------------------------------------------------
/src/main/java/org/infinispan/tutorial/embedded/CachingWeatherService.java:
--------------------------------------------------------------------------------
1 | package org.infinispan.tutorial.embedded;
2 |
3 | import org.infinispan.Cache;
4 |
5 | public abstract class CachingWeatherService implements WeatherService {
6 | final private Cache cache;
7 |
8 | public CachingWeatherService(Cache cache) {
9 | this.cache = cache;
10 | }
11 |
12 | @Override
13 | final public LocationWeather getWeatherForLocation(String location) {
14 | LocationWeather weather = cache.get(location);
15 | if (weather == null) {
16 | weather = fetchWeather(location);
17 | cache.put(location, weather);
18 | }
19 | return weather;
20 | }
21 |
22 | protected abstract LocationWeather fetchWeather(String location);
23 | }
24 |
--------------------------------------------------------------------------------
/src/main/java/org/infinispan/tutorial/embedded/ClusterListener.java:
--------------------------------------------------------------------------------
1 | package org.infinispan.tutorial.embedded;
2 |
3 | import java.util.concurrent.CountDownLatch;
4 |
5 | import org.infinispan.notifications.Listener;
6 | import org.infinispan.notifications.cachemanagerlistener.annotation.ViewChanged;
7 | import org.infinispan.notifications.cachemanagerlistener.event.ViewChangedEvent;
8 |
9 | @Listener
10 | public class ClusterListener {
11 | CountDownLatch clusterFormedLatch = new CountDownLatch(1);
12 | CountDownLatch shutdownLatch = new CountDownLatch(1);
13 | private final int expectedNodes;
14 |
15 | public ClusterListener(int expectedNodes) {
16 | this.expectedNodes = expectedNodes;
17 | }
18 |
19 | @ViewChanged
20 | public void viewChanged(ViewChangedEvent event) {
21 | System.out.printf("---- View changed: %s ----\n", event.getNewMembers());
22 |
23 | if (event.getCacheManager().getMembers().size() == expectedNodes) {
24 | clusterFormedLatch.countDown();
25 | } else if (event.getNewMembers().size() < event.getOldMembers().size()) {
26 | shutdownLatch.countDown();
27 | }
28 | }
29 | }
30 |
--------------------------------------------------------------------------------
/src/main/java/org/infinispan/tutorial/embedded/LocationWeather.java:
--------------------------------------------------------------------------------
1 | package org.infinispan.tutorial.embedded;
2 |
3 | import org.infinispan.distribution.group.Grouper;
4 | import org.infinispan.protostream.annotations.ProtoFactory;
5 | import org.infinispan.protostream.annotations.ProtoField;
6 |
7 | public class LocationWeather {
8 |
9 | @ProtoField(number = 1, defaultValue = "0.0")
10 | final float temperature;
11 |
12 | @ProtoField(number = 2)
13 | final String conditions;
14 |
15 | @ProtoField(number = 3)
16 | final String country;
17 |
18 | @ProtoFactory
19 | public LocationWeather(float temperature, String conditions, String country) {
20 | this.temperature = temperature;
21 | this.conditions = conditions;
22 | this.country = country;
23 | }
24 |
25 | @Override
26 | public String toString() {
27 | return String.format("Temperature: %.1f° C, Conditions: %s", temperature, conditions);
28 | }
29 |
30 | public static class LocationGrouper implements Grouper {
31 |
32 | @Override
33 | public String computeGroup(String key, String group) {
34 | return key.split(",")[1].trim();
35 | }
36 |
37 | @Override
38 | public Class getKeyType() {
39 | return String.class;
40 | }
41 | }
42 |
43 | }
44 |
45 |
--------------------------------------------------------------------------------
/src/main/java/org/infinispan/tutorial/embedded/OpenWeatherMapService.java:
--------------------------------------------------------------------------------
1 | package org.infinispan.tutorial.embedded;
2 |
3 | import java.net.HttpURLConnection;
4 | import java.net.URL;
5 | import java.net.URLEncoder;
6 |
7 | import javax.xml.parsers.DocumentBuilder;
8 | import javax.xml.parsers.DocumentBuilderFactory;
9 | import javax.xml.parsers.ParserConfigurationException;
10 |
11 | import org.infinispan.Cache;
12 | import org.w3c.dom.Document;
13 | import org.w3c.dom.Element;
14 |
15 | public class OpenWeatherMapService extends CachingWeatherService {
16 | final private static String OWM_BASE_URL = "http://api.openweathermap.org/data/2.5/weather";
17 | private DocumentBuilder db;
18 | private final String apiKey;
19 |
20 | public OpenWeatherMapService(String apiKey, Cache cache) {
21 | super(cache);
22 | this.apiKey = apiKey;
23 | DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
24 | try {
25 | db = dbf.newDocumentBuilder();
26 | } catch (ParserConfigurationException e) {
27 | }
28 | }
29 |
30 | private Document fetchData(String location) {
31 | HttpURLConnection conn = null;
32 | try {
33 | String query = String.format("%s?q=%s&mode=xml&units=metric&APPID=%s", OWM_BASE_URL,
34 | URLEncoder.encode(location.replaceAll(" ", ""), "UTF-8"), apiKey);
35 | URL url = new URL(query);
36 | conn = (HttpURLConnection) url.openConnection();
37 | conn.setRequestMethod("GET");
38 | conn.setRequestProperty("Accept", "application/xml");
39 | if (conn.getResponseCode() != 200) {
40 | throw new Exception();
41 | }
42 | return db.parse(conn.getInputStream());
43 | } catch (Exception e) {
44 | return null;
45 | } finally {
46 | if (conn != null) {
47 | conn.disconnect();
48 | }
49 | }
50 | }
51 |
52 | @Override
53 | protected LocationWeather fetchWeather(String location) {
54 |
55 | Document dom = fetchData(location);
56 | if (dom == null) {
57 | throw new RuntimeException("Unable to reach or get response from open weather service with given OWMAPIKEY : please try with valid OWMAPIKEY or use Random Weather Service");
58 | }
59 | Element current = (Element) dom.getElementsByTagName("current").item(0);
60 | Element temperature = (Element) current.getElementsByTagName("temperature").item(0);
61 | Element weather = (Element) current.getElementsByTagName("weather").item(0);
62 | String[] split = location.split(",");
63 | return new LocationWeather(
64 | Float.parseFloat(temperature.getAttribute("value")),
65 | weather.getAttribute("value"),
66 | split[1].trim());
67 | }
68 |
69 | }
70 |
--------------------------------------------------------------------------------
/src/main/java/org/infinispan/tutorial/embedded/RandomWeatherService.java:
--------------------------------------------------------------------------------
1 | package org.infinispan.tutorial.embedded;
2 |
3 | import java.util.Random;
4 | import java.util.concurrent.TimeUnit;
5 |
6 | import org.infinispan.Cache;
7 |
8 | public class RandomWeatherService extends CachingWeatherService {
9 | final Random random;
10 |
11 | public RandomWeatherService(Cache cache) {
12 | super(cache);
13 | random = new Random();
14 | }
15 |
16 | @Override
17 | protected LocationWeather fetchWeather(String location) {
18 | try {
19 | TimeUnit.MILLISECONDS.sleep(200);
20 | } catch (InterruptedException e) {}
21 | String[] split = location.split(",");
22 | return new LocationWeather(random.nextFloat() * 20f + 5f, "sunny", split[1].trim());
23 | }
24 |
25 | }
26 |
--------------------------------------------------------------------------------
/src/main/java/org/infinispan/tutorial/embedded/SerializationContextInitializer.java:
--------------------------------------------------------------------------------
1 | package org.infinispan.tutorial.embedded;
2 |
3 | import org.infinispan.protostream.annotations.AutoProtoSchemaBuilder;
4 |
5 | @AutoProtoSchemaBuilder(
6 | includeClasses = LocationWeather.class,
7 | schemaFileName = "weather.proto",
8 | schemaFilePath = "proto",
9 | schemaPackageName = "org.infinispan.tutorial.embedded"
10 | )
11 | public interface SerializationContextInitializer extends org.infinispan.protostream.SerializationContextInitializer {
12 | }
13 |
--------------------------------------------------------------------------------
/src/main/java/org/infinispan/tutorial/embedded/WeatherApp.java:
--------------------------------------------------------------------------------
1 | package org.infinispan.tutorial.embedded;
2 |
3 | import java.io.IOException;
4 | import java.util.Map;
5 | import java.util.Map.Entry;
6 | import java.util.concurrent.TimeUnit;
7 |
8 | import org.infinispan.Cache;
9 | import org.infinispan.manager.DefaultCacheManager;
10 | import org.infinispan.manager.EmbeddedCacheManager;
11 | import org.infinispan.stream.CacheCollectors;
12 |
13 | import static java.util.stream.Collectors.averagingDouble;
14 | import static java.util.stream.Collectors.groupingBy;
15 |
16 | public class WeatherApp {
17 |
18 | static final String[] locations = { "Rome, Italy", "Como, Italy", "Basel, Switzerland", "Bern, Switzerland",
19 | "London, UK", "Newcastle, UK", "Bucarest, Romania", "Cluj-Napoca, Romania", "Ottawa, Canada",
20 | "Toronto, Canada", "Lisbon, Portugal", "Porto, Portugal", "Raleigh, USA", "Washington, USA" };
21 | private final EmbeddedCacheManager cacheManager;
22 | private final WeatherService weatherService;
23 | private Cache cache;
24 | private final ClusterListener listener;
25 |
26 | public WeatherApp() throws InterruptedException, IOException {
27 | cacheManager = new DefaultCacheManager(WeatherApp.class.getResourceAsStream("/weatherapp-infinispan.xml"));
28 | listener = new ClusterListener(2);
29 | cacheManager.addListener(listener);
30 | cache = cacheManager.getCache("weather");
31 | cache.addListener(new CacheListener());
32 | weatherService = initWeatherService(cache);
33 |
34 | System.out.println("---- Waiting for cluster to form ----");
35 | listener.clusterFormedLatch.await();
36 | }
37 |
38 | private WeatherService initWeatherService(Cache cache) {
39 | String apiKey = System.getenv("OWMAPIKEY");
40 | if (apiKey == null) {
41 | System.out.println("WARNING: OWMAPIKEY environment variable not set, using the RandomWeatherService.");
42 | return new RandomWeatherService(cache);
43 | } else {
44 | return new OpenWeatherMapService(apiKey, cache);
45 | }
46 | }
47 |
48 | public void fetchWeather() {
49 | System.out.println("---- Fetching weather information ----");
50 | long start = System.currentTimeMillis();
51 | for (String location : locations) {
52 | LocationWeather weather = weatherService.getWeatherForLocation(location);
53 | System.out.printf("%s - %s\n", location, weather);
54 | }
55 | System.out.printf("---- Fetched in %dms ----\n", System.currentTimeMillis() - start);
56 | }
57 |
58 | public void computeCountryAverages() {
59 | System.out.println("---- Average country temperatures ----");
60 | Map averages = cache.entrySet().stream()
61 | .collect(CacheCollectors.serializableCollector(() -> groupingBy(e -> e.getValue().country,
62 | averagingDouble(e -> e.getValue().temperature))));
63 | for(Entry entry : averages.entrySet()) {
64 | System.out.printf("Average temperature in %s is %.1f° C\n", entry.getKey(), entry.getValue());
65 | }
66 | }
67 |
68 | public void shutdown() throws InterruptedException {
69 | if (!cacheManager.isCoordinator()) {
70 | listener.shutdownLatch.await();
71 | }
72 | cacheManager.stop();
73 | }
74 |
75 | public static void main(String[] args) throws Exception {
76 | WeatherApp app = new WeatherApp();
77 | try {
78 | if (app.cacheManager.isCoordinator()) {
79 |
80 | app.fetchWeather();
81 |
82 | app.fetchWeather();
83 |
84 | TimeUnit.SECONDS.sleep(5);
85 |
86 | app.fetchWeather();
87 |
88 | app.computeCountryAverages();
89 | }
90 | } finally {
91 | app.shutdown();
92 | }
93 |
94 | }
95 |
96 | }
97 |
--------------------------------------------------------------------------------
/src/main/java/org/infinispan/tutorial/embedded/WeatherService.java:
--------------------------------------------------------------------------------
1 | package org.infinispan.tutorial.embedded;
2 |
3 | public interface WeatherService {
4 | LocationWeather getWeatherForLocation(String location);
5 | }
6 |
--------------------------------------------------------------------------------
/src/main/resources/logging.properties:
--------------------------------------------------------------------------------
1 | handlers=java.util.logging.ConsoleHandler
2 | .level=INFO
3 |
4 | java.util.logging.ConsoleHandler.level=INFO
5 | java.util.logging.ConsoleHandler.formatter=java.util.logging.SimpleFormatter
6 |
--------------------------------------------------------------------------------
/src/main/resources/weatherapp-infinispan.xml:
--------------------------------------------------------------------------------
1 |
2 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
20 |
21 |
--------------------------------------------------------------------------------