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

    
132
def main():
133
    # Input
134
    env_names = []
135
    debug = opts.env_flag('debug', False, env_names)
136
    taxons = sys.argv[1:]
137
    if not taxons: raise SystemExit('Usage: '+opts.env_usage(env_names, True)
138
        +' '+sys.argv[0]+' taxon... >out 2>>log')
139
    
140
    tnrs_request(taxons, debug)
141

    
142
main()
(55-55/60)