This repository has been archived by the owner on May 23, 2019. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathFarequote.java
348 lines (302 loc) · 12.7 KB
/
Farequote.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
/****************************************************************************
* *
* Copyright 2015-2016 Prelert Ltd *
* *
* Licensed under the Apache License, Version 2.0 (the "License"); *
* you may not use this file except in compliance with the License. *
* You may obtain a copy of the License at *
* *
* http://www.apache.org/licenses/LICENSE-2.0 *
* *
* Unless required by applicable law or agreed to in writing, software *
* distributed under the License is distributed on an "AS IS" BASIS, *
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. *
* See the License for the specific language governing permissions and *
* limitations under the License. *
* *
***************************************************************************/
package com.prelert.rs.examples;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.lang.IllegalStateException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import org.apache.log4j.ConsoleAppender;
import org.apache.log4j.Level;
import org.apache.log4j.Logger;
import org.apache.log4j.PatternLayout;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.ObjectWriter;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.prelert.job.AnalysisConfig;
import com.prelert.job.DataDescription;
import com.prelert.job.Detector;
import com.prelert.job.JobConfiguration;
import com.prelert.job.JobDetails;
import com.prelert.job.results.Bucket;
import com.prelert.rs.client.BucketRequestBuilder;
import com.prelert.rs.client.BucketsRequestBuilder;
import com.prelert.rs.client.EngineApiClient;
import com.prelert.rs.data.ApiError;
import com.prelert.rs.data.MultiDataPostResult;
import com.prelert.rs.data.Pagination;
import com.prelert.rs.data.SingleDocument;
/**
* Example of using the Prelert Engine API Java client.
*
* This class shows how to configure and create a new job,
* upload data for analysis and inspect the results. See
* <a href=https://github.com/prelert/engine-java/blob/master/README.md>
* https://github.com/prelert/engine-java/blob/master/README.md</a>
* for more details.
* <p>
* The data used in this example can be downloaded from
* <a href=http://s3.amazonaws.com/prelert_demo/farequote.csv>
* http://s3.amazonaws.com/prelert_demo/farequote.csv</a>
* the first 5 lines of which should resemble:<p>
* <code>
* time,airline,responsetime,sourcetype<br>
* 2014-06-23 00:00:00Z,AAL,132.2046,farequote<br>
* 2014-06-23 00:00:00Z,JZA,990.4628,farequote<br>
* 2014-06-23 00:00:00Z,JBU,877.5927,farequote<br>
* </code>
* <p>
* The <code>main</code> method takes 2 arguments - the path to farequote.csv
* and optionally the URL of the REST API. If the URL is not passed
* {@value #API_BASE_URL} is used.
*/
public class Farequote
{
/**
* The default base Url
*/
static final public String API_BASE_URL = "http://localhost:8080/engine/v2";
static final private Logger s_Logger = Logger.getLogger(Farequote.class);
/**
* Object to JSON mapper.
* Writes dates in ISO 8601 format
*/
static final private ObjectWriter s_ObjectWriter =
new ObjectMapper()
.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false)
.writer().withDefaultPrettyPrinter();
/**
* Create the job configuration for the farequote data set.
* The config has one detector set to analyze the field
* 'responsetime' by the field 'airline' using the 'metric'
* functions. The data is CSV format with a time field formatted
* as 2014-05-19 00:00:00+0000. Bucket span is set to 1 hour.
*
* @return The job configuration.
*/
static public JobConfiguration createFarequoteJobConfig()
{
// Configure a detector
Detector responseTimebyAirline = new Detector();
responseTimebyAirline.setFieldName("responsetime");
responseTimebyAirline.setByFieldName("airline");
responseTimebyAirline.setFunction(Detector.METRIC);
AnalysisConfig ac = new AnalysisConfig();
ac.setBucketSpan(3600L); // 3600 seconds = 1 hour
ac.setDetectors(Arrays.asList(responseTimebyAirline));
// Data is CSV format with time field such as 2014-05-19 00:00:00+0000
DataDescription dd = new DataDescription();
dd.setFormat(DataDescription.DataFormat.DELIMITED);
dd.setFieldDelimiter(',');
dd.setTimeField("time");
dd.setTimeFormat("yyyy-MM-dd HH:mm:ssX");
JobConfiguration jobConfig = new JobConfiguration();
jobConfig.setAnalysisConfig(ac);
jobConfig.setDataDescription(dd);
return jobConfig;
}
/**
* Check for the last error from the REST API and log if present.
*
* @param error The error to report, if <code>null</code> nothing
* is reported
*/
static public void reportApiErrorMessage(ApiError error)
{
if (error != null)
{
s_Logger.warn(error.toJson());
}
}
/**
* Print the CSV header for the bucket scores
*/
static public void printBucketScoresHeader()
{
System.out.println("Time, Anomaly Score, Unusual Score");
}
/**
* Print the bucket time, id and anomaly score to std out
* in CSV format.
*
* @param buckets The bucket results
*/
static public void printBucketScores(List<Bucket> buckets)
{
for (Bucket bucket : buckets)
{
System.out.println(String.format("%s,%f,%f",
bucket.getTimestamp().toString(),
bucket.getAnomalyScore(),
bucket.getMaxNormalizedProbability()));
}
}
/**
* Print the bucket as a JSON document.
*
* @throws JsonProcessingException
*/
static public void printBucket(Bucket bucket)
throws JsonProcessingException
{
System.out.println(s_ObjectWriter.writeValueAsString(bucket));
}
/**
* Create a new Engine API analytics job, upload data to it and
* print the results.
*
* @param args If set the first argument is the path to farequote.csv
* and must be set. The second argument is the Engine API Url if not set
* {@value #API_BASE_URL} is used.
*
* @throws IOException
*/
public static void main(String[] args)
throws IOException
{
// configure logging to console
ConsoleAppender console = new ConsoleAppender();
console.setLayout(new PatternLayout("%d [%p|%c|%C{1}] %m%n"));
console.setThreshold(Level.INFO);
console.activateOptions();
Logger.getRootLogger().addAppender(console);
if (args.length == 0)
{
System.out.println("This script expects at least one argument - "
+ "the path to farequote.csv. Download the file from "
+ "http://s3.amazonaws.com/prelert_demo/farequote.csv");
System.out.println("Usage: The first (mandatory) argument is the path to "
+ "farequote.csv the second (optional) argument is the API "
+ "Url, the default is " + API_BASE_URL);
return;
}
File dataFile = new File(args[0]);
FileInputStream fileStream;
try
{
fileStream = new FileInputStream(dataFile);
}
catch (FileNotFoundException e)
{
String msg = "Cannot find data file " + dataFile;
s_Logger.error(msg, e);
throw new IllegalStateException(msg);
}
String baseUrl = API_BASE_URL;
if (args.length > 1)
{
baseUrl = args[1];
}
// Create the job config
JobConfiguration jobConfig = Farequote.createFarequoteJobConfig();
try (EngineApiClient engineApiClient = new EngineApiClient(baseUrl))
{
String jobId = engineApiClient.createJob(jobConfig);
if (jobId == null || jobId.isEmpty())
{
String msg = "No Job Id returned by create job";
s_Logger.error(msg);
reportApiErrorMessage(engineApiClient.getLastError());
throw new IllegalStateException(msg);
}
// Review the job details
SingleDocument<JobDetails> jobDoc = engineApiClient.getJob(jobId);
if (jobDoc.isExists() == false)
{
// Strange, the job does not exist review any error messages
reportApiErrorMessage(engineApiClient.getLastError());
throw new IllegalStateException(engineApiClient.getLastError().toJson());
}
MultiDataPostResult uploadSummary = engineApiClient.streamingUpload(jobId, fileStream, false);
if (uploadSummary.getResponses().get(0).getError() != null)
{
String msg = "Failed to upload file to job " + jobId;
s_Logger.error(msg);
reportApiErrorMessage(uploadSummary.getResponses().get(0).getError());
throw new IllegalStateException(msg);
}
// commit the uploaded data and close the job.
engineApiClient.closeJob(jobId);
// results are available immediately after the close
BucketsRequestBuilder builder = new BucketsRequestBuilder(engineApiClient, jobId).take(100);
Pagination<Bucket> page = builder.get();
if (page.getDocumentCount() == 0 && engineApiClient.getLastError() == null)
{
String msg = "Error reading analysis results";
s_Logger.error(msg);
reportApiErrorMessage(engineApiClient.getLastError());
throw new IllegalStateException(msg);
}
// print
printBucketScoresHeader();
printBucketScores(page.getDocuments());
List<Bucket> allBuckets = new ArrayList<>(page.getDocuments());
int skip = page.getDocumentCount();
while (page.getNextPage() != null)
{
// get the next page of results
page = builder.skip(skip).get();
skip += page.getDocumentCount();
// or get next page using the next page URL, generic get and TypeReference
/*
page = engineApiClient.get(page.getNextPage().toString(),
new TypeReference<Pagination<Bucket>>() {});
*/
printBucketScores(page.getDocuments());
allBuckets.addAll(page.getDocuments());
}
// Sort by anomaly score
Collections.sort(allBuckets, new Comparator<Bucket>() {
@Override
public int compare(Bucket b1, Bucket b2)
{
return Double.compare(b2.getAnomalyScore(),
b1.getAnomalyScore());
}
});
if (allBuckets.size() > 0)
{
String bucketTime = String.valueOf(allBuckets.get(0).getEpoch());
// ask for the bucket and its anomaly records
SingleDocument<Bucket> bucket = new
BucketRequestBuilder(engineApiClient, jobId, bucketTime).expand(true).get();
if (bucket.isExists() == false)
{
// error, where has the bucket gone?
reportApiErrorMessage(engineApiClient.getLastError());
}
else
{
String msg = String.format(
"The bucket at time %1$TF %1$TT%1$Tz has the "
+ "largest anomaly score with a value of %2$f",
bucket.getDocument().getTimestamp(),
bucket.getDocument().getAnomalyScore());
System.out.println(msg);
printBucket(bucket.getDocument());
}
}
}
}
}