Project

General

Profile

1
#!/usr/bin/env python
2
# A TNRS client
3
# When using xargs to pass many names, note that xargs will by default split its
4
# arguments into chunks of 5000. You can change this using the -n option.
5
# Note that obtaining an actual CSV requires four (!) steps: submit, retrieve,
6
# prepare download, and download. The output of the retrieve step is unusable
7
# because the array has different lengths depending on the taxonomic ranks
8
# present in the provided taxon name.
9

    
10
import os.path
11
import re
12
import sys
13
import time
14
import urllib2
15

    
16
sys.path.append(os.path.dirname(__file__)+"/../lib")
17

    
18
import opts
19
import streams
20
#import util
21

    
22
# Config
23
initial_pause = 0.35 # sec
24
pause_growth_factor = 1.3
25
max_pause = 600 # sec; = 10 min
26
assert initial_pause <= max_pause
27
max_taxons = 5000# according to http://tnrs.iplantcollaborative.org/TNRSapp.html
28

    
29
# Protocol params
30
url_base = 'http://tnrs.iplantcollaborative.org/tnrsdemo/'
31
url = url_base+'search'
32
initial_headers = {
33
    'Content-Type': 'text/x-gwt-rpc; charset=utf-8',
34
    'X-GWT-Module-Base': url_base,
35
    'X-GWT-Permutation': '574AA16D15D917C7704646FD92AFF6B3',
36
}
37
submission_request_template = ('7|0|7|'+url_base+
38
'||org.iplantc.tnrs.demo.client.SearchService|doSearch|\
39
java.lang.String/2004016611|{"sources":"gcc,tropicos,usda", "names":"[taxons]"\
40
, "type":"matching", "taxonomic":"true", "classification":"tropicos", \
41
"match_to_rank":"true"}|0.05|1|2|3|4|2|5|5|6|7|')
42
submission_response_pattern = r'^//OK\[1,\["(\w+)"\],0,7\]$'
43
retrieval_request_template = ('7|0|15|'+url_base+
44
'|1E87C78041CEFBF0992F46BDF84D7D60|org.iplantc.tnrs.demo.client.SearchService\
45
|getRemoteData|com.extjs.gxt.ui.client.data.PagingLoadConfig|\
46
java.lang.String/2004016611|com.extjs.gxt.ui.client.data.BasePagingLoadConfig/\
47
2011366567|com.extjs.gxt.ui.client.data.RpcMap/3441186752|sortField|sortDir|\
48
com.extjs.gxt.ui.client.Style$SortDir/640452531|offset|java.lang.Integer/\
49
3438268394|limit|{"email":"tnrs@lka5jjs.orv", "key":"[key]", \
50
"taxonomic_constraint":"false", "source_sorting":"false", "first":"false"}\
51
|1|2|3|4|2|5|6|7|0|1|8|4|9|0|10|11|0|12|13|0|14|13|100|15|')
52
retrieval_response_pattern = '^//OK\[.*?\["com.extjs.gxt.ui.client.data.\
53
BasePagingLoadResult/496878394","java.util.ArrayList/4159755760","org.iplantc.\
54
tnrs.demo.shared.BeanTNRSEntry/1039545748",".*"\],0,7\]$'
55
retrieval_response_info_pattern = r'(?ms).*^Set-Cookie: JSESSIONID=(\w+);'
56
download_request_template = ('7|0|6|'+url_base+
57
'|1E87C78041CEFBF0992F46BDF84D7D60|org.iplantc.tnrs.demo.client.SearchService|\
58
downloadRemoteResults|java.lang.String/2004016611|{"name":"tnrs_results.txt", \
59
"mode":"Best", "type":"Detailed", "encoding":"utf8", "dirty":"false", \
60
"sources":"false", "taxonomic":"false", "email":"tnrs@lka5jjs.orv", \
61
"key":"[key]"}|1|2|3|4|1|5|6|')
62
download_response_pattern = '^//OK\[1,\["(.*)"\],0,7\]$'
63
download_url_suffix = '&name=tnrs_results.txt&encoding=utf8'
64

    
65
def gwt_encode(str_): return re.sub(r'[^\w.() -]+', r' ', str_)
66

    
67
def parse_response(name, pattern, response):
68
    match = re.match(pattern, response)
69
    if not match: raise SystemExit('Invalid '+name+' response:\n'+response)
70
    return match.groups()
71

    
72
def main():
73
    # Input
74
    env_names = []
75
    debug = opts.env_flag('debug', False, env_names)
76
    taxons = sys.argv[1:]
77
    if not taxons: raise SystemExit('Usage: '+opts.env_usage(env_names, True)
78
        +' '+sys.argv[0]+' taxon... >out 2>>log')
79
    assert len(taxons) <= max_taxons
80
    
81
    # Logging
82
    def debug_log(label, str_=''):
83
        if debug: sys.stderr.write('\n'+label+':\n'+str_+'\n')
84
    
85
    ## HTTP
86
    headers = initial_headers
87
    
88
    def do_request(request=None, url=url, headers=headers):
89
        debug_log('request', str(request))
90
        response = urllib2.urlopen(urllib2.Request(url, request, headers))
91
        response_str = streams.read_all(response)
92
        response_info = str(response.info())
93
        debug_log('response info', response_info)
94
        debug_log('response str', response_str)
95
        return response_str, response_info
96
    
97
    def do_repeated_request(request):
98
        pause = initial_pause
99
        total_pause = 0
100
        while True:
101
            total_pause += pause
102
            if total_pause > max_pause: raise # error is not temporary
103
            debug_log('total_pause', str(total_pause)+'s')
104
            time.sleep(pause) # wait for job to complete
105
            
106
            try: return do_request(request)
107
            except urllib2.HTTPError: pass # try again
108
            pause *= pause_growth_factor
109
    
110
    debug_log('Submit')
111
    request = submission_request_template.replace('[taxons]',
112
        r'\\n'.join(map(gwt_encode, taxons))) # double-escape \n
113
    response, response_info = do_request(request)
114
    key, = parse_response('submission', submission_response_pattern, response)
115
    debug_log('key', key)
116
    key_enc = gwt_encode(key)
117
    
118
    debug_log('Retrieve')
119
    request = retrieval_request_template.replace('[key]', key_enc)
120
    response, response_info = do_repeated_request(request)
121
    parse_response('retrieval', retrieval_response_pattern, response)
122
    session_id, = parse_response('retrieval info',
123
        retrieval_response_info_pattern, response_info)
124
    debug_log('session_id', session_id)
125
    headers['Cookie'] = 'JSESSIONID='+session_id
126
    
127
    debug_log('Prepare download')
128
    request = download_request_template.replace('[key]', key_enc)
129
    response, response_info = do_request(request)
130
    csv_url, = parse_response('download', download_response_pattern, response)
131
    csv_url += download_url_suffix
132
    debug_log('csv_url', csv_url)
133
    
134
    debug_log('Download')
135
    response, response_info = do_request(url=csv_url, headers={})
136
    sys.stdout.write(response)
137

    
138
main()
(55-55/60)