My favorites | Sign in
Project Home Downloads Source
Checkout   Browse   Changes    
 
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
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
/**
*
*/
package com.spatialkey.datapoller;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FilenameFilter;
import java.net.URL;
import java.net.URLEncoder;
import java.util.UUID;
import java.util.zip.Deflater;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

import org.apache.commons.httpclient.Header;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.multipart.FilePart;
import org.apache.commons.httpclient.methods.multipart.MultipartRequestEntity;
import org.apache.commons.httpclient.methods.multipart.Part;
import org.apache.commons.httpclient.params.HttpMethodParams;
import org.apache.log4j.Logger;
import org.dom4j.Document;
import org.dom4j.Node;
import org.dom4j.io.SAXReader;

import com.spatialkey.datapoller.communication.PollFTP;

/**
* Copyright (c) 2009 Universal Mind, Inc.
* @author Anthony McClure
* Date: May 8, 2009
* Time: 10:31:36 AM
*
* The DataPollingTask class will have one instantiation (by Spring configuration) for each "task" XML
* file in the spatialkey-datapoller.tasks directory.
*
* The scheduling engine will execute the run() method based on the CRON or SIMPLE scheduling defined
* in the XML file.
*
*/
public class DataPollingTask implements IScheduledPollingTask, IDataPollingTask {
private static Logger logger = Logger.getLogger("com.spatialkey.datapoller.DataPollingTask");

/*
* The following variables are set by Spring (the task definitions)
*/

/* IScheduledPublishingTask variables */
private long interval = 0; //Time in minutes for a simple scheduled task
private String taskType; //Should be set as "full" or "incremental" (what kind of DataImportAPI update)
private String scheduleType; //Should be either "cron" or "simple"
private String cronExpression; //If scheduleType is "cron", this is the cron expression to use
private String runAtStartup = "false"; //Used in a cron schedule. If set as true will execute the task at startup (useful for testing)
private String connectionType; //Currently should only be "ftp", can add additional connection types in the future

/* API variables */
private String taskName; //used in logging
private String skServiceURL; //if known, the cluster url that the SpatialKey Organization exists on
private String skUsername; //SpatialKey username used for import
private String skPassword; //SpatialKey password used for import
private String skOrganization; //The full SpatialKey organization name (abc.spatialkey.com)
private boolean runAsBackground = false; //If set to false, will wait until the entire dataset is imported for a response (otherwise will disconnect after the upload is complete)
private boolean notifyByEmail = false; //If set to true, and email will be sent to the user when the import is complete

/* FTP Connection Variables - Used when connectionType = "ftp" */
private String ftpHost; //the ftp host address/domain name
private int ftpPort = 21; //the ftp port
private String ftpUsername; //the ftp username
private String ftpPassword; //the ftp password
private boolean ftpDeleteFromRemote = false; //if set to true, will delete the .csv when complete (otherwise renames it so it does not get picked up again)

/* Run variables */
private boolean checkedRunAtStart = false;
private String jSessionID;
private String processingId;
private String outputDirectory;

/**
*
*/
public DataPollingTask() {
outputDirectory = "spatialkey-datapoller.out/";
}

/* (non-Javadoc)
* @see com.spatialkey.datapoller.IDataPollingTask#run()
*/
public void run() {
// This block is needed for double run checking at application start
if (checkedRunAtStart == false && scheduleType.toLowerCase().equals("simple"))
{
checkedRunAtStart = true;

if (runAtStartup.toLowerCase().equals("false"))
return;
}
else
checkedRunAtStart = true;

processingId = UUID.randomUUID().toString();

logger.info("["+ taskName + " - " + taskType + "] [run] Requesting file download...");

//check task type
boolean processFiles = false;

//if adding other connectionTypes (i.e. file watcher, database watcher, http, etc.) will need to add code here (and add vars as needed)
if (this.connectionType.toLowerCase().equals("ftp"))
{
PollFTP ftp = new PollFTP(this.ftpHost, this.ftpPort, this.ftpUsername, this.ftpPassword, this.ftpDeleteFromRemote);
processFiles = ftp.checkForFile(outputDirectory, processingId);
}

if (processFiles)
{
//zip files
this.zipPackage();

//upload data (must authenticate first, see API documentation)
boolean loggedIn = this.login();

if (! loggedIn)
return;

String uploaded = uploadZip((taskType.equals("full") ? true : false));

if (! uploaded.equals("ERROR")) {
logger.info("["+ taskName + " - " + taskType + "] [run] " + (taskType.equals("full") ? "Full" : "Incremental") + " update task finished.");
}

//remove any left over files
File dir = new File(outputDirectory);
FilenameFilter filter = new FilenameFilter() {
public boolean accept(File dir, String name) {
return name.startsWith(processingId);
}
};

for (File deleteThis : dir.listFiles(filter))
deleteThis.delete();
}
}

/**
* This method uploads the .zip file to the spatialkey server.
*
* @param overwrite If true, the dataset will be overwritten if it already exists.
*
* @return String response body or "ERROR"
*/
private String uploadZip(boolean overwrite) {
logger.info("["+ taskName + " - " + taskType + "] [uploadZip] Enter");

String ret = "";

try {
//check skServiceURL, look up if needed (will call a service to get the cluster url) - cached after first call
lookupClusterURL();

// Get target URL (see API documentation for URL information)
logger.info("["+ taskName + " - " + taskType + "] [uploadZip] About to connect to: " + skServiceURL + "/SpatialKeyFramework/dataImportAPI?action=" + (overwrite ? "overwrite" : "append"));
String strURL = skServiceURL + "/SpatialKeyFramework/dataImportAPI?action=" + (overwrite ? "overwrite" : "append") +
"&runAsBackground=" + (runAsBackground ? "true" : "false") + "&notifyByEmail=" + (notifyByEmail ? "true" : "false");

// Get file to be posted (uploading the .zip containing the .csv and .xml)
File input = new File(outputDirectory + processingId + ".zip");
// Prepare HTTP post
PostMethod post = new PostMethod(strURL);
post.getParams().setBooleanParameter(HttpMethodParams.USE_EXPECT_CONTINUE, true);
post.getParams().setSoTimeout(10000);

//create the file part
Part[] parts = {new FilePart(processingId + ".zip", input)};

// Request content will be retrieved directly
// from the input stream
post.setRequestEntity(new MultipartRequestEntity(parts, post.getParams()));

// set the JSESSIONID cookie - VERY IMPORTANT, needed so that the logged in user's session is used!
post.setRequestHeader("Cookie", jSessionID);
// Get HTTP client
HttpClient httpclient = new HttpClient();

// Execute request
try {
logger.info("["+ taskName + " - " + taskType + "] [uploadZip] Sending...");
int result = httpclient.executeMethod(post);

// Display response
logger.info("["+ taskName + " - " + taskType + "] [uploadZip] Server response '" + post.getResponseBodyAsString() + "'");
ret = post.getResponseBodyAsString();

if (result != HttpStatus.SC_OK)
throw new Exception("Upload failed: " + post.getStatusLine());
} finally {
// Release current connection to the connection pool once you are done
post.releaseConnection();
}
} catch (Exception e) {
logger.error("["+ taskName + " - " + taskType + "] [uploadZip] Error!",e);
return "ERROR";
}
logger.info("["+ taskName + " - " + taskType + "] [uploadZip] Exit");
return ret;
}

/**
* This method creates a .zip file that contains the .umg and .xml file.
*/
private void zipPackage() {
byte[] buffer = new byte[18024];
try{
ZipOutputStream out = new ZipOutputStream(new FileOutputStream(outputDirectory + processingId + ".zip"));
out.setLevel(Deflater.BEST_COMPRESSION);

// .csv file
String csvFile = processingId + ".csv";
FileInputStream in = new FileInputStream(outputDirectory + csvFile);
out.putNextEntry(new ZipEntry(csvFile));
int len;
while ((len = in.read(buffer)) > 0){
out.write(buffer, 0, len);
}
out.closeEntry();
in.close();
// .xml file
String xmlFile = processingId + ".xml";
in = new FileInputStream(outputDirectory + xmlFile);
out.putNextEntry(new ZipEntry(xmlFile));
while ((len = in.read(buffer)) > 0){
out.write(buffer, 0, len);
}
out.closeEntry();
in.close();
out.close();
logger.debug("["+ taskName + " - " + taskType + "] [zipPackage] '" + outputDirectory + processingId + ".zip' was created.");
} catch (Exception e) {
logger.error("["+ taskName + " - " + taskType + "] [zipPackage] Error!",e);
}
}

/**
* This method performs a login to the spatialkey server.
*
* @return True if the login was successful, otherwise false.
*/
private boolean login() {
try {
//check skServiceURL, look up if needed (will call a service to get the cluster url) - cached after first call
lookupClusterURL();

//check org url name (we only use the first portion of the domain name for authentication)
String nameOnly = null;
if (skOrganization.contains("."))
{
String[] splitOrg = skOrganization.split("\\.");
nameOnly = splitOrg[0];
}
else
nameOnly = skOrganization;

// set up the URL (see the DataImportAPI documentation for more information)
String hostPath = skServiceURL + "/SpatialKeyFramework/dataImportAPI";
String query = "?action=login&orgName=" + URLEncoder.encode(nameOnly,"UTF-8") + "&user=" + URLEncoder.encode(skUsername,"UTF-8") + "&password=" + URLEncoder.encode(skPassword,"UTF-8");

// set up the GET method
GetMethod get = new GetMethod(hostPath + query);

// Get HTTP client
HttpClient httpclient = new HttpClient();

// Execute login
try
{
int result = httpclient.executeMethod(get);

if (result != HttpStatus.SC_OK)
throw new Exception("Login failed: " + get.getStatusLine());

String response = get.getResponseBodyAsString();
logger.debug("["+ taskName + " - " + taskType + "] [login] server response: " + response);

//get the headers (need to find the JSESSIONID)
Header[] headers = get.getResponseHeaders("Set-Cookie");

boolean foundId = false;
for (Header header : headers)
{
//set cookie headers have multiple values, need to get the JSESSIONID one
if (header.toString().contains("JSESSIONID="))
{
jSessionID = header.getValue();
foundId = true;
}
}

if (! foundId)
throw new Exception("No JSESSIONID found in returned headers.");
}
finally
{
get.releaseConnection();
}
} catch (Exception e) {
logger.error("["+ taskName + " - " + taskType + "] [login] Error!",e);
return false;
}
return true;
}

private void lookupClusterURL() {
if (skServiceURL != null && skServiceURL.trim().length() > 0)
return;

String skOrgDomain = "";
//check org url name
if (skOrganization.contains("."))
skOrgDomain = skOrganization;
else
skOrgDomain = skOrganization + ".spatialkey.com";

Document xml;
try {
//get data as XML
URL url = new URL("http://" + skOrganization + "/clusterlookup.cfm");

SAXReader reader = new SAXReader();
xml = reader.read(url);
} catch (Exception e) {
logger.error("[lookupClusterURL] Lookup of domain: " + skOrgDomain + " returned an error: " + e.getMessage());
return;
}

//check for errors
Node error = xml.selectSingleNode("//error");
if (error.getText() != null && error.getText().trim().length() > 0)
{
logger.error("[lookupClusterURL] Lookup of domain: " + skOrgDomain + " returned an error: " + error.getText());
return;
}

Node cluster = xml.selectSingleNode("//cluster");
Node protocol = xml.selectSingleNode("//protocol");

if (protocol.getText() != null && protocol.getText().trim().length() > 0)
skServiceURL = protocol.getText().trim();
else
skServiceURL = "http://";

if (cluster.getText() != null && cluster.getText().trim().length() > 0)
skServiceURL += cluster.getText().trim();
else
{
skServiceURL = "";
logger.error("[lookupClusterURL] Lookup of domain: " + skOrgDomain + " returned without a cluster.");
}

logger.info("[lookupClusterURL] Lookup of domain: " + skOrgDomain + " returned with cluster url of: " + skServiceURL);
}

/* (non-Javadoc)
* @see com.spatialkey.datapoller.IScheduledPollingTask#getCronExpression()
*/
public String getCronExpression() {
return cronExpression;
}

/* (non-Javadoc)
* @see com.spatialkey.datapoller.IScheduledPollingTask#getInterval()
*/
public long getInterval() {
return interval;
}

/* (non-Javadoc)
* @see com.spatialkey.datapoller.IScheduledPollingTask#getRunAtStartup()
*/
public String getRunAtStartup() {
return runAtStartup;
}

/* (non-Javadoc)
* @see com.spatialkey.datapoller.IScheduledPollingTask#getScheduleType()
*/
public String getScheduleType() {
return scheduleType;
}

/* (non-Javadoc)
* @see com.spatialkey.datapoller.IScheduledPollingTask#getTaskType()
*/
public String getTaskType() {
return taskType;
}

/* (non-Javadoc)
* @see com.spatialkey.datapoller.IScheduledPollingTask#setCronExpression(java.lang.String)
*/
public void setCronExpression(String cronExpression) {
this.cronExpression = cronExpression;
}

/* (non-Javadoc)
* @see com.spatialkey.datapoller.IScheduledPollingTask#setInterval(long)
*/
public void setInterval(long interval) {
this.interval = interval;
}

/* (non-Javadoc)
* @see com.spatialkey.datapoller.IScheduledPollingTask#setRunAtStartup(java.lang.String)
*/
public void setRunAtStartup(String runAtStartup) {
this.runAtStartup = runAtStartup;
}

/* (non-Javadoc)
* @see com.spatialkey.datapoller.IScheduledPollingTask#setScheduleType(java.lang.String)
*/
public void setScheduleType(String scheduleType) {
this.scheduleType = scheduleType;
}

/* (non-Javadoc)
* @see com.spatialkey.datapoller.IScheduledPollingTask#setTaskType(java.lang.String)
*/
public void setTaskType(String taskType) {
this.taskType = taskType;
}

/**
* @return the outputDirectory
*/
public String getOutputDirectory() {
return outputDirectory;
}

/**
* @param outputDirectory the outputDirectory to set
*/
public void setOutputDirectory(String outputDirectory) {
this.outputDirectory = outputDirectory;
}

/**
* @return the checkedRunAtStart
*/
public boolean isCheckedRunAtStart() {
return checkedRunAtStart;
}

/**
* @param checkedRunAtStart the checkedRunAtStart to set
*/
public void setCheckedRunAtStart(boolean checkedRunAtStart) {
this.checkedRunAtStart = checkedRunAtStart;
}

/**
* @return the taskName
*/
public String getTaskName() {
return taskName;
}

/**
* @param datasetName the taskName to set
*/
public void setTaskName(String datasetName) {
this.taskName = datasetName;
}

/**
* @return the skServiceURL
*/
public String getSkServiceURL() {
return skServiceURL;
}

/**
* @param skServiceURL the skServiceURL to set
*/
public void setSkServiceURL(String skServiceURL) {
this.skServiceURL = skServiceURL;
}

/**
* @return the skUsername
*/
public String getSkUsername() {
return skUsername;
}

/**
* @param skUsername the skUsername to set
*/
public void setSkUsername(String skUsername) {
this.skUsername = skUsername;
}

/**
* @return the skPassword
*/
public String getSkPassword() {
return skPassword;
}

/**
* @param skPassword the skPassword to set
*/
public void setSkPassword(String skPassword) {
this.skPassword = skPassword;
}

/**
* @return the skOrganization
*/
public String getSkOrganization() {
return skOrganization;
}

/**
* @param skOrganization the skOrganization to set
*/
public void setSkOrganization(String skOrganization) {
this.skOrganization = skOrganization;
}

/**
* @return the connectionType
*/
public String getConnectionType() {
return connectionType;
}

/**
* @param connectionType the connectionType to set
*/
public void setConnectionType(String connectionType) {
this.connectionType = connectionType;
}

/**
* @return the ftpHost
*/
public String getFtpHost() {
return ftpHost;
}

/**
* @param ftpHost the ftpHost to set
*/
public void setFtpHost(String ftpHost) {
this.ftpHost = ftpHost;
}

/**
* @return the ftpUsername
*/
public String getFtpUsername() {
return ftpUsername;
}

/**
* @param ftpUsername the ftpUsername to set
*/
public void setFtpUsername(String ftpUsername) {
this.ftpUsername = ftpUsername;
}

/**
* @return the ftpPassword
*/
public String getFtpPassword() {
return ftpPassword;
}

/**
* @param ftpPassword the ftpPassword to set
*/
public void setFtpPassword(String ftpPassword) {
this.ftpPassword = ftpPassword;
}

/**
* @return the ftpPort
*/
public int getFtpPort() {
return ftpPort;
}

/**
* @param ftpPort the ftpPort to set
*/
public void setFtpPort(int ftpPort) {
this.ftpPort = ftpPort;
}

/**
* @return the deleteFromRemote
*/
public boolean isFtpDeleteFromRemote() {
return ftpDeleteFromRemote;
}
public boolean getFtpDeleteFromRemote() {
return ftpDeleteFromRemote;
}

/**
* @param ftpDeleteFromRemote the ftpDeleteFromRemote to set
*/
public void setFtpDeleteFromRemote(boolean ftpDeleteFromRemote) {
this.ftpDeleteFromRemote = ftpDeleteFromRemote;
}

/**
* @return the runAsBackground
*/
public boolean isRunAsBackground() {
return runAsBackground;
}
public boolean getRunAsBackground() {
return runAsBackground;
}

/**
* @param runAsBackground the runAsBackground to set
*/
public void setRunAsBackground(boolean runAsBackground) {
this.runAsBackground = runAsBackground;
}

/**
* @return the notifyByEmail
*/
public boolean isNotifyByEmail() {
return notifyByEmail;
}
public boolean getNotifyByEmail() {
return notifyByEmail;
}

/**
* @param notifyByEmail the notifyByEmail to set
*/
public void setNotifyByEmail(boolean notifyByEmail) {
this.notifyByEmail = notifyByEmail;
}

}

Change log

r3 by amcclure1 on May 14, 2009   Diff
Anthony McClure - 5-14-2009
Initial Code Push
Go to: 
Project members, sign in to write a code review

Older revisions

All revisions of this file

File info

Size: 19822 bytes, 655 lines
Powered by Google Project Hosting