├── src
└── main
│ ├── resources
│ └── es-plugin.properties
│ ├── java
│ └── com
│ │ └── ubervu
│ │ ├── river
│ │ └── github
│ │ │ ├── GitHubRiverModule.java
│ │ │ └── GitHubRiver.java
│ │ └── plugin
│ │ └── river
│ │ └── github
│ │ └── GitHubRiverPlugin.java
│ └── assemblies
│ └── plugin.xml
├── .gitignore
├── README.md
├── pom.xml
└── LICENSE
/src/main/resources/es-plugin.properties:
--------------------------------------------------------------------------------
1 | plugin=com.ubervu.plugin.river.github.GitHubRiverPlugin
2 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | *.class
2 |
3 | # Package Files #
4 | *.jar
5 | *.war
6 | *.ear
7 |
8 | target/
9 |
10 | settings.xml
11 |
--------------------------------------------------------------------------------
/src/main/java/com/ubervu/river/github/GitHubRiverModule.java:
--------------------------------------------------------------------------------
1 | package com.ubervu.river.github;
2 |
3 | import org.elasticsearch.common.inject.AbstractModule;
4 | import org.elasticsearch.river.River;
5 |
6 | /**
7 | *
8 | */
9 | public class GitHubRiverModule extends AbstractModule {
10 |
11 | @Override
12 | protected void configure() {
13 | bind(River.class).to(GitHubRiver.class).asEagerSingleton();
14 | }
15 | }
16 |
17 |
--------------------------------------------------------------------------------
/src/main/java/com/ubervu/plugin/river/github/GitHubRiverPlugin.java:
--------------------------------------------------------------------------------
1 | package com.ubervu.plugin.river.github;
2 |
3 | import org.elasticsearch.common.inject.Inject;
4 | import org.elasticsearch.plugins.AbstractPlugin;
5 | import org.elasticsearch.river.RiversModule;
6 | import com.ubervu.river.github.GitHubRiverModule;
7 |
8 | /**
9 | *
10 | */
11 | public class GitHubRiverPlugin extends AbstractPlugin {
12 |
13 | @Inject
14 | public GitHubRiverPlugin() {
15 | }
16 |
17 | @Override
18 | public String name() {
19 | return "river-github";
20 | }
21 |
22 | @Override
23 | public String description() {
24 | return "GitHub River Plugin";
25 | }
26 |
27 | public void onModule(RiversModule module) {
28 | module.registerRiver("github", GitHubRiverModule.class);
29 | }
30 | }
31 |
--------------------------------------------------------------------------------
/src/main/assemblies/plugin.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 | plugin
4 |
5 | zip
6 |
7 | false
8 |
9 |
10 | /
11 | true
12 | true
13 |
14 | org.elasticsearch:elasticsearch
15 |
16 |
17 |
18 | /
19 | true
20 | true
21 |
22 | org.eclipse.mylyn.github:org.eclipse.egit.github.core
23 | com.google.gson:com.google.gson
24 |
25 |
26 |
27 |
28 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | elasticsearch-river-github
2 | ==========================
3 |
4 | Elasticsearch river for GitHub data. Fetches all of the following for
5 | a given GitHub repo:
6 |
7 | * [events](http://developer.github.com/v3/activity/events/)
8 | * [issues](http://developer.github.com/v3/issues/#list-issues-for-a-repository)
9 | * [open pull requests](http://developer.github.com/v3/pulls/#list-pull-requests)
10 | * [open milestones](http://developer.github.com/v3/issues/milestones/)
11 | * [labels](http://developer.github.com/v3/issues/labels/)
12 | * [collaborators](http://developer.github.com/v3/repos/collaborators/#list)
13 |
14 | Works for private repos as well if you provide authentication.
15 |
16 | ##Easy install
17 |
18 | Assuming you have elasticsearch's `bin` folder in your `PATH`:
19 |
20 | ```
21 | plugin -i com.ubervu/elasticsearch-river-github/1.7.1
22 | ```
23 |
24 | Otherwise, you have to find the directory yourself. It should be
25 | `/usr/share/elasticsearch/bin` on Ubuntu.
26 |
27 | ##Adding the river
28 |
29 | ```bash
30 | curl -XPUT localhost:9200/_river/my_gh_river/_meta -d '{
31 | "type": "github",
32 | "github": {
33 | "owner": "gabrielfalcao",
34 | "repository": "lettuce",
35 | "interval": 60,
36 | "authentication": {
37 | "username": "MYUSER", # or token
38 | "password": "MYPASSWORD" # or x-oauth-basic when using a token
39 | }
40 | "endpoint": "https://api.somegithub.com" # optional, use it only for non github.com
41 | }
42 | }'
43 | ```
44 |
45 | _interval_ is optional, given in seconds and changes how often the river looks for new data. Since 1.7.1 the default value has been reduced to one minute as we now only load issues and events that has changed, which should decrease API calls and improve the time to update quite significantly. The actual polling interval will be affected by GitHub's minimum allowed polling interval, which is normally 60 seconds, but may increase when servers are busy.
46 |
47 | _authentication_ is optional and helps with the API rate limit (5000 requests/hour instead of 60 requests/hour) and when accessing private data. You can use your own GitHub credentials or a token. When using a token, fill in the token as the username and `x-oauth-basic` as the password, as the [docs](http://developer.github.com/v3/auth/#basic-authentication) mention.
48 |
49 | If you do not use _authentication_, you may want to set _interval_ to a higher value, like 900 (every 15 minutes), as the GitHub rate limit will probably be breached when using low values. This is __not__ recommended if you require the GitHub events without holes, as Github only allows access to the last 300 events. In that case, authenticating is highly recommended. _This will probably change in a later version, at least for repositories without too much traffic, as we should be able to check for changes before loading most types of entries._
50 |
51 | ##Deleting the river
52 |
53 | ```
54 | curl -XDELETE localhost:9200/_river/my_gh_river
55 | ```
56 |
57 | ##Indexes and types
58 |
59 | The data will be stored in an index of format "%s&%s" % (owner, repo), i.e.
60 | `gabrielfalcao&lettuce`.
61 |
62 | For every API event type, there will be an elasticsearch type of the same name -
63 | i.e. `ForkEvent`.
64 |
65 | Issue data will be stored with the `IssueData` type. Pull request data will be stored
66 | with the `PullRequestData` type. Milestone data will be stored with the `MilestoneData`
67 | type.
68 |
69 |
--------------------------------------------------------------------------------
/pom.xml:
--------------------------------------------------------------------------------
1 |
2 |
5 | elasticsearch-river-github
6 | 4.0.0
7 | com.ubervu
8 | elasticsearch-river-github
9 | 1.7.1
10 | jar
11 | Github River for ElasticSearch
12 | 2014
13 |
14 |
15 | The Apache Software License, Version 2.0
16 | http://www.apache.org/licenses/LICENSE-2.0.txt
17 | repo
18 |
19 |
20 |
21 | scm:git:git@github.com:ubervu/elasticsearch-river-github.git
22 | scm:git:git@github.com:ubervu/elasticsearch-river-github.git
23 | http://github.com/ubervu/elasticsearch-river-github
24 |
25 |
26 |
27 | org.sonatype.oss
28 | oss-parent
29 | 7
30 |
31 |
32 |
33 | 1.0.1
34 |
35 |
36 |
37 |
38 | sonatype
39 | http://oss.sonatype.org/content/repositories/releases/
40 |
41 |
42 |
43 |
44 |
45 | org.elasticsearch
46 | elasticsearch
47 | ${elasticsearch.version}
48 | compile
49 |
50 |
51 |
52 | log4j
53 | log4j
54 | 1.2.16
55 | runtime
56 |
57 |
58 |
59 | commons-io
60 | commons-io
61 | 2.4
62 |
63 |
64 |
65 | commons-codec
66 | commons-codec
67 | 1.6
68 |
69 |
70 |
71 | com.google.code.gson
72 | gson
73 | 2.2.2
74 |
75 |
76 |
77 |
78 |
79 |
80 |
81 |
82 | org.apache.maven.plugins
83 | maven-gpg-plugin
84 |
85 |
86 | sign-artifacts
87 | verify
88 |
89 | sign
90 |
91 |
92 |
93 |
94 |
95 | org.apache.maven.plugins
96 | maven-compiler-plugin
97 | 2.3.2
98 |
99 | 1.6
100 | 1.6
101 |
102 |
103 |
104 | org.apache.maven.plugins
105 | maven-surefire-plugin
106 | 2.11
107 |
108 |
109 | **/*Tests.java
110 |
111 |
112 |
113 |
114 | org.apache.maven.plugins
115 | maven-javadoc-plugin
116 |
117 |
118 | attach-javadocs
119 |
120 | jar
121 |
122 |
123 |
124 |
125 |
126 | org.apache.maven.plugins
127 | maven-source-plugin
128 | 2.1.2
129 |
130 |
131 | attach-sources
132 |
133 | jar
134 |
135 |
136 |
137 |
138 |
139 | maven-assembly-plugin
140 | 2.3
141 |
142 | false
143 | ${project.build.directory}/releases/
144 |
145 | ${basedir}/src/main/assemblies/plugin.xml
146 |
147 |
148 |
149 |
150 | package
151 |
152 | single
153 |
154 |
155 |
156 |
157 |
158 |
159 |
160 |
161 | sonatype
162 | https://oss.sonatype.org/service/local/staging/deploy/maven2
163 |
164 |
165 |
166 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | Apache License
2 | Version 2.0, January 2004
3 | http://www.apache.org/licenses/
4 |
5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6 |
7 | 1. Definitions.
8 |
9 | "License" shall mean the terms and conditions for use, reproduction,
10 | and distribution as defined by Sections 1 through 9 of this document.
11 |
12 | "Licensor" shall mean the copyright owner or entity authorized by
13 | the copyright owner that is granting the License.
14 |
15 | "Legal Entity" shall mean the union of the acting entity and all
16 | other entities that control, are controlled by, or are under common
17 | control with that entity. For the purposes of this definition,
18 | "control" means (i) the power, direct or indirect, to cause the
19 | direction or management of such entity, whether by contract or
20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the
21 | outstanding shares, or (iii) beneficial ownership of such entity.
22 |
23 | "You" (or "Your") shall mean an individual or Legal Entity
24 | exercising permissions granted by this License.
25 |
26 | "Source" form shall mean the preferred form for making modifications,
27 | including but not limited to software source code, documentation
28 | source, and configuration files.
29 |
30 | "Object" form shall mean any form resulting from mechanical
31 | transformation or translation of a Source form, including but
32 | not limited to compiled object code, generated documentation,
33 | and conversions to other media types.
34 |
35 | "Work" shall mean the work of authorship, whether in Source or
36 | Object form, made available under the License, as indicated by a
37 | copyright notice that is included in or attached to the work
38 | (an example is provided in the Appendix below).
39 |
40 | "Derivative Works" shall mean any work, whether in Source or Object
41 | form, that is based on (or derived from) the Work and for which the
42 | editorial revisions, annotations, elaborations, or other modifications
43 | represent, as a whole, an original work of authorship. For the purposes
44 | of this License, Derivative Works shall not include works that remain
45 | separable from, or merely link (or bind by name) to the interfaces of,
46 | the Work and Derivative Works thereof.
47 |
48 | "Contribution" shall mean any work of authorship, including
49 | the original version of the Work and any modifications or additions
50 | to that Work or Derivative Works thereof, that is intentionally
51 | submitted to Licensor for inclusion in the Work by the copyright owner
52 | or by an individual or Legal Entity authorized to submit on behalf of
53 | the copyright owner. For the purposes of this definition, "submitted"
54 | means any form of electronic, verbal, or written communication sent
55 | to the Licensor or its representatives, including but not limited to
56 | communication on electronic mailing lists, source code control systems,
57 | and issue tracking systems that are managed by, or on behalf of, the
58 | Licensor for the purpose of discussing and improving the Work, but
59 | excluding communication that is conspicuously marked or otherwise
60 | designated in writing by the copyright owner as "Not a Contribution."
61 |
62 | "Contributor" shall mean Licensor and any individual or Legal Entity
63 | on behalf of whom a Contribution has been received by Licensor and
64 | subsequently incorporated within the Work.
65 |
66 | 2. Grant of Copyright License. Subject to the terms and conditions of
67 | this License, each Contributor hereby grants to You a perpetual,
68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69 | copyright license to reproduce, prepare Derivative Works of,
70 | publicly display, publicly perform, sublicense, and distribute the
71 | Work and such Derivative Works in Source or Object form.
72 |
73 | 3. Grant of Patent License. Subject to the terms and conditions of
74 | this License, each Contributor hereby grants to You a perpetual,
75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76 | (except as stated in this section) patent license to make, have made,
77 | use, offer to sell, sell, import, and otherwise transfer the Work,
78 | where such license applies only to those patent claims licensable
79 | by such Contributor that are necessarily infringed by their
80 | Contribution(s) alone or by combination of their Contribution(s)
81 | with the Work to which such Contribution(s) was submitted. If You
82 | institute patent litigation against any entity (including a
83 | cross-claim or counterclaim in a lawsuit) alleging that the Work
84 | or a Contribution incorporated within the Work constitutes direct
85 | or contributory patent infringement, then any patent licenses
86 | granted to You under this License for that Work shall terminate
87 | as of the date such litigation is filed.
88 |
89 | 4. Redistribution. You may reproduce and distribute copies of the
90 | Work or Derivative Works thereof in any medium, with or without
91 | modifications, and in Source or Object form, provided that You
92 | meet the following conditions:
93 |
94 | (a) You must give any other recipients of the Work or
95 | Derivative Works a copy of this License; and
96 |
97 | (b) You must cause any modified files to carry prominent notices
98 | stating that You changed the files; and
99 |
100 | (c) You must retain, in the Source form of any Derivative Works
101 | that You distribute, all copyright, patent, trademark, and
102 | attribution notices from the Source form of the Work,
103 | excluding those notices that do not pertain to any part of
104 | the Derivative Works; and
105 |
106 | (d) If the Work includes a "NOTICE" text file as part of its
107 | distribution, then any Derivative Works that You distribute must
108 | include a readable copy of the attribution notices contained
109 | within such NOTICE file, excluding those notices that do not
110 | pertain to any part of the Derivative Works, in at least one
111 | of the following places: within a NOTICE text file distributed
112 | as part of the Derivative Works; within the Source form or
113 | documentation, if provided along with the Derivative Works; or,
114 | within a display generated by the Derivative Works, if and
115 | wherever such third-party notices normally appear. The contents
116 | of the NOTICE file are for informational purposes only and
117 | do not modify the License. You may add Your own attribution
118 | notices within Derivative Works that You distribute, alongside
119 | or as an addendum to the NOTICE text from the Work, provided
120 | that such additional attribution notices cannot be construed
121 | as modifying the License.
122 |
123 | You may add Your own copyright statement to Your modifications and
124 | may provide additional or different license terms and conditions
125 | for use, reproduction, or distribution of Your modifications, or
126 | for any such Derivative Works as a whole, provided Your use,
127 | reproduction, and distribution of the Work otherwise complies with
128 | the conditions stated in this License.
129 |
130 | 5. Submission of Contributions. Unless You explicitly state otherwise,
131 | any Contribution intentionally submitted for inclusion in the Work
132 | by You to the Licensor shall be under the terms and conditions of
133 | this License, without any additional terms or conditions.
134 | Notwithstanding the above, nothing herein shall supersede or modify
135 | the terms of any separate license agreement you may have executed
136 | with Licensor regarding such Contributions.
137 |
138 | 6. Trademarks. This License does not grant permission to use the trade
139 | names, trademarks, service marks, or product names of the Licensor,
140 | except as required for reasonable and customary use in describing the
141 | origin of the Work and reproducing the content of the NOTICE file.
142 |
143 | 7. Disclaimer of Warranty. Unless required by applicable law or
144 | agreed to in writing, Licensor provides the Work (and each
145 | Contributor provides its Contributions) on an "AS IS" BASIS,
146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147 | implied, including, without limitation, any warranties or conditions
148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149 | PARTICULAR PURPOSE. You are solely responsible for determining the
150 | appropriateness of using or redistributing the Work and assume any
151 | risks associated with Your exercise of permissions under this License.
152 |
153 | 8. Limitation of Liability. In no event and under no legal theory,
154 | whether in tort (including negligence), contract, or otherwise,
155 | unless required by applicable law (such as deliberate and grossly
156 | negligent acts) or agreed to in writing, shall any Contributor be
157 | liable to You for damages, including any direct, indirect, special,
158 | incidental, or consequential damages of any character arising as a
159 | result of this License or out of the use or inability to use the
160 | Work (including but not limited to damages for loss of goodwill,
161 | work stoppage, computer failure or malfunction, or any and all
162 | other commercial damages or losses), even if such Contributor
163 | has been advised of the possibility of such damages.
164 |
165 | 9. Accepting Warranty or Additional Liability. While redistributing
166 | the Work or Derivative Works thereof, You may choose to offer,
167 | and charge a fee for, acceptance of support, warranty, indemnity,
168 | or other liability obligations and/or rights consistent with this
169 | License. However, in accepting such obligations, You may act only
170 | on Your own behalf and on Your sole responsibility, not on behalf
171 | of any other Contributor, and only if You agree to indemnify,
172 | defend, and hold each Contributor harmless for any liability
173 | incurred by, or claims asserted against, such Contributor by reason
174 | of your accepting any such warranty or additional liability.
175 |
176 | END OF TERMS AND CONDITIONS
177 |
178 | APPENDIX: How to apply the Apache License to your work.
179 |
180 | To apply the Apache License to your work, attach the following
181 | boilerplate notice, with the fields enclosed by brackets "{}"
182 | replaced with your own identifying information. (Don't include
183 | the brackets!) The text should be enclosed in the appropriate
184 | comment syntax for the file format. We also recommend that a
185 | file or class name and description of purpose be included on the
186 | same "printed page" as the copyright notice for easier
187 | identification within third-party archives.
188 |
189 | Copyright {yyyy} {name of copyright owner}
190 |
191 | Licensed under the Apache License, Version 2.0 (the "License");
192 | you may not use this file except in compliance with the License.
193 | You may obtain a copy of the License at
194 |
195 | http://www.apache.org/licenses/LICENSE-2.0
196 |
197 | Unless required by applicable law or agreed to in writing, software
198 | distributed under the License is distributed on an "AS IS" BASIS,
199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200 | See the License for the specific language governing permissions and
201 | limitations under the License.
202 |
203 |
--------------------------------------------------------------------------------
/src/main/java/com/ubervu/river/github/GitHubRiver.java:
--------------------------------------------------------------------------------
1 | package com.ubervu.river.github;
2 |
3 | import com.google.gson.JsonArray;
4 | import com.google.gson.JsonElement;
5 | import com.google.gson.JsonObject;
6 | import com.google.gson.JsonStreamParser;
7 | import org.apache.commons.codec.digest.DigestUtils;
8 | import org.elasticsearch.action.bulk.BulkProcessor;
9 | import org.elasticsearch.action.bulk.BulkRequest;
10 | import org.elasticsearch.action.bulk.BulkResponse;
11 | import org.elasticsearch.action.index.IndexRequest;
12 | import org.elasticsearch.action.search.SearchResponse;
13 | import org.elasticsearch.client.Client;
14 | import org.elasticsearch.common.Base64;
15 | import org.elasticsearch.common.inject.Inject;
16 | import org.elasticsearch.common.settings.ImmutableSettings;
17 | import org.elasticsearch.common.settings.Settings;
18 | import org.elasticsearch.common.xcontent.support.XContentMapValues;
19 | import org.elasticsearch.index.query.FilterBuilders;
20 | import org.elasticsearch.index.query.FilteredQueryBuilder;
21 | import org.elasticsearch.index.query.QueryBuilders;
22 | import org.elasticsearch.indices.IndexAlreadyExistsException;
23 | import org.elasticsearch.river.AbstractRiverComponent;
24 | import org.elasticsearch.river.River;
25 | import org.elasticsearch.river.RiverName;
26 | import org.elasticsearch.river.RiverSettings;
27 | import org.elasticsearch.search.sort.FieldSortBuilder;
28 | import org.elasticsearch.search.sort.SortBuilders;
29 | import org.elasticsearch.search.sort.SortOrder;
30 |
31 | import java.io.IOException;
32 | import java.io.InputStream;
33 | import java.io.InputStreamReader;
34 | import java.net.HttpURLConnection;
35 | import java.net.URL;
36 | import java.net.URLConnection;
37 | import java.util.HashMap;
38 | import java.util.Map;
39 | import java.util.regex.Matcher;
40 | import java.util.regex.Pattern;
41 |
42 | import static org.elasticsearch.index.query.QueryBuilders.matchAllQuery;
43 | import static org.elasticsearch.index.query.QueryBuilders.termQuery;
44 |
45 |
46 | public class GitHubRiver extends AbstractRiverComponent implements River {
47 |
48 | private final Client client;
49 | private final String index;
50 | private final String repository;
51 | private final String owner;
52 | private final int userRequestedInterval;
53 | private final String endpoint;
54 |
55 | private String password;
56 | private String username;
57 | private DataStream dataStream;
58 | private String eventETag = null;
59 | private int pollInterval = 60;
60 |
61 | @SuppressWarnings({"unchecked"})
62 | @Inject
63 | public GitHubRiver(RiverName riverName, RiverSettings settings, Client client) {
64 | super(riverName, settings);
65 | this.client = client;
66 |
67 | if (!settings.settings().containsKey("github")) {
68 | throw new IllegalArgumentException("Need river settings - owner and repository.");
69 | }
70 |
71 | // get settings
72 | Map githubSettings = (Map) settings.settings().get("github");
73 | owner = XContentMapValues.nodeStringValue(githubSettings.get("owner"), null);
74 | repository = XContentMapValues.nodeStringValue(githubSettings.get("repository"), null);
75 |
76 | index = String.format("%s&%s", owner, repository);
77 | userRequestedInterval = XContentMapValues.nodeIntegerValue(githubSettings.get("interval"), 60);
78 |
79 | // auth (optional)
80 | username = null;
81 | password = null;
82 | if (githubSettings.containsKey("authentication")) {
83 | Map auth = (Map) githubSettings.get("authentication");
84 | username = XContentMapValues.nodeStringValue(auth.get("username"), null);
85 | password = XContentMapValues.nodeStringValue(auth.get("password"), null);
86 | }
87 |
88 | // endpoint (optional - default to github.com)
89 | endpoint = XContentMapValues.nodeStringValue(githubSettings.get("endpoint"), "https://api.github.com");
90 |
91 | logger.info("Created GitHub river.");
92 | }
93 |
94 | @Override
95 | public void start() {
96 | // create the index explicitly so we can use the whitespace tokenizer
97 | // because there are usernames like "user-name" and we want those
98 | // to be treated as just one term
99 | try {
100 | Settings indexSettings = ImmutableSettings.settingsBuilder().put("analysis.analyzer.default.tokenizer", "whitespace").build();
101 | client.admin().indices().prepareCreate(index).setSettings(indexSettings).execute().actionGet();
102 | logger.info("Created index.");
103 | } catch (IndexAlreadyExistsException e) {
104 | logger.info("Index already created");
105 | } catch (Exception e) {
106 | logger.error("Exception creating index.", e);
107 | }
108 | dataStream = new DataStream();
109 | dataStream.start();
110 | logger.info("Started GitHub river.");
111 | }
112 |
113 | @Override
114 | public void close() {
115 | dataStream.setRunning(false);
116 | dataStream.interrupt();
117 | logger.info("Stopped GitHub river.");
118 | }
119 |
120 | private class DataStream extends Thread {
121 | private volatile boolean isRunning;
122 |
123 | @Inject
124 | public DataStream() {
125 | super("DataStream thread");
126 | isRunning = true;
127 | }
128 |
129 | private boolean checkAndUpdateETag(HttpURLConnection conn) throws IOException {
130 | if (eventETag != null) {
131 | conn.setRequestProperty("If-None-Match", eventETag);
132 | }
133 |
134 | String xPollInterval = conn.getHeaderField("X-Poll-Interval");
135 | if (xPollInterval != null) {
136 | logger.debug("Next GitHub specified minimum polling interval is {} s", xPollInterval);
137 | pollInterval = Integer.parseInt(xPollInterval);
138 | }
139 |
140 | if (conn.getResponseCode() == 304) {
141 | logger.debug("304 {}", conn.getResponseMessage());
142 | return false;
143 | }
144 |
145 | String eTag = conn.getHeaderField("ETag");
146 | if (eTag != null) {
147 | logger.debug("New eTag: {}", eTag);
148 | eventETag = eTag;
149 | }
150 |
151 | return true;
152 | }
153 |
154 | private boolean indexResponse(HttpURLConnection conn, String type) {
155 | InputStream input;
156 | try {
157 | input = conn.getInputStream();
158 | } catch (IOException e) {
159 | logger.info("Exception encountered (403 usually is rate limit exceeded): ", e);
160 | return false;
161 | }
162 | JsonStreamParser jsp = new JsonStreamParser(new InputStreamReader(input));
163 |
164 | JsonArray array = (JsonArray) jsp.next();
165 |
166 | BulkProcessor bp = BulkProcessor.builder(client, new BulkProcessor.Listener() {
167 | @Override
168 | public void beforeBulk(long executionId, BulkRequest request) {
169 | }
170 |
171 | @Override
172 | public void afterBulk(long executionId, BulkRequest request, BulkResponse response) {
173 | }
174 |
175 | @Override
176 | public void afterBulk(long executionId, BulkRequest request, Throwable failure) {
177 | }
178 | }).build();
179 |
180 | boolean continueIndexing = true;
181 |
182 | IndexRequest req = null;
183 | for (JsonElement e: array) {
184 | if (type.equals("event")) {
185 | req = indexEvent(e);
186 | if (req == null) {
187 | continueIndexing = false;
188 | logger.debug("Found existing event, all remaining events has already been indexed");
189 | break;
190 | }
191 | } else if (type.equals("issue")) {
192 | req = indexOther(e, "IssueData", true);
193 | } else if (type.equals("pullreq")) {
194 | req = indexOther(e, "PullRequestData");
195 | } else if (type.equals("milestone")) {
196 | req = indexOther(e, "MilestoneData");
197 | } else if (type.equals("label")) {
198 | req = indexOther(e, "LabelData");
199 | } else if (type.equals("collaborator")) {
200 | req = indexOther(e, "CollaboratorData");
201 | }
202 | bp.add(req);
203 | }
204 | bp.close();
205 |
206 | try {
207 | input.close();
208 | } catch (IOException e) {
209 | logger.warn("Couldn't close connection?", e);
210 | }
211 |
212 | return continueIndexing;
213 | }
214 |
215 | private boolean isEventIndexed(String id) {
216 | return client.prepareGet(index, null, id).get().isExists();
217 | }
218 |
219 | private IndexRequest indexEvent(JsonElement e) {
220 | JsonObject obj = e.getAsJsonObject();
221 | String type = obj.get("type").getAsString();
222 | String id = obj.get("id").getAsString();
223 |
224 | if (isEventIndexed(id)) {
225 | return null;
226 | }
227 |
228 | IndexRequest req = new IndexRequest(index)
229 | .type(type)
230 | .id(id).create(false) // we want to overwrite old items
231 | .source(e.toString());
232 | return req;
233 | }
234 |
235 | private IndexRequest indexOther(JsonElement e, String type, boolean overwrite) {
236 | JsonObject obj = e.getAsJsonObject();
237 |
238 | // handle objects that don't have IDs (i.e. labels)
239 | // set the ID to the MD5 hash of the string representation
240 | String id;
241 | if (obj.has("id")) {
242 | id = obj.get("id").getAsString();
243 | } else {
244 | id = DigestUtils.md5Hex(e.toString());
245 | }
246 |
247 | IndexRequest req = new IndexRequest(index)
248 | .type(type)
249 | .id(id).create(!overwrite)
250 | .source(e.toString());
251 | return req;
252 | }
253 |
254 | private IndexRequest indexOther(JsonElement e, String type) {
255 | return indexOther(e, type, false);
256 | }
257 |
258 | private HashMap parseHeader(String header) {
259 | // inspired from https://github.com/uberVU/elasticboard/blob/4ccdfd8c8e772c1dda49a29a7487d14b8d820762/data_processor/github.py#L73
260 | Pattern p = Pattern.compile("\\<([a-z/0-9:\\.\\?_&=]+page=([0-9]+))\\>;\\s*rel=\\\"([a-z]+)\\\".*");
261 | Matcher m = p.matcher(header);
262 |
263 | if (!m.matches()) {
264 | return null;
265 | }
266 |
267 | HashMap data = new HashMap();
268 | data.put("url", m.group(1));
269 | data.put("page", m.group(2));
270 | data.put("rel", m.group(3));
271 |
272 | return data;
273 | }
274 |
275 | private boolean morePagesAvailable(URLConnection response) {
276 | String link = response.getHeaderField("link");
277 | if (link == null || link.length() == 0) {
278 | return false;
279 | }
280 |
281 | HashMap headerData = parseHeader(response.getHeaderField("link"));
282 | if (headerData == null) {
283 | return false;
284 | }
285 |
286 | String rel = headerData.get("rel");
287 | return rel.equals("next");
288 | }
289 |
290 | private String nextPageURL(URLConnection response) {
291 | HashMap headerData = parseHeader(response.getHeaderField("link"));
292 | if (headerData == null) {
293 | return null;
294 | }
295 | return headerData.get("url");
296 | }
297 |
298 | private void addAuthHeader(URLConnection connection) {
299 | if (username == null || password == null) {
300 | return;
301 | }
302 | String auth = String.format("%s:%s", username, password);
303 | String encoded = Base64.encodeBytes(auth.getBytes());
304 | connection.setRequestProperty("Authorization", "Basic " + encoded);
305 | }
306 |
307 | private boolean getData(String fmt, String type) {
308 | return getData(fmt, type, null);
309 | }
310 |
311 | private boolean getData(String fmt, String type, String since) {
312 | try {
313 | URL url;
314 | if (since != null) {
315 | url = new URL(String.format(fmt, owner, repository, since));
316 | } else {
317 | url = new URL(String.format(fmt, owner, repository));
318 | }
319 | HttpURLConnection connection = (HttpURLConnection) url.openConnection();
320 | addAuthHeader(connection);
321 | if (type.equals("event")) {
322 | boolean modified = checkAndUpdateETag(connection);
323 | if (!modified) {
324 | return false;
325 | }
326 | }
327 | boolean continueIndexing = indexResponse(connection, type);
328 |
329 | while (continueIndexing && morePagesAvailable(connection)) {
330 | url = new URL(nextPageURL(connection));
331 | connection = (HttpURLConnection) url.openConnection();
332 | addAuthHeader(connection);
333 | continueIndexing = indexResponse(connection, type);
334 | }
335 | } catch (Exception e) {
336 | logger.error("Exception in getData", e);
337 | }
338 |
339 | return true;
340 | }
341 |
342 | private void deleteByType(String type) {
343 | client.prepareDeleteByQuery(index)
344 | .setQuery(termQuery("_type", type))
345 | .execute()
346 | .actionGet();
347 | }
348 |
349 | /**
350 | * Gets the creation data of the single newest entry.
351 | *
352 | * @return ISO8601 formatted time of most recent entry, or null on empty or error.
353 | */
354 | private String getMostRecentEntry() {
355 | long totalEntries = client.prepareCount(index).setQuery(matchAllQuery()).execute().actionGet().getCount();
356 | if (totalEntries > 0) {
357 | FilteredQueryBuilder updatedAtQuery = QueryBuilders
358 | .filteredQuery(QueryBuilders.matchAllQuery(), FilterBuilders.existsFilter("created_at"));
359 | FieldSortBuilder updatedAtSort = SortBuilders.fieldSort("created_at").order(SortOrder.DESC);
360 |
361 | SearchResponse response = client.prepareSearch(index)
362 | .setQuery(updatedAtQuery)
363 | .addSort(updatedAtSort)
364 | .setSize(1)
365 | .execute()
366 | .actionGet();
367 |
368 | String createdAt = (String) response.getHits().getAt(0).getSource().get("created_at");
369 | logger.debug("Most recent event was created at {}", createdAt);
370 | return createdAt;
371 | } else {
372 | // getData will get all data on a null.
373 | logger.info("No existing entries, assuming first run");
374 | return null;
375 | }
376 | }
377 |
378 | @Override
379 | public void run() {
380 | while (isRunning) {
381 | // Must be read before getting new events.
382 | String mostRecentEntry = getMostRecentEntry();
383 |
384 | logger.debug("Checking for events");
385 | if (getData(endpoint + "/repos/%s/%s/events?per_page=1000",
386 | "event")) {
387 | logger.debug("First run or new events found, fetching rest of the data");
388 | if (mostRecentEntry != null) {
389 | getData(endpoint + "/repos/%s/%s/issues?state=all&per_page=1000&since=%s",
390 | "issue", mostRecentEntry);
391 | } else {
392 | getData(endpoint + "/repos/%s/%s/issues?state=all&per_page=1000",
393 | "issue");
394 | }
395 | // delete pull req data - we are only storing open pull reqs
396 | // and when a pull request is closed we have no way of knowing;
397 | // this is why we have to delete them and reindex "fresh" ones
398 | deleteByType("PullRequestData");
399 | getData(endpoint + "/repos/%s/%s/pulls", "pullreq");
400 |
401 | // same for milestones
402 | deleteByType("MilestoneData");
403 | getData(endpoint + "/repos/%s/%s/milestones?per_page=1000", "milestone");
404 |
405 | // collaborators
406 | deleteByType("CollaboratorData");
407 | getData(endpoint + "/repos/%s/%s/collaborators?per_page=1000", "collaborator");
408 |
409 | // and for labels - they have IDs based on the MD5 of the contents, so
410 | // if a property changes, we get a "new" document
411 | deleteByType("LabelData");
412 | getData(endpoint + "/repos/%s/%s/labels?per_page=1000", "label");
413 | } else {
414 | logger.debug("No new events found");
415 | }
416 | try {
417 | int waitTime = Math.max(pollInterval, userRequestedInterval) * 1000;
418 | logger.debug("Waiting {} ms before polling for new events", waitTime);
419 | Thread.sleep(waitTime); // needs milliseconds
420 | } catch (InterruptedException e) {
421 | logger.info("Wait interrupted, river was probably stopped");
422 | }
423 | }
424 | }
425 |
426 | public void setRunning(boolean running) {
427 | isRunning = running;
428 | }
429 | }
430 | }
431 |
--------------------------------------------------------------------------------